xref: /openbmc/qemu/target/arm/helper.c (revision 00d1d29b768d920342c5e33cc56a9e0be596b2b4)
1 /*
2  * ARM generic helpers.
3  *
4  * This code is licensed under the GNU GPL v2 or later.
5  *
6  * SPDX-License-Identifier: GPL-2.0-or-later
7  */
8 
9 #include "qemu/osdep.h"
10 #include "qemu/units.h"
11 #include "target/arm/idau.h"
12 #include "trace.h"
13 #include "cpu.h"
14 #include "internals.h"
15 #include "exec/gdbstub.h"
16 #include "exec/helper-proto.h"
17 #include "qemu/host-utils.h"
18 #include "qemu/main-loop.h"
19 #include "qemu/bitops.h"
20 #include "qemu/crc32c.h"
21 #include "qemu/qemu-print.h"
22 #include "exec/exec-all.h"
23 #include <zlib.h> /* For crc32 */
24 #include "hw/irq.h"
25 #include "hw/semihosting/semihost.h"
26 #include "sysemu/cpus.h"
27 #include "sysemu/kvm.h"
28 #include "sysemu/tcg.h"
29 #include "qemu/range.h"
30 #include "qapi/qapi-commands-machine-target.h"
31 #include "qapi/error.h"
32 #include "qemu/guest-random.h"
33 #ifdef CONFIG_TCG
34 #include "arm_ldst.h"
35 #include "exec/cpu_ldst.h"
36 #endif
37 
38 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
39 
40 #ifndef CONFIG_USER_ONLY
41 
42 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
43                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
44                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
45                                target_ulong *page_size_ptr,
46                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
47 #endif
48 
49 static void switch_mode(CPUARMState *env, int mode);
50 
51 static int vfp_gdb_get_reg(CPUARMState *env, GByteArray *buf, int reg)
52 {
53     ARMCPU *cpu = env_archcpu(env);
54     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
55 
56     /* VFP data registers are always little-endian.  */
57     if (reg < nregs) {
58         return gdb_get_reg64(buf, *aa32_vfp_dreg(env, reg));
59     }
60     if (arm_feature(env, ARM_FEATURE_NEON)) {
61         /* Aliases for Q regs.  */
62         nregs += 16;
63         if (reg < nregs) {
64             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
65             return gdb_get_reg128(buf, q[0], q[1]);
66         }
67     }
68     switch (reg - nregs) {
69     case 0: return gdb_get_reg32(buf, env->vfp.xregs[ARM_VFP_FPSID]); break;
70     case 1: return gdb_get_reg32(buf, vfp_get_fpscr(env)); break;
71     case 2: return gdb_get_reg32(buf, env->vfp.xregs[ARM_VFP_FPEXC]); break;
72     }
73     return 0;
74 }
75 
76 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
77 {
78     ARMCPU *cpu = env_archcpu(env);
79     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
80 
81     if (reg < nregs) {
82         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
83         return 8;
84     }
85     if (arm_feature(env, ARM_FEATURE_NEON)) {
86         nregs += 16;
87         if (reg < nregs) {
88             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
89             q[0] = ldq_le_p(buf);
90             q[1] = ldq_le_p(buf + 8);
91             return 16;
92         }
93     }
94     switch (reg - nregs) {
95     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
96     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
97     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
98     }
99     return 0;
100 }
101 
102 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, GByteArray *buf, int reg)
103 {
104     switch (reg) {
105     case 0 ... 31:
106     {
107         /* 128 bit FP register - quads are in LE order */
108         uint64_t *q = aa64_vfp_qreg(env, reg);
109         return gdb_get_reg128(buf, q[1], q[0]);
110     }
111     case 32:
112         /* FPSR */
113         return gdb_get_reg32(buf, vfp_get_fpsr(env));
114     case 33:
115         /* FPCR */
116         return gdb_get_reg32(buf,vfp_get_fpcr(env));
117     default:
118         return 0;
119     }
120 }
121 
122 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
123 {
124     switch (reg) {
125     case 0 ... 31:
126         /* 128 bit FP register */
127         {
128             uint64_t *q = aa64_vfp_qreg(env, reg);
129             q[0] = ldq_le_p(buf);
130             q[1] = ldq_le_p(buf + 8);
131             return 16;
132         }
133     case 32:
134         /* FPSR */
135         vfp_set_fpsr(env, ldl_p(buf));
136         return 4;
137     case 33:
138         /* FPCR */
139         vfp_set_fpcr(env, ldl_p(buf));
140         return 4;
141     default:
142         return 0;
143     }
144 }
145 
146 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
147 {
148     assert(ri->fieldoffset);
149     if (cpreg_field_is_64bit(ri)) {
150         return CPREG_FIELD64(env, ri);
151     } else {
152         return CPREG_FIELD32(env, ri);
153     }
154 }
155 
156 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
157                       uint64_t value)
158 {
159     assert(ri->fieldoffset);
160     if (cpreg_field_is_64bit(ri)) {
161         CPREG_FIELD64(env, ri) = value;
162     } else {
163         CPREG_FIELD32(env, ri) = value;
164     }
165 }
166 
167 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
168 {
169     return (char *)env + ri->fieldoffset;
170 }
171 
172 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
173 {
174     /* Raw read of a coprocessor register (as needed for migration, etc). */
175     if (ri->type & ARM_CP_CONST) {
176         return ri->resetvalue;
177     } else if (ri->raw_readfn) {
178         return ri->raw_readfn(env, ri);
179     } else if (ri->readfn) {
180         return ri->readfn(env, ri);
181     } else {
182         return raw_read(env, ri);
183     }
184 }
185 
186 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
187                              uint64_t v)
188 {
189     /* Raw write of a coprocessor register (as needed for migration, etc).
190      * Note that constant registers are treated as write-ignored; the
191      * caller should check for success by whether a readback gives the
192      * value written.
193      */
194     if (ri->type & ARM_CP_CONST) {
195         return;
196     } else if (ri->raw_writefn) {
197         ri->raw_writefn(env, ri, v);
198     } else if (ri->writefn) {
199         ri->writefn(env, ri, v);
200     } else {
201         raw_write(env, ri, v);
202     }
203 }
204 
205 /**
206  * arm_get/set_gdb_*: get/set a gdb register
207  * @env: the CPU state
208  * @buf: a buffer to copy to/from
209  * @reg: register number (offset from start of group)
210  *
211  * We return the number of bytes copied
212  */
213 
214 static int arm_gdb_get_sysreg(CPUARMState *env, GByteArray *buf, int reg)
215 {
216     ARMCPU *cpu = env_archcpu(env);
217     const ARMCPRegInfo *ri;
218     uint32_t key;
219 
220     key = cpu->dyn_sysreg_xml.data.cpregs.keys[reg];
221     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
222     if (ri) {
223         if (cpreg_field_is_64bit(ri)) {
224             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
225         } else {
226             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
227         }
228     }
229     return 0;
230 }
231 
232 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
233 {
234     return 0;
235 }
236 
237 #ifdef TARGET_AARCH64
238 static int arm_gdb_get_svereg(CPUARMState *env, GByteArray *buf, int reg)
239 {
240     ARMCPU *cpu = env_archcpu(env);
241 
242     switch (reg) {
243     /* The first 32 registers are the zregs */
244     case 0 ... 31:
245     {
246         int vq, len = 0;
247         for (vq = 0; vq < cpu->sve_max_vq; vq++) {
248             len += gdb_get_reg128(buf,
249                                   env->vfp.zregs[reg].d[vq * 2 + 1],
250                                   env->vfp.zregs[reg].d[vq * 2]);
251         }
252         return len;
253     }
254     case 32:
255         return gdb_get_reg32(buf, vfp_get_fpsr(env));
256     case 33:
257         return gdb_get_reg32(buf, vfp_get_fpcr(env));
258     /* then 16 predicates and the ffr */
259     case 34 ... 50:
260     {
261         int preg = reg - 34;
262         int vq, len = 0;
263         for (vq = 0; vq < cpu->sve_max_vq; vq = vq + 4) {
264             len += gdb_get_reg64(buf, env->vfp.pregs[preg].p[vq / 4]);
265         }
266         return len;
267     }
268     case 51:
269     {
270         /*
271          * We report in Vector Granules (VG) which is 64bit in a Z reg
272          * while the ZCR works in Vector Quads (VQ) which is 128bit chunks.
273          */
274         int vq = sve_zcr_len_for_el(env, arm_current_el(env)) + 1;
275         return gdb_get_reg32(buf, vq * 2);
276     }
277     default:
278         /* gdbstub asked for something out our range */
279         qemu_log_mask(LOG_UNIMP, "%s: out of range register %d", __func__, reg);
280         break;
281     }
282 
283     return 0;
284 }
285 
286 static int arm_gdb_set_svereg(CPUARMState *env, uint8_t *buf, int reg)
287 {
288     ARMCPU *cpu = env_archcpu(env);
289 
290     /* The first 32 registers are the zregs */
291     switch (reg) {
292     /* The first 32 registers are the zregs */
293     case 0 ... 31:
294     {
295         int vq, len = 0;
296         uint64_t *p = (uint64_t *) buf;
297         for (vq = 0; vq < cpu->sve_max_vq; vq++) {
298             env->vfp.zregs[reg].d[vq * 2 + 1] = *p++;
299             env->vfp.zregs[reg].d[vq * 2] = *p++;
300             len += 16;
301         }
302         return len;
303     }
304     case 32:
305         vfp_set_fpsr(env, *(uint32_t *)buf);
306         return 4;
307     case 33:
308         vfp_set_fpcr(env, *(uint32_t *)buf);
309         return 4;
310     case 34 ... 50:
311     {
312         int preg = reg - 34;
313         int vq, len = 0;
314         uint64_t *p = (uint64_t *) buf;
315         for (vq = 0; vq < cpu->sve_max_vq; vq = vq + 4) {
316             env->vfp.pregs[preg].p[vq / 4] = *p++;
317             len += 8;
318         }
319         return len;
320     }
321     case 51:
322         /* cannot set vg via gdbstub */
323         return 0;
324     default:
325         /* gdbstub asked for something out our range */
326         break;
327     }
328 
329     return 0;
330 }
331 #endif /* TARGET_AARCH64 */
332 
333 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
334 {
335    /* Return true if the regdef would cause an assertion if you called
336     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
337     * program bug for it not to have the NO_RAW flag).
338     * NB that returning false here doesn't necessarily mean that calling
339     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
340     * read/write access functions which are safe for raw use" from "has
341     * read/write access functions which have side effects but has forgotten
342     * to provide raw access functions".
343     * The tests here line up with the conditions in read/write_raw_cp_reg()
344     * and assertions in raw_read()/raw_write().
345     */
346     if ((ri->type & ARM_CP_CONST) ||
347         ri->fieldoffset ||
348         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
349         return false;
350     }
351     return true;
352 }
353 
354 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
355 {
356     /* Write the coprocessor state from cpu->env to the (index,value) list. */
357     int i;
358     bool ok = true;
359 
360     for (i = 0; i < cpu->cpreg_array_len; i++) {
361         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
362         const ARMCPRegInfo *ri;
363         uint64_t newval;
364 
365         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
366         if (!ri) {
367             ok = false;
368             continue;
369         }
370         if (ri->type & ARM_CP_NO_RAW) {
371             continue;
372         }
373 
374         newval = read_raw_cp_reg(&cpu->env, ri);
375         if (kvm_sync) {
376             /*
377              * Only sync if the previous list->cpustate sync succeeded.
378              * Rather than tracking the success/failure state for every
379              * item in the list, we just recheck "does the raw write we must
380              * have made in write_list_to_cpustate() read back OK" here.
381              */
382             uint64_t oldval = cpu->cpreg_values[i];
383 
384             if (oldval == newval) {
385                 continue;
386             }
387 
388             write_raw_cp_reg(&cpu->env, ri, oldval);
389             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
390                 continue;
391             }
392 
393             write_raw_cp_reg(&cpu->env, ri, newval);
394         }
395         cpu->cpreg_values[i] = newval;
396     }
397     return ok;
398 }
399 
400 bool write_list_to_cpustate(ARMCPU *cpu)
401 {
402     int i;
403     bool ok = true;
404 
405     for (i = 0; i < cpu->cpreg_array_len; i++) {
406         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
407         uint64_t v = cpu->cpreg_values[i];
408         const ARMCPRegInfo *ri;
409 
410         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
411         if (!ri) {
412             ok = false;
413             continue;
414         }
415         if (ri->type & ARM_CP_NO_RAW) {
416             continue;
417         }
418         /* Write value and confirm it reads back as written
419          * (to catch read-only registers and partially read-only
420          * registers where the incoming migration value doesn't match)
421          */
422         write_raw_cp_reg(&cpu->env, ri, v);
423         if (read_raw_cp_reg(&cpu->env, ri) != v) {
424             ok = false;
425         }
426     }
427     return ok;
428 }
429 
430 static void add_cpreg_to_list(gpointer key, gpointer opaque)
431 {
432     ARMCPU *cpu = opaque;
433     uint64_t regidx;
434     const ARMCPRegInfo *ri;
435 
436     regidx = *(uint32_t *)key;
437     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
438 
439     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
440         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
441         /* The value array need not be initialized at this point */
442         cpu->cpreg_array_len++;
443     }
444 }
445 
446 static void count_cpreg(gpointer key, gpointer opaque)
447 {
448     ARMCPU *cpu = opaque;
449     uint64_t regidx;
450     const ARMCPRegInfo *ri;
451 
452     regidx = *(uint32_t *)key;
453     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
454 
455     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
456         cpu->cpreg_array_len++;
457     }
458 }
459 
460 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
461 {
462     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
463     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
464 
465     if (aidx > bidx) {
466         return 1;
467     }
468     if (aidx < bidx) {
469         return -1;
470     }
471     return 0;
472 }
473 
474 void init_cpreg_list(ARMCPU *cpu)
475 {
476     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
477      * Note that we require cpreg_tuples[] to be sorted by key ID.
478      */
479     GList *keys;
480     int arraylen;
481 
482     keys = g_hash_table_get_keys(cpu->cp_regs);
483     keys = g_list_sort(keys, cpreg_key_compare);
484 
485     cpu->cpreg_array_len = 0;
486 
487     g_list_foreach(keys, count_cpreg, cpu);
488 
489     arraylen = cpu->cpreg_array_len;
490     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
491     cpu->cpreg_values = g_new(uint64_t, arraylen);
492     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
493     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
494     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
495     cpu->cpreg_array_len = 0;
496 
497     g_list_foreach(keys, add_cpreg_to_list, cpu);
498 
499     assert(cpu->cpreg_array_len == arraylen);
500 
501     g_list_free(keys);
502 }
503 
504 /*
505  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
506  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
507  *
508  * access_el3_aa32ns: Used to check AArch32 register views.
509  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
510  */
511 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
512                                         const ARMCPRegInfo *ri,
513                                         bool isread)
514 {
515     bool secure = arm_is_secure_below_el3(env);
516 
517     assert(!arm_el_is_aa64(env, 3));
518     if (secure) {
519         return CP_ACCESS_TRAP_UNCATEGORIZED;
520     }
521     return CP_ACCESS_OK;
522 }
523 
524 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
525                                                 const ARMCPRegInfo *ri,
526                                                 bool isread)
527 {
528     if (!arm_el_is_aa64(env, 3)) {
529         return access_el3_aa32ns(env, ri, isread);
530     }
531     return CP_ACCESS_OK;
532 }
533 
534 /* Some secure-only AArch32 registers trap to EL3 if used from
535  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
536  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
537  * We assume that the .access field is set to PL1_RW.
538  */
539 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
540                                             const ARMCPRegInfo *ri,
541                                             bool isread)
542 {
543     if (arm_current_el(env) == 3) {
544         return CP_ACCESS_OK;
545     }
546     if (arm_is_secure_below_el3(env)) {
547         return CP_ACCESS_TRAP_EL3;
548     }
549     /* This will be EL1 NS and EL2 NS, which just UNDEF */
550     return CP_ACCESS_TRAP_UNCATEGORIZED;
551 }
552 
553 /* Check for traps to "powerdown debug" registers, which are controlled
554  * by MDCR.TDOSA
555  */
556 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
557                                    bool isread)
558 {
559     int el = arm_current_el(env);
560     bool mdcr_el2_tdosa = (env->cp15.mdcr_el2 & MDCR_TDOSA) ||
561         (env->cp15.mdcr_el2 & MDCR_TDE) ||
562         (arm_hcr_el2_eff(env) & HCR_TGE);
563 
564     if (el < 2 && mdcr_el2_tdosa && !arm_is_secure_below_el3(env)) {
565         return CP_ACCESS_TRAP_EL2;
566     }
567     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
568         return CP_ACCESS_TRAP_EL3;
569     }
570     return CP_ACCESS_OK;
571 }
572 
573 /* Check for traps to "debug ROM" registers, which are controlled
574  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
575  */
576 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
577                                   bool isread)
578 {
579     int el = arm_current_el(env);
580     bool mdcr_el2_tdra = (env->cp15.mdcr_el2 & MDCR_TDRA) ||
581         (env->cp15.mdcr_el2 & MDCR_TDE) ||
582         (arm_hcr_el2_eff(env) & HCR_TGE);
583 
584     if (el < 2 && mdcr_el2_tdra && !arm_is_secure_below_el3(env)) {
585         return CP_ACCESS_TRAP_EL2;
586     }
587     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
588         return CP_ACCESS_TRAP_EL3;
589     }
590     return CP_ACCESS_OK;
591 }
592 
593 /* Check for traps to general debug registers, which are controlled
594  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
595  */
596 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
597                                   bool isread)
598 {
599     int el = arm_current_el(env);
600     bool mdcr_el2_tda = (env->cp15.mdcr_el2 & MDCR_TDA) ||
601         (env->cp15.mdcr_el2 & MDCR_TDE) ||
602         (arm_hcr_el2_eff(env) & HCR_TGE);
603 
604     if (el < 2 && mdcr_el2_tda && !arm_is_secure_below_el3(env)) {
605         return CP_ACCESS_TRAP_EL2;
606     }
607     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
608         return CP_ACCESS_TRAP_EL3;
609     }
610     return CP_ACCESS_OK;
611 }
612 
613 /* Check for traps to performance monitor registers, which are controlled
614  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
615  */
616 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
617                                  bool isread)
618 {
619     int el = arm_current_el(env);
620 
621     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
622         && !arm_is_secure_below_el3(env)) {
623         return CP_ACCESS_TRAP_EL2;
624     }
625     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
626         return CP_ACCESS_TRAP_EL3;
627     }
628     return CP_ACCESS_OK;
629 }
630 
631 /* Check for traps from EL1 due to HCR_EL2.TVM and HCR_EL2.TRVM.  */
632 static CPAccessResult access_tvm_trvm(CPUARMState *env, const ARMCPRegInfo *ri,
633                                       bool isread)
634 {
635     if (arm_current_el(env) == 1) {
636         uint64_t trap = isread ? HCR_TRVM : HCR_TVM;
637         if (arm_hcr_el2_eff(env) & trap) {
638             return CP_ACCESS_TRAP_EL2;
639         }
640     }
641     return CP_ACCESS_OK;
642 }
643 
644 /* Check for traps from EL1 due to HCR_EL2.TSW.  */
645 static CPAccessResult access_tsw(CPUARMState *env, const ARMCPRegInfo *ri,
646                                  bool isread)
647 {
648     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TSW)) {
649         return CP_ACCESS_TRAP_EL2;
650     }
651     return CP_ACCESS_OK;
652 }
653 
654 /* Check for traps from EL1 due to HCR_EL2.TACR.  */
655 static CPAccessResult access_tacr(CPUARMState *env, const ARMCPRegInfo *ri,
656                                   bool isread)
657 {
658     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TACR)) {
659         return CP_ACCESS_TRAP_EL2;
660     }
661     return CP_ACCESS_OK;
662 }
663 
664 /* Check for traps from EL1 due to HCR_EL2.TTLB. */
665 static CPAccessResult access_ttlb(CPUARMState *env, const ARMCPRegInfo *ri,
666                                   bool isread)
667 {
668     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TTLB)) {
669         return CP_ACCESS_TRAP_EL2;
670     }
671     return CP_ACCESS_OK;
672 }
673 
674 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
675 {
676     ARMCPU *cpu = env_archcpu(env);
677 
678     raw_write(env, ri, value);
679     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
680 }
681 
682 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
683 {
684     ARMCPU *cpu = env_archcpu(env);
685 
686     if (raw_read(env, ri) != value) {
687         /* Unlike real hardware the qemu TLB uses virtual addresses,
688          * not modified virtual addresses, so this causes a TLB flush.
689          */
690         tlb_flush(CPU(cpu));
691         raw_write(env, ri, value);
692     }
693 }
694 
695 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
696                              uint64_t value)
697 {
698     ARMCPU *cpu = env_archcpu(env);
699 
700     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
701         && !extended_addresses_enabled(env)) {
702         /* For VMSA (when not using the LPAE long descriptor page table
703          * format) this register includes the ASID, so do a TLB flush.
704          * For PMSA it is purely a process ID and no action is needed.
705          */
706         tlb_flush(CPU(cpu));
707     }
708     raw_write(env, ri, value);
709 }
710 
711 /* IS variants of TLB operations must affect all cores */
712 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
713                              uint64_t value)
714 {
715     CPUState *cs = env_cpu(env);
716 
717     tlb_flush_all_cpus_synced(cs);
718 }
719 
720 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
721                              uint64_t value)
722 {
723     CPUState *cs = env_cpu(env);
724 
725     tlb_flush_all_cpus_synced(cs);
726 }
727 
728 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
729                              uint64_t value)
730 {
731     CPUState *cs = env_cpu(env);
732 
733     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
734 }
735 
736 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
737                              uint64_t value)
738 {
739     CPUState *cs = env_cpu(env);
740 
741     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
742 }
743 
744 /*
745  * Non-IS variants of TLB operations are upgraded to
746  * IS versions if we are at NS EL1 and HCR_EL2.FB is set to
747  * force broadcast of these operations.
748  */
749 static bool tlb_force_broadcast(CPUARMState *env)
750 {
751     return (env->cp15.hcr_el2 & HCR_FB) &&
752         arm_current_el(env) == 1 && arm_is_secure_below_el3(env);
753 }
754 
755 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
756                           uint64_t value)
757 {
758     /* Invalidate all (TLBIALL) */
759     CPUState *cs = env_cpu(env);
760 
761     if (tlb_force_broadcast(env)) {
762         tlb_flush_all_cpus_synced(cs);
763     } else {
764         tlb_flush(cs);
765     }
766 }
767 
768 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
769                           uint64_t value)
770 {
771     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
772     CPUState *cs = env_cpu(env);
773 
774     value &= TARGET_PAGE_MASK;
775     if (tlb_force_broadcast(env)) {
776         tlb_flush_page_all_cpus_synced(cs, value);
777     } else {
778         tlb_flush_page(cs, value);
779     }
780 }
781 
782 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
783                            uint64_t value)
784 {
785     /* Invalidate by ASID (TLBIASID) */
786     CPUState *cs = env_cpu(env);
787 
788     if (tlb_force_broadcast(env)) {
789         tlb_flush_all_cpus_synced(cs);
790     } else {
791         tlb_flush(cs);
792     }
793 }
794 
795 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
796                            uint64_t value)
797 {
798     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
799     CPUState *cs = env_cpu(env);
800 
801     value &= TARGET_PAGE_MASK;
802     if (tlb_force_broadcast(env)) {
803         tlb_flush_page_all_cpus_synced(cs, value);
804     } else {
805         tlb_flush_page(cs, value);
806     }
807 }
808 
809 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
810                                uint64_t value)
811 {
812     CPUState *cs = env_cpu(env);
813 
814     tlb_flush_by_mmuidx(cs,
815                         ARMMMUIdxBit_E10_1 |
816                         ARMMMUIdxBit_E10_1_PAN |
817                         ARMMMUIdxBit_E10_0 |
818                         ARMMMUIdxBit_Stage2);
819 }
820 
821 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
822                                   uint64_t value)
823 {
824     CPUState *cs = env_cpu(env);
825 
826     tlb_flush_by_mmuidx_all_cpus_synced(cs,
827                                         ARMMMUIdxBit_E10_1 |
828                                         ARMMMUIdxBit_E10_1_PAN |
829                                         ARMMMUIdxBit_E10_0 |
830                                         ARMMMUIdxBit_Stage2);
831 }
832 
833 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
834                             uint64_t value)
835 {
836     /* Invalidate by IPA. This has to invalidate any structures that
837      * contain only stage 2 translation information, but does not need
838      * to apply to structures that contain combined stage 1 and stage 2
839      * translation information.
840      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
841      */
842     CPUState *cs = env_cpu(env);
843     uint64_t pageaddr;
844 
845     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
846         return;
847     }
848 
849     pageaddr = sextract64(value << 12, 0, 40);
850 
851     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_Stage2);
852 }
853 
854 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
855                                uint64_t value)
856 {
857     CPUState *cs = env_cpu(env);
858     uint64_t pageaddr;
859 
860     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
861         return;
862     }
863 
864     pageaddr = sextract64(value << 12, 0, 40);
865 
866     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
867                                              ARMMMUIdxBit_Stage2);
868 }
869 
870 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
871                               uint64_t value)
872 {
873     CPUState *cs = env_cpu(env);
874 
875     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_E2);
876 }
877 
878 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
879                                  uint64_t value)
880 {
881     CPUState *cs = env_cpu(env);
882 
883     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_E2);
884 }
885 
886 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
887                               uint64_t value)
888 {
889     CPUState *cs = env_cpu(env);
890     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
891 
892     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_E2);
893 }
894 
895 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
896                                  uint64_t value)
897 {
898     CPUState *cs = env_cpu(env);
899     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
900 
901     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
902                                              ARMMMUIdxBit_E2);
903 }
904 
905 static const ARMCPRegInfo cp_reginfo[] = {
906     /* Define the secure and non-secure FCSE identifier CP registers
907      * separately because there is no secure bank in V8 (no _EL3).  This allows
908      * the secure register to be properly reset and migrated. There is also no
909      * v8 EL1 version of the register so the non-secure instance stands alone.
910      */
911     { .name = "FCSEIDR",
912       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
913       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
914       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
915       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
916     { .name = "FCSEIDR_S",
917       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
918       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
919       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
920       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
921     /* Define the secure and non-secure context identifier CP registers
922      * separately because there is no secure bank in V8 (no _EL3).  This allows
923      * the secure register to be properly reset and migrated.  In the
924      * non-secure case, the 32-bit register will have reset and migration
925      * disabled during registration as it is handled by the 64-bit instance.
926      */
927     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
928       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
929       .access = PL1_RW, .accessfn = access_tvm_trvm,
930       .secure = ARM_CP_SECSTATE_NS,
931       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
932       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
933     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
934       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
935       .access = PL1_RW, .accessfn = access_tvm_trvm,
936       .secure = ARM_CP_SECSTATE_S,
937       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
938       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
939     REGINFO_SENTINEL
940 };
941 
942 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
943     /* NB: Some of these registers exist in v8 but with more precise
944      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
945      */
946     /* MMU Domain access control / MPU write buffer control */
947     { .name = "DACR",
948       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
949       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
950       .writefn = dacr_write, .raw_writefn = raw_write,
951       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
952                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
953     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
954      * For v6 and v5, these mappings are overly broad.
955      */
956     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
957       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
958     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
959       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
960     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
961       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
962     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
963       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
964     /* Cache maintenance ops; some of this space may be overridden later. */
965     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
966       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
967       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
968     REGINFO_SENTINEL
969 };
970 
971 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
972     /* Not all pre-v6 cores implemented this WFI, so this is slightly
973      * over-broad.
974      */
975     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
976       .access = PL1_W, .type = ARM_CP_WFI },
977     REGINFO_SENTINEL
978 };
979 
980 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
981     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
982      * is UNPREDICTABLE; we choose to NOP as most implementations do).
983      */
984     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
985       .access = PL1_W, .type = ARM_CP_WFI },
986     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
987      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
988      * OMAPCP will override this space.
989      */
990     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
991       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
992       .resetvalue = 0 },
993     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
994       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
995       .resetvalue = 0 },
996     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
997     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
998       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
999       .resetvalue = 0 },
1000     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
1001      * implementing it as RAZ means the "debug architecture version" bits
1002      * will read as a reserved value, which should cause Linux to not try
1003      * to use the debug hardware.
1004      */
1005     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
1006       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
1007     /* MMU TLB control. Note that the wildcarding means we cover not just
1008      * the unified TLB ops but also the dside/iside/inner-shareable variants.
1009      */
1010     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
1011       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
1012       .type = ARM_CP_NO_RAW },
1013     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
1014       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
1015       .type = ARM_CP_NO_RAW },
1016     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
1017       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
1018       .type = ARM_CP_NO_RAW },
1019     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
1020       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
1021       .type = ARM_CP_NO_RAW },
1022     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
1023       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
1024     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
1025       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
1026     REGINFO_SENTINEL
1027 };
1028 
1029 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1030                         uint64_t value)
1031 {
1032     uint32_t mask = 0;
1033 
1034     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
1035     if (!arm_feature(env, ARM_FEATURE_V8)) {
1036         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
1037          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
1038          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
1039          */
1040         if (cpu_isar_feature(aa32_vfp_simd, env_archcpu(env))) {
1041             /* VFP coprocessor: cp10 & cp11 [23:20] */
1042             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
1043 
1044             if (!arm_feature(env, ARM_FEATURE_NEON)) {
1045                 /* ASEDIS [31] bit is RAO/WI */
1046                 value |= (1 << 31);
1047             }
1048 
1049             /* VFPv3 and upwards with NEON implement 32 double precision
1050              * registers (D0-D31).
1051              */
1052             if (!cpu_isar_feature(aa32_simd_r32, env_archcpu(env))) {
1053                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
1054                 value |= (1 << 30);
1055             }
1056         }
1057         value &= mask;
1058     }
1059 
1060     /*
1061      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
1062      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
1063      */
1064     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
1065         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
1066         value &= ~(0xf << 20);
1067         value |= env->cp15.cpacr_el1 & (0xf << 20);
1068     }
1069 
1070     env->cp15.cpacr_el1 = value;
1071 }
1072 
1073 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1074 {
1075     /*
1076      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
1077      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
1078      */
1079     uint64_t value = env->cp15.cpacr_el1;
1080 
1081     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
1082         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
1083         value &= ~(0xf << 20);
1084     }
1085     return value;
1086 }
1087 
1088 
1089 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1090 {
1091     /* Call cpacr_write() so that we reset with the correct RAO bits set
1092      * for our CPU features.
1093      */
1094     cpacr_write(env, ri, 0);
1095 }
1096 
1097 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1098                                    bool isread)
1099 {
1100     if (arm_feature(env, ARM_FEATURE_V8)) {
1101         /* Check if CPACR accesses are to be trapped to EL2 */
1102         if (arm_current_el(env) == 1 &&
1103             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
1104             return CP_ACCESS_TRAP_EL2;
1105         /* Check if CPACR accesses are to be trapped to EL3 */
1106         } else if (arm_current_el(env) < 3 &&
1107                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1108             return CP_ACCESS_TRAP_EL3;
1109         }
1110     }
1111 
1112     return CP_ACCESS_OK;
1113 }
1114 
1115 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1116                                   bool isread)
1117 {
1118     /* Check if CPTR accesses are set to trap to EL3 */
1119     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1120         return CP_ACCESS_TRAP_EL3;
1121     }
1122 
1123     return CP_ACCESS_OK;
1124 }
1125 
1126 static const ARMCPRegInfo v6_cp_reginfo[] = {
1127     /* prefetch by MVA in v6, NOP in v7 */
1128     { .name = "MVA_prefetch",
1129       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
1130       .access = PL1_W, .type = ARM_CP_NOP },
1131     /* We need to break the TB after ISB to execute self-modifying code
1132      * correctly and also to take any pending interrupts immediately.
1133      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
1134      */
1135     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
1136       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
1137     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
1138       .access = PL0_W, .type = ARM_CP_NOP },
1139     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
1140       .access = PL0_W, .type = ARM_CP_NOP },
1141     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
1142       .access = PL1_RW, .accessfn = access_tvm_trvm,
1143       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
1144                              offsetof(CPUARMState, cp15.ifar_ns) },
1145       .resetvalue = 0, },
1146     /* Watchpoint Fault Address Register : should actually only be present
1147      * for 1136, 1176, 11MPCore.
1148      */
1149     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
1150       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
1151     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
1152       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
1153       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
1154       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
1155     REGINFO_SENTINEL
1156 };
1157 
1158 /* Definitions for the PMU registers */
1159 #define PMCRN_MASK  0xf800
1160 #define PMCRN_SHIFT 11
1161 #define PMCRLC  0x40
1162 #define PMCRDP  0x20
1163 #define PMCRX   0x10
1164 #define PMCRD   0x8
1165 #define PMCRC   0x4
1166 #define PMCRP   0x2
1167 #define PMCRE   0x1
1168 /*
1169  * Mask of PMCR bits writeable by guest (not including WO bits like C, P,
1170  * which can be written as 1 to trigger behaviour but which stay RAZ).
1171  */
1172 #define PMCR_WRITEABLE_MASK (PMCRLC | PMCRDP | PMCRX | PMCRD | PMCRE)
1173 
1174 #define PMXEVTYPER_P          0x80000000
1175 #define PMXEVTYPER_U          0x40000000
1176 #define PMXEVTYPER_NSK        0x20000000
1177 #define PMXEVTYPER_NSU        0x10000000
1178 #define PMXEVTYPER_NSH        0x08000000
1179 #define PMXEVTYPER_M          0x04000000
1180 #define PMXEVTYPER_MT         0x02000000
1181 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1182 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1183                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1184                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1185                                PMXEVTYPER_EVTCOUNT)
1186 
1187 #define PMCCFILTR             0xf8000000
1188 #define PMCCFILTR_M           PMXEVTYPER_M
1189 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1190 
1191 static inline uint32_t pmu_num_counters(CPUARMState *env)
1192 {
1193   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1194 }
1195 
1196 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1197 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1198 {
1199   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1200 }
1201 
1202 typedef struct pm_event {
1203     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1204     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1205     bool (*supported)(CPUARMState *);
1206     /*
1207      * Retrieve the current count of the underlying event. The programmed
1208      * counters hold a difference from the return value from this function
1209      */
1210     uint64_t (*get_count)(CPUARMState *);
1211     /*
1212      * Return how many nanoseconds it will take (at a minimum) for count events
1213      * to occur. A negative value indicates the counter will never overflow, or
1214      * that the counter has otherwise arranged for the overflow bit to be set
1215      * and the PMU interrupt to be raised on overflow.
1216      */
1217     int64_t (*ns_per_count)(uint64_t);
1218 } pm_event;
1219 
1220 static bool event_always_supported(CPUARMState *env)
1221 {
1222     return true;
1223 }
1224 
1225 static uint64_t swinc_get_count(CPUARMState *env)
1226 {
1227     /*
1228      * SW_INCR events are written directly to the pmevcntr's by writes to
1229      * PMSWINC, so there is no underlying count maintained by the PMU itself
1230      */
1231     return 0;
1232 }
1233 
1234 static int64_t swinc_ns_per(uint64_t ignored)
1235 {
1236     return -1;
1237 }
1238 
1239 /*
1240  * Return the underlying cycle count for the PMU cycle counters. If we're in
1241  * usermode, simply return 0.
1242  */
1243 static uint64_t cycles_get_count(CPUARMState *env)
1244 {
1245 #ifndef CONFIG_USER_ONLY
1246     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1247                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1248 #else
1249     return cpu_get_host_ticks();
1250 #endif
1251 }
1252 
1253 #ifndef CONFIG_USER_ONLY
1254 static int64_t cycles_ns_per(uint64_t cycles)
1255 {
1256     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1257 }
1258 
1259 static bool instructions_supported(CPUARMState *env)
1260 {
1261     return use_icount == 1 /* Precise instruction counting */;
1262 }
1263 
1264 static uint64_t instructions_get_count(CPUARMState *env)
1265 {
1266     return (uint64_t)cpu_get_icount_raw();
1267 }
1268 
1269 static int64_t instructions_ns_per(uint64_t icount)
1270 {
1271     return cpu_icount_to_ns((int64_t)icount);
1272 }
1273 #endif
1274 
1275 static bool pmu_8_1_events_supported(CPUARMState *env)
1276 {
1277     /* For events which are supported in any v8.1 PMU */
1278     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
1279 }
1280 
1281 static bool pmu_8_4_events_supported(CPUARMState *env)
1282 {
1283     /* For events which are supported in any v8.1 PMU */
1284     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
1285 }
1286 
1287 static uint64_t zero_event_get_count(CPUARMState *env)
1288 {
1289     /* For events which on QEMU never fire, so their count is always zero */
1290     return 0;
1291 }
1292 
1293 static int64_t zero_event_ns_per(uint64_t cycles)
1294 {
1295     /* An event which never fires can never overflow */
1296     return -1;
1297 }
1298 
1299 static const pm_event pm_events[] = {
1300     { .number = 0x000, /* SW_INCR */
1301       .supported = event_always_supported,
1302       .get_count = swinc_get_count,
1303       .ns_per_count = swinc_ns_per,
1304     },
1305 #ifndef CONFIG_USER_ONLY
1306     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1307       .supported = instructions_supported,
1308       .get_count = instructions_get_count,
1309       .ns_per_count = instructions_ns_per,
1310     },
1311     { .number = 0x011, /* CPU_CYCLES, Cycle */
1312       .supported = event_always_supported,
1313       .get_count = cycles_get_count,
1314       .ns_per_count = cycles_ns_per,
1315     },
1316 #endif
1317     { .number = 0x023, /* STALL_FRONTEND */
1318       .supported = pmu_8_1_events_supported,
1319       .get_count = zero_event_get_count,
1320       .ns_per_count = zero_event_ns_per,
1321     },
1322     { .number = 0x024, /* STALL_BACKEND */
1323       .supported = pmu_8_1_events_supported,
1324       .get_count = zero_event_get_count,
1325       .ns_per_count = zero_event_ns_per,
1326     },
1327     { .number = 0x03c, /* STALL */
1328       .supported = pmu_8_4_events_supported,
1329       .get_count = zero_event_get_count,
1330       .ns_per_count = zero_event_ns_per,
1331     },
1332 };
1333 
1334 /*
1335  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1336  * events (i.e. the statistical profiling extension), this implementation
1337  * should first be updated to something sparse instead of the current
1338  * supported_event_map[] array.
1339  */
1340 #define MAX_EVENT_ID 0x3c
1341 #define UNSUPPORTED_EVENT UINT16_MAX
1342 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1343 
1344 /*
1345  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1346  * of ARM event numbers to indices in our pm_events array.
1347  *
1348  * Note: Events in the 0x40XX range are not currently supported.
1349  */
1350 void pmu_init(ARMCPU *cpu)
1351 {
1352     unsigned int i;
1353 
1354     /*
1355      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1356      * events to them
1357      */
1358     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1359         supported_event_map[i] = UNSUPPORTED_EVENT;
1360     }
1361     cpu->pmceid0 = 0;
1362     cpu->pmceid1 = 0;
1363 
1364     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1365         const pm_event *cnt = &pm_events[i];
1366         assert(cnt->number <= MAX_EVENT_ID);
1367         /* We do not currently support events in the 0x40xx range */
1368         assert(cnt->number <= 0x3f);
1369 
1370         if (cnt->supported(&cpu->env)) {
1371             supported_event_map[cnt->number] = i;
1372             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1373             if (cnt->number & 0x20) {
1374                 cpu->pmceid1 |= event_mask;
1375             } else {
1376                 cpu->pmceid0 |= event_mask;
1377             }
1378         }
1379     }
1380 }
1381 
1382 /*
1383  * Check at runtime whether a PMU event is supported for the current machine
1384  */
1385 static bool event_supported(uint16_t number)
1386 {
1387     if (number > MAX_EVENT_ID) {
1388         return false;
1389     }
1390     return supported_event_map[number] != UNSUPPORTED_EVENT;
1391 }
1392 
1393 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1394                                    bool isread)
1395 {
1396     /* Performance monitor registers user accessibility is controlled
1397      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1398      * trapping to EL2 or EL3 for other accesses.
1399      */
1400     int el = arm_current_el(env);
1401 
1402     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1403         return CP_ACCESS_TRAP;
1404     }
1405     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
1406         && !arm_is_secure_below_el3(env)) {
1407         return CP_ACCESS_TRAP_EL2;
1408     }
1409     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1410         return CP_ACCESS_TRAP_EL3;
1411     }
1412 
1413     return CP_ACCESS_OK;
1414 }
1415 
1416 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1417                                            const ARMCPRegInfo *ri,
1418                                            bool isread)
1419 {
1420     /* ER: event counter read trap control */
1421     if (arm_feature(env, ARM_FEATURE_V8)
1422         && arm_current_el(env) == 0
1423         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1424         && isread) {
1425         return CP_ACCESS_OK;
1426     }
1427 
1428     return pmreg_access(env, ri, isread);
1429 }
1430 
1431 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1432                                          const ARMCPRegInfo *ri,
1433                                          bool isread)
1434 {
1435     /* SW: software increment write trap control */
1436     if (arm_feature(env, ARM_FEATURE_V8)
1437         && arm_current_el(env) == 0
1438         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1439         && !isread) {
1440         return CP_ACCESS_OK;
1441     }
1442 
1443     return pmreg_access(env, ri, isread);
1444 }
1445 
1446 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1447                                         const ARMCPRegInfo *ri,
1448                                         bool isread)
1449 {
1450     /* ER: event counter read trap control */
1451     if (arm_feature(env, ARM_FEATURE_V8)
1452         && arm_current_el(env) == 0
1453         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1454         return CP_ACCESS_OK;
1455     }
1456 
1457     return pmreg_access(env, ri, isread);
1458 }
1459 
1460 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1461                                          const ARMCPRegInfo *ri,
1462                                          bool isread)
1463 {
1464     /* CR: cycle counter read trap control */
1465     if (arm_feature(env, ARM_FEATURE_V8)
1466         && arm_current_el(env) == 0
1467         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1468         && isread) {
1469         return CP_ACCESS_OK;
1470     }
1471 
1472     return pmreg_access(env, ri, isread);
1473 }
1474 
1475 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1476  * the current EL, security state, and register configuration.
1477  */
1478 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1479 {
1480     uint64_t filter;
1481     bool e, p, u, nsk, nsu, nsh, m;
1482     bool enabled, prohibited, filtered;
1483     bool secure = arm_is_secure(env);
1484     int el = arm_current_el(env);
1485     uint8_t hpmn = env->cp15.mdcr_el2 & MDCR_HPMN;
1486 
1487     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1488         return false;
1489     }
1490 
1491     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1492             (counter < hpmn || counter == 31)) {
1493         e = env->cp15.c9_pmcr & PMCRE;
1494     } else {
1495         e = env->cp15.mdcr_el2 & MDCR_HPME;
1496     }
1497     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1498 
1499     if (!secure) {
1500         if (el == 2 && (counter < hpmn || counter == 31)) {
1501             prohibited = env->cp15.mdcr_el2 & MDCR_HPMD;
1502         } else {
1503             prohibited = false;
1504         }
1505     } else {
1506         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1507            (env->cp15.mdcr_el3 & MDCR_SPME);
1508     }
1509 
1510     if (prohibited && counter == 31) {
1511         prohibited = env->cp15.c9_pmcr & PMCRDP;
1512     }
1513 
1514     if (counter == 31) {
1515         filter = env->cp15.pmccfiltr_el0;
1516     } else {
1517         filter = env->cp15.c14_pmevtyper[counter];
1518     }
1519 
1520     p   = filter & PMXEVTYPER_P;
1521     u   = filter & PMXEVTYPER_U;
1522     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1523     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1524     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1525     m   = arm_el_is_aa64(env, 1) &&
1526               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1527 
1528     if (el == 0) {
1529         filtered = secure ? u : u != nsu;
1530     } else if (el == 1) {
1531         filtered = secure ? p : p != nsk;
1532     } else if (el == 2) {
1533         filtered = !nsh;
1534     } else { /* EL3 */
1535         filtered = m != p;
1536     }
1537 
1538     if (counter != 31) {
1539         /*
1540          * If not checking PMCCNTR, ensure the counter is setup to an event we
1541          * support
1542          */
1543         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1544         if (!event_supported(event)) {
1545             return false;
1546         }
1547     }
1548 
1549     return enabled && !prohibited && !filtered;
1550 }
1551 
1552 static void pmu_update_irq(CPUARMState *env)
1553 {
1554     ARMCPU *cpu = env_archcpu(env);
1555     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1556             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1557 }
1558 
1559 /*
1560  * Ensure c15_ccnt is the guest-visible count so that operations such as
1561  * enabling/disabling the counter or filtering, modifying the count itself,
1562  * etc. can be done logically. This is essentially a no-op if the counter is
1563  * not enabled at the time of the call.
1564  */
1565 static void pmccntr_op_start(CPUARMState *env)
1566 {
1567     uint64_t cycles = cycles_get_count(env);
1568 
1569     if (pmu_counter_enabled(env, 31)) {
1570         uint64_t eff_cycles = cycles;
1571         if (env->cp15.c9_pmcr & PMCRD) {
1572             /* Increment once every 64 processor clock cycles */
1573             eff_cycles /= 64;
1574         }
1575 
1576         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1577 
1578         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1579                                  1ull << 63 : 1ull << 31;
1580         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1581             env->cp15.c9_pmovsr |= (1 << 31);
1582             pmu_update_irq(env);
1583         }
1584 
1585         env->cp15.c15_ccnt = new_pmccntr;
1586     }
1587     env->cp15.c15_ccnt_delta = cycles;
1588 }
1589 
1590 /*
1591  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1592  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1593  * pmccntr_op_start.
1594  */
1595 static void pmccntr_op_finish(CPUARMState *env)
1596 {
1597     if (pmu_counter_enabled(env, 31)) {
1598 #ifndef CONFIG_USER_ONLY
1599         /* Calculate when the counter will next overflow */
1600         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1601         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1602             remaining_cycles = (uint32_t)remaining_cycles;
1603         }
1604         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1605 
1606         if (overflow_in > 0) {
1607             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1608                 overflow_in;
1609             ARMCPU *cpu = env_archcpu(env);
1610             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1611         }
1612 #endif
1613 
1614         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1615         if (env->cp15.c9_pmcr & PMCRD) {
1616             /* Increment once every 64 processor clock cycles */
1617             prev_cycles /= 64;
1618         }
1619         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1620     }
1621 }
1622 
1623 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1624 {
1625 
1626     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1627     uint64_t count = 0;
1628     if (event_supported(event)) {
1629         uint16_t event_idx = supported_event_map[event];
1630         count = pm_events[event_idx].get_count(env);
1631     }
1632 
1633     if (pmu_counter_enabled(env, counter)) {
1634         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1635 
1636         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1637             env->cp15.c9_pmovsr |= (1 << counter);
1638             pmu_update_irq(env);
1639         }
1640         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1641     }
1642     env->cp15.c14_pmevcntr_delta[counter] = count;
1643 }
1644 
1645 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1646 {
1647     if (pmu_counter_enabled(env, counter)) {
1648 #ifndef CONFIG_USER_ONLY
1649         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1650         uint16_t event_idx = supported_event_map[event];
1651         uint64_t delta = UINT32_MAX -
1652             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1653         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1654 
1655         if (overflow_in > 0) {
1656             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1657                 overflow_in;
1658             ARMCPU *cpu = env_archcpu(env);
1659             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1660         }
1661 #endif
1662 
1663         env->cp15.c14_pmevcntr_delta[counter] -=
1664             env->cp15.c14_pmevcntr[counter];
1665     }
1666 }
1667 
1668 void pmu_op_start(CPUARMState *env)
1669 {
1670     unsigned int i;
1671     pmccntr_op_start(env);
1672     for (i = 0; i < pmu_num_counters(env); i++) {
1673         pmevcntr_op_start(env, i);
1674     }
1675 }
1676 
1677 void pmu_op_finish(CPUARMState *env)
1678 {
1679     unsigned int i;
1680     pmccntr_op_finish(env);
1681     for (i = 0; i < pmu_num_counters(env); i++) {
1682         pmevcntr_op_finish(env, i);
1683     }
1684 }
1685 
1686 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1687 {
1688     pmu_op_start(&cpu->env);
1689 }
1690 
1691 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1692 {
1693     pmu_op_finish(&cpu->env);
1694 }
1695 
1696 void arm_pmu_timer_cb(void *opaque)
1697 {
1698     ARMCPU *cpu = opaque;
1699 
1700     /*
1701      * Update all the counter values based on the current underlying counts,
1702      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1703      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1704      * counter may expire.
1705      */
1706     pmu_op_start(&cpu->env);
1707     pmu_op_finish(&cpu->env);
1708 }
1709 
1710 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1711                        uint64_t value)
1712 {
1713     pmu_op_start(env);
1714 
1715     if (value & PMCRC) {
1716         /* The counter has been reset */
1717         env->cp15.c15_ccnt = 0;
1718     }
1719 
1720     if (value & PMCRP) {
1721         unsigned int i;
1722         for (i = 0; i < pmu_num_counters(env); i++) {
1723             env->cp15.c14_pmevcntr[i] = 0;
1724         }
1725     }
1726 
1727     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1728     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1729 
1730     pmu_op_finish(env);
1731 }
1732 
1733 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1734                           uint64_t value)
1735 {
1736     unsigned int i;
1737     for (i = 0; i < pmu_num_counters(env); i++) {
1738         /* Increment a counter's count iff: */
1739         if ((value & (1 << i)) && /* counter's bit is set */
1740                 /* counter is enabled and not filtered */
1741                 pmu_counter_enabled(env, i) &&
1742                 /* counter is SW_INCR */
1743                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1744             pmevcntr_op_start(env, i);
1745 
1746             /*
1747              * Detect if this write causes an overflow since we can't predict
1748              * PMSWINC overflows like we can for other events
1749              */
1750             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1751 
1752             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1753                 env->cp15.c9_pmovsr |= (1 << i);
1754                 pmu_update_irq(env);
1755             }
1756 
1757             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1758 
1759             pmevcntr_op_finish(env, i);
1760         }
1761     }
1762 }
1763 
1764 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1765 {
1766     uint64_t ret;
1767     pmccntr_op_start(env);
1768     ret = env->cp15.c15_ccnt;
1769     pmccntr_op_finish(env);
1770     return ret;
1771 }
1772 
1773 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1774                          uint64_t value)
1775 {
1776     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1777      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1778      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1779      * accessed.
1780      */
1781     env->cp15.c9_pmselr = value & 0x1f;
1782 }
1783 
1784 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1785                         uint64_t value)
1786 {
1787     pmccntr_op_start(env);
1788     env->cp15.c15_ccnt = value;
1789     pmccntr_op_finish(env);
1790 }
1791 
1792 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1793                             uint64_t value)
1794 {
1795     uint64_t cur_val = pmccntr_read(env, NULL);
1796 
1797     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1798 }
1799 
1800 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1801                             uint64_t value)
1802 {
1803     pmccntr_op_start(env);
1804     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1805     pmccntr_op_finish(env);
1806 }
1807 
1808 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1809                             uint64_t value)
1810 {
1811     pmccntr_op_start(env);
1812     /* M is not accessible from AArch32 */
1813     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1814         (value & PMCCFILTR);
1815     pmccntr_op_finish(env);
1816 }
1817 
1818 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1819 {
1820     /* M is not visible in AArch32 */
1821     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1822 }
1823 
1824 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1825                             uint64_t value)
1826 {
1827     value &= pmu_counter_mask(env);
1828     env->cp15.c9_pmcnten |= value;
1829 }
1830 
1831 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1832                              uint64_t value)
1833 {
1834     value &= pmu_counter_mask(env);
1835     env->cp15.c9_pmcnten &= ~value;
1836 }
1837 
1838 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1839                          uint64_t value)
1840 {
1841     value &= pmu_counter_mask(env);
1842     env->cp15.c9_pmovsr &= ~value;
1843     pmu_update_irq(env);
1844 }
1845 
1846 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1847                          uint64_t value)
1848 {
1849     value &= pmu_counter_mask(env);
1850     env->cp15.c9_pmovsr |= value;
1851     pmu_update_irq(env);
1852 }
1853 
1854 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1855                              uint64_t value, const uint8_t counter)
1856 {
1857     if (counter == 31) {
1858         pmccfiltr_write(env, ri, value);
1859     } else if (counter < pmu_num_counters(env)) {
1860         pmevcntr_op_start(env, counter);
1861 
1862         /*
1863          * If this counter's event type is changing, store the current
1864          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1865          * pmevcntr_op_finish has the correct baseline when it converts back to
1866          * a delta.
1867          */
1868         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1869             PMXEVTYPER_EVTCOUNT;
1870         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1871         if (old_event != new_event) {
1872             uint64_t count = 0;
1873             if (event_supported(new_event)) {
1874                 uint16_t event_idx = supported_event_map[new_event];
1875                 count = pm_events[event_idx].get_count(env);
1876             }
1877             env->cp15.c14_pmevcntr_delta[counter] = count;
1878         }
1879 
1880         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1881         pmevcntr_op_finish(env, counter);
1882     }
1883     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1884      * PMSELR value is equal to or greater than the number of implemented
1885      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1886      */
1887 }
1888 
1889 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1890                                const uint8_t counter)
1891 {
1892     if (counter == 31) {
1893         return env->cp15.pmccfiltr_el0;
1894     } else if (counter < pmu_num_counters(env)) {
1895         return env->cp15.c14_pmevtyper[counter];
1896     } else {
1897       /*
1898        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1899        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1900        */
1901         return 0;
1902     }
1903 }
1904 
1905 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1906                               uint64_t value)
1907 {
1908     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1909     pmevtyper_write(env, ri, value, counter);
1910 }
1911 
1912 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1913                                uint64_t value)
1914 {
1915     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1916     env->cp15.c14_pmevtyper[counter] = value;
1917 
1918     /*
1919      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1920      * pmu_op_finish calls when loading saved state for a migration. Because
1921      * we're potentially updating the type of event here, the value written to
1922      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1923      * different counter type. Therefore, we need to set this value to the
1924      * current count for the counter type we're writing so that pmu_op_finish
1925      * has the correct count for its calculation.
1926      */
1927     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1928     if (event_supported(event)) {
1929         uint16_t event_idx = supported_event_map[event];
1930         env->cp15.c14_pmevcntr_delta[counter] =
1931             pm_events[event_idx].get_count(env);
1932     }
1933 }
1934 
1935 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1936 {
1937     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1938     return pmevtyper_read(env, ri, counter);
1939 }
1940 
1941 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1942                              uint64_t value)
1943 {
1944     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1945 }
1946 
1947 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1948 {
1949     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1950 }
1951 
1952 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1953                              uint64_t value, uint8_t counter)
1954 {
1955     if (counter < pmu_num_counters(env)) {
1956         pmevcntr_op_start(env, counter);
1957         env->cp15.c14_pmevcntr[counter] = value;
1958         pmevcntr_op_finish(env, counter);
1959     }
1960     /*
1961      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1962      * are CONSTRAINED UNPREDICTABLE.
1963      */
1964 }
1965 
1966 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1967                               uint8_t counter)
1968 {
1969     if (counter < pmu_num_counters(env)) {
1970         uint64_t ret;
1971         pmevcntr_op_start(env, counter);
1972         ret = env->cp15.c14_pmevcntr[counter];
1973         pmevcntr_op_finish(env, counter);
1974         return ret;
1975     } else {
1976       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1977        * are CONSTRAINED UNPREDICTABLE. */
1978         return 0;
1979     }
1980 }
1981 
1982 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1983                              uint64_t value)
1984 {
1985     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1986     pmevcntr_write(env, ri, value, counter);
1987 }
1988 
1989 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1990 {
1991     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1992     return pmevcntr_read(env, ri, counter);
1993 }
1994 
1995 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1996                              uint64_t value)
1997 {
1998     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1999     assert(counter < pmu_num_counters(env));
2000     env->cp15.c14_pmevcntr[counter] = value;
2001     pmevcntr_write(env, ri, value, counter);
2002 }
2003 
2004 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
2005 {
2006     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
2007     assert(counter < pmu_num_counters(env));
2008     return env->cp15.c14_pmevcntr[counter];
2009 }
2010 
2011 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2012                              uint64_t value)
2013 {
2014     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
2015 }
2016 
2017 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2018 {
2019     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
2020 }
2021 
2022 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2023                             uint64_t value)
2024 {
2025     if (arm_feature(env, ARM_FEATURE_V8)) {
2026         env->cp15.c9_pmuserenr = value & 0xf;
2027     } else {
2028         env->cp15.c9_pmuserenr = value & 1;
2029     }
2030 }
2031 
2032 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
2033                              uint64_t value)
2034 {
2035     /* We have no event counters so only the C bit can be changed */
2036     value &= pmu_counter_mask(env);
2037     env->cp15.c9_pminten |= value;
2038     pmu_update_irq(env);
2039 }
2040 
2041 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2042                              uint64_t value)
2043 {
2044     value &= pmu_counter_mask(env);
2045     env->cp15.c9_pminten &= ~value;
2046     pmu_update_irq(env);
2047 }
2048 
2049 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2050                        uint64_t value)
2051 {
2052     /* Note that even though the AArch64 view of this register has bits
2053      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
2054      * architectural requirements for bits which are RES0 only in some
2055      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
2056      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
2057      */
2058     raw_write(env, ri, value & ~0x1FULL);
2059 }
2060 
2061 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2062 {
2063     /* Begin with base v8.0 state.  */
2064     uint32_t valid_mask = 0x3fff;
2065     ARMCPU *cpu = env_archcpu(env);
2066 
2067     if (arm_el_is_aa64(env, 3)) {
2068         value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
2069         valid_mask &= ~SCR_NET;
2070     } else {
2071         valid_mask &= ~(SCR_RW | SCR_ST);
2072     }
2073 
2074     if (!arm_feature(env, ARM_FEATURE_EL2)) {
2075         valid_mask &= ~SCR_HCE;
2076 
2077         /* On ARMv7, SMD (or SCD as it is called in v7) is only
2078          * supported if EL2 exists. The bit is UNK/SBZP when
2079          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
2080          * when EL2 is unavailable.
2081          * On ARMv8, this bit is always available.
2082          */
2083         if (arm_feature(env, ARM_FEATURE_V7) &&
2084             !arm_feature(env, ARM_FEATURE_V8)) {
2085             valid_mask &= ~SCR_SMD;
2086         }
2087     }
2088     if (cpu_isar_feature(aa64_lor, cpu)) {
2089         valid_mask |= SCR_TLOR;
2090     }
2091     if (cpu_isar_feature(aa64_pauth, cpu)) {
2092         valid_mask |= SCR_API | SCR_APK;
2093     }
2094 
2095     /* Clear all-context RES0 bits.  */
2096     value &= valid_mask;
2097     raw_write(env, ri, value);
2098 }
2099 
2100 static CPAccessResult access_aa64_tid2(CPUARMState *env,
2101                                        const ARMCPRegInfo *ri,
2102                                        bool isread)
2103 {
2104     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
2105         return CP_ACCESS_TRAP_EL2;
2106     }
2107 
2108     return CP_ACCESS_OK;
2109 }
2110 
2111 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2112 {
2113     ARMCPU *cpu = env_archcpu(env);
2114 
2115     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
2116      * bank
2117      */
2118     uint32_t index = A32_BANKED_REG_GET(env, csselr,
2119                                         ri->secure & ARM_CP_SECSTATE_S);
2120 
2121     return cpu->ccsidr[index];
2122 }
2123 
2124 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2125                          uint64_t value)
2126 {
2127     raw_write(env, ri, value & 0xf);
2128 }
2129 
2130 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2131 {
2132     CPUState *cs = env_cpu(env);
2133     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
2134     uint64_t ret = 0;
2135     bool allow_virt = (arm_current_el(env) == 1 &&
2136                        (!arm_is_secure_below_el3(env) ||
2137                         (env->cp15.scr_el3 & SCR_EEL2)));
2138 
2139     if (allow_virt && (hcr_el2 & HCR_IMO)) {
2140         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
2141             ret |= CPSR_I;
2142         }
2143     } else {
2144         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
2145             ret |= CPSR_I;
2146         }
2147     }
2148 
2149     if (allow_virt && (hcr_el2 & HCR_FMO)) {
2150         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
2151             ret |= CPSR_F;
2152         }
2153     } else {
2154         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
2155             ret |= CPSR_F;
2156         }
2157     }
2158 
2159     /* External aborts are not possible in QEMU so A bit is always clear */
2160     return ret;
2161 }
2162 
2163 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2164                                        bool isread)
2165 {
2166     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
2167         return CP_ACCESS_TRAP_EL2;
2168     }
2169 
2170     return CP_ACCESS_OK;
2171 }
2172 
2173 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2174                                        bool isread)
2175 {
2176     if (arm_feature(env, ARM_FEATURE_V8)) {
2177         return access_aa64_tid1(env, ri, isread);
2178     }
2179 
2180     return CP_ACCESS_OK;
2181 }
2182 
2183 static const ARMCPRegInfo v7_cp_reginfo[] = {
2184     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
2185     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
2186       .access = PL1_W, .type = ARM_CP_NOP },
2187     /* Performance monitors are implementation defined in v7,
2188      * but with an ARM recommended set of registers, which we
2189      * follow.
2190      *
2191      * Performance registers fall into three categories:
2192      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
2193      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
2194      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
2195      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
2196      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
2197      */
2198     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
2199       .access = PL0_RW, .type = ARM_CP_ALIAS,
2200       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2201       .writefn = pmcntenset_write,
2202       .accessfn = pmreg_access,
2203       .raw_writefn = raw_write },
2204     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
2205       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
2206       .access = PL0_RW, .accessfn = pmreg_access,
2207       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
2208       .writefn = pmcntenset_write, .raw_writefn = raw_write },
2209     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
2210       .access = PL0_RW,
2211       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2212       .accessfn = pmreg_access,
2213       .writefn = pmcntenclr_write,
2214       .type = ARM_CP_ALIAS },
2215     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
2216       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
2217       .access = PL0_RW, .accessfn = pmreg_access,
2218       .type = ARM_CP_ALIAS,
2219       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
2220       .writefn = pmcntenclr_write },
2221     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2222       .access = PL0_RW, .type = ARM_CP_IO,
2223       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2224       .accessfn = pmreg_access,
2225       .writefn = pmovsr_write,
2226       .raw_writefn = raw_write },
2227     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2228       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2229       .access = PL0_RW, .accessfn = pmreg_access,
2230       .type = ARM_CP_ALIAS | ARM_CP_IO,
2231       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2232       .writefn = pmovsr_write,
2233       .raw_writefn = raw_write },
2234     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2235       .access = PL0_W, .accessfn = pmreg_access_swinc,
2236       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2237       .writefn = pmswinc_write },
2238     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2239       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2240       .access = PL0_W, .accessfn = pmreg_access_swinc,
2241       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2242       .writefn = pmswinc_write },
2243     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2244       .access = PL0_RW, .type = ARM_CP_ALIAS,
2245       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2246       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2247       .raw_writefn = raw_write},
2248     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2249       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2250       .access = PL0_RW, .accessfn = pmreg_access_selr,
2251       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2252       .writefn = pmselr_write, .raw_writefn = raw_write, },
2253     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2254       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2255       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2256       .accessfn = pmreg_access_ccntr },
2257     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2258       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2259       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2260       .type = ARM_CP_IO,
2261       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2262       .readfn = pmccntr_read, .writefn = pmccntr_write,
2263       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2264     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2265       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2266       .access = PL0_RW, .accessfn = pmreg_access,
2267       .type = ARM_CP_ALIAS | ARM_CP_IO,
2268       .resetvalue = 0, },
2269     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2270       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2271       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2272       .access = PL0_RW, .accessfn = pmreg_access,
2273       .type = ARM_CP_IO,
2274       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2275       .resetvalue = 0, },
2276     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2277       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2278       .accessfn = pmreg_access,
2279       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2280     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2281       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2282       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2283       .accessfn = pmreg_access,
2284       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2285     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2286       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2287       .accessfn = pmreg_access_xevcntr,
2288       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2289     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2290       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2291       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2292       .accessfn = pmreg_access_xevcntr,
2293       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2294     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2295       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2296       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2297       .resetvalue = 0,
2298       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2299     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2300       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2301       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2302       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2303       .resetvalue = 0,
2304       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2305     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2306       .access = PL1_RW, .accessfn = access_tpm,
2307       .type = ARM_CP_ALIAS | ARM_CP_IO,
2308       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2309       .resetvalue = 0,
2310       .writefn = pmintenset_write, .raw_writefn = raw_write },
2311     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2312       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2313       .access = PL1_RW, .accessfn = access_tpm,
2314       .type = ARM_CP_IO,
2315       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2316       .writefn = pmintenset_write, .raw_writefn = raw_write,
2317       .resetvalue = 0x0 },
2318     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2319       .access = PL1_RW, .accessfn = access_tpm,
2320       .type = ARM_CP_ALIAS | ARM_CP_IO,
2321       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2322       .writefn = pmintenclr_write, },
2323     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2324       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2325       .access = PL1_RW, .accessfn = access_tpm,
2326       .type = ARM_CP_ALIAS | ARM_CP_IO,
2327       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2328       .writefn = pmintenclr_write },
2329     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2330       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2331       .access = PL1_R,
2332       .accessfn = access_aa64_tid2,
2333       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2334     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2335       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2336       .access = PL1_RW,
2337       .accessfn = access_aa64_tid2,
2338       .writefn = csselr_write, .resetvalue = 0,
2339       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2340                              offsetof(CPUARMState, cp15.csselr_ns) } },
2341     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2342      * just RAZ for all cores:
2343      */
2344     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2345       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2346       .access = PL1_R, .type = ARM_CP_CONST,
2347       .accessfn = access_aa64_tid1,
2348       .resetvalue = 0 },
2349     /* Auxiliary fault status registers: these also are IMPDEF, and we
2350      * choose to RAZ/WI for all cores.
2351      */
2352     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2353       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2354       .access = PL1_RW, .accessfn = access_tvm_trvm,
2355       .type = ARM_CP_CONST, .resetvalue = 0 },
2356     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2357       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2358       .access = PL1_RW, .accessfn = access_tvm_trvm,
2359       .type = ARM_CP_CONST, .resetvalue = 0 },
2360     /* MAIR can just read-as-written because we don't implement caches
2361      * and so don't need to care about memory attributes.
2362      */
2363     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2364       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2365       .access = PL1_RW, .accessfn = access_tvm_trvm,
2366       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2367       .resetvalue = 0 },
2368     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2369       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2370       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2371       .resetvalue = 0 },
2372     /* For non-long-descriptor page tables these are PRRR and NMRR;
2373      * regardless they still act as reads-as-written for QEMU.
2374      */
2375      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2376       * allows them to assign the correct fieldoffset based on the endianness
2377       * handled in the field definitions.
2378       */
2379     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2380       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2381       .access = PL1_RW, .accessfn = access_tvm_trvm,
2382       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2383                              offsetof(CPUARMState, cp15.mair0_ns) },
2384       .resetfn = arm_cp_reset_ignore },
2385     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2386       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2387       .access = PL1_RW, .accessfn = access_tvm_trvm,
2388       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2389                              offsetof(CPUARMState, cp15.mair1_ns) },
2390       .resetfn = arm_cp_reset_ignore },
2391     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2392       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2393       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2394     /* 32 bit ITLB invalidates */
2395     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2396       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2397       .writefn = tlbiall_write },
2398     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2399       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2400       .writefn = tlbimva_write },
2401     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2402       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2403       .writefn = tlbiasid_write },
2404     /* 32 bit DTLB invalidates */
2405     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2406       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2407       .writefn = tlbiall_write },
2408     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2409       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2410       .writefn = tlbimva_write },
2411     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2412       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2413       .writefn = tlbiasid_write },
2414     /* 32 bit TLB invalidates */
2415     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2416       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2417       .writefn = tlbiall_write },
2418     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2419       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2420       .writefn = tlbimva_write },
2421     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2422       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2423       .writefn = tlbiasid_write },
2424     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2425       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2426       .writefn = tlbimvaa_write },
2427     REGINFO_SENTINEL
2428 };
2429 
2430 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2431     /* 32 bit TLB invalidates, Inner Shareable */
2432     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2433       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2434       .writefn = tlbiall_is_write },
2435     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2436       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2437       .writefn = tlbimva_is_write },
2438     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2439       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2440       .writefn = tlbiasid_is_write },
2441     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2442       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2443       .writefn = tlbimvaa_is_write },
2444     REGINFO_SENTINEL
2445 };
2446 
2447 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2448     /* PMOVSSET is not implemented in v7 before v7ve */
2449     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2450       .access = PL0_RW, .accessfn = pmreg_access,
2451       .type = ARM_CP_ALIAS | ARM_CP_IO,
2452       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2453       .writefn = pmovsset_write,
2454       .raw_writefn = raw_write },
2455     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2456       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2457       .access = PL0_RW, .accessfn = pmreg_access,
2458       .type = ARM_CP_ALIAS | ARM_CP_IO,
2459       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2460       .writefn = pmovsset_write,
2461       .raw_writefn = raw_write },
2462     REGINFO_SENTINEL
2463 };
2464 
2465 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2466                         uint64_t value)
2467 {
2468     value &= 1;
2469     env->teecr = value;
2470 }
2471 
2472 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2473                                     bool isread)
2474 {
2475     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2476         return CP_ACCESS_TRAP;
2477     }
2478     return CP_ACCESS_OK;
2479 }
2480 
2481 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2482     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2483       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2484       .resetvalue = 0,
2485       .writefn = teecr_write },
2486     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2487       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2488       .accessfn = teehbr_access, .resetvalue = 0 },
2489     REGINFO_SENTINEL
2490 };
2491 
2492 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2493     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2494       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2495       .access = PL0_RW,
2496       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2497     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2498       .access = PL0_RW,
2499       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2500                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2501       .resetfn = arm_cp_reset_ignore },
2502     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2503       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2504       .access = PL0_R|PL1_W,
2505       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2506       .resetvalue = 0},
2507     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2508       .access = PL0_R|PL1_W,
2509       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2510                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2511       .resetfn = arm_cp_reset_ignore },
2512     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2513       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2514       .access = PL1_RW,
2515       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2516     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2517       .access = PL1_RW,
2518       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2519                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2520       .resetvalue = 0 },
2521     REGINFO_SENTINEL
2522 };
2523 
2524 #ifndef CONFIG_USER_ONLY
2525 
2526 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2527                                        bool isread)
2528 {
2529     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2530      * Writable only at the highest implemented exception level.
2531      */
2532     int el = arm_current_el(env);
2533     uint64_t hcr;
2534     uint32_t cntkctl;
2535 
2536     switch (el) {
2537     case 0:
2538         hcr = arm_hcr_el2_eff(env);
2539         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2540             cntkctl = env->cp15.cnthctl_el2;
2541         } else {
2542             cntkctl = env->cp15.c14_cntkctl;
2543         }
2544         if (!extract32(cntkctl, 0, 2)) {
2545             return CP_ACCESS_TRAP;
2546         }
2547         break;
2548     case 1:
2549         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2550             arm_is_secure_below_el3(env)) {
2551             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2552             return CP_ACCESS_TRAP_UNCATEGORIZED;
2553         }
2554         break;
2555     case 2:
2556     case 3:
2557         break;
2558     }
2559 
2560     if (!isread && el < arm_highest_el(env)) {
2561         return CP_ACCESS_TRAP_UNCATEGORIZED;
2562     }
2563 
2564     return CP_ACCESS_OK;
2565 }
2566 
2567 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2568                                         bool isread)
2569 {
2570     unsigned int cur_el = arm_current_el(env);
2571     bool secure = arm_is_secure(env);
2572     uint64_t hcr = arm_hcr_el2_eff(env);
2573 
2574     switch (cur_el) {
2575     case 0:
2576         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2577         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2578             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2579                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2580         }
2581 
2582         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2583         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2584             return CP_ACCESS_TRAP;
2585         }
2586 
2587         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2588         if (hcr & HCR_E2H) {
2589             if (timeridx == GTIMER_PHYS &&
2590                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2591                 return CP_ACCESS_TRAP_EL2;
2592             }
2593         } else {
2594             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2595             if (arm_feature(env, ARM_FEATURE_EL2) &&
2596                 timeridx == GTIMER_PHYS && !secure &&
2597                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2598                 return CP_ACCESS_TRAP_EL2;
2599             }
2600         }
2601         break;
2602 
2603     case 1:
2604         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2605         if (arm_feature(env, ARM_FEATURE_EL2) &&
2606             timeridx == GTIMER_PHYS && !secure &&
2607             (hcr & HCR_E2H
2608              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2609              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2610             return CP_ACCESS_TRAP_EL2;
2611         }
2612         break;
2613     }
2614     return CP_ACCESS_OK;
2615 }
2616 
2617 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2618                                       bool isread)
2619 {
2620     unsigned int cur_el = arm_current_el(env);
2621     bool secure = arm_is_secure(env);
2622     uint64_t hcr = arm_hcr_el2_eff(env);
2623 
2624     switch (cur_el) {
2625     case 0:
2626         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2627             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2628             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2629                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2630         }
2631 
2632         /*
2633          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2634          * EL0 if EL0[PV]TEN is zero.
2635          */
2636         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2637             return CP_ACCESS_TRAP;
2638         }
2639         /* fall through */
2640 
2641     case 1:
2642         if (arm_feature(env, ARM_FEATURE_EL2) &&
2643             timeridx == GTIMER_PHYS && !secure) {
2644             if (hcr & HCR_E2H) {
2645                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2646                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2647                     return CP_ACCESS_TRAP_EL2;
2648                 }
2649             } else {
2650                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2651                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2652                     return CP_ACCESS_TRAP_EL2;
2653                 }
2654             }
2655         }
2656         break;
2657     }
2658     return CP_ACCESS_OK;
2659 }
2660 
2661 static CPAccessResult gt_pct_access(CPUARMState *env,
2662                                     const ARMCPRegInfo *ri,
2663                                     bool isread)
2664 {
2665     return gt_counter_access(env, GTIMER_PHYS, isread);
2666 }
2667 
2668 static CPAccessResult gt_vct_access(CPUARMState *env,
2669                                     const ARMCPRegInfo *ri,
2670                                     bool isread)
2671 {
2672     return gt_counter_access(env, GTIMER_VIRT, isread);
2673 }
2674 
2675 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2676                                        bool isread)
2677 {
2678     return gt_timer_access(env, GTIMER_PHYS, isread);
2679 }
2680 
2681 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2682                                        bool isread)
2683 {
2684     return gt_timer_access(env, GTIMER_VIRT, isread);
2685 }
2686 
2687 static CPAccessResult gt_stimer_access(CPUARMState *env,
2688                                        const ARMCPRegInfo *ri,
2689                                        bool isread)
2690 {
2691     /* The AArch64 register view of the secure physical timer is
2692      * always accessible from EL3, and configurably accessible from
2693      * Secure EL1.
2694      */
2695     switch (arm_current_el(env)) {
2696     case 1:
2697         if (!arm_is_secure(env)) {
2698             return CP_ACCESS_TRAP;
2699         }
2700         if (!(env->cp15.scr_el3 & SCR_ST)) {
2701             return CP_ACCESS_TRAP_EL3;
2702         }
2703         return CP_ACCESS_OK;
2704     case 0:
2705     case 2:
2706         return CP_ACCESS_TRAP;
2707     case 3:
2708         return CP_ACCESS_OK;
2709     default:
2710         g_assert_not_reached();
2711     }
2712 }
2713 
2714 static uint64_t gt_get_countervalue(CPUARMState *env)
2715 {
2716     ARMCPU *cpu = env_archcpu(env);
2717 
2718     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2719 }
2720 
2721 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2722 {
2723     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2724 
2725     if (gt->ctl & 1) {
2726         /* Timer enabled: calculate and set current ISTATUS, irq, and
2727          * reset timer to when ISTATUS next has to change
2728          */
2729         uint64_t offset = timeridx == GTIMER_VIRT ?
2730                                       cpu->env.cp15.cntvoff_el2 : 0;
2731         uint64_t count = gt_get_countervalue(&cpu->env);
2732         /* Note that this must be unsigned 64 bit arithmetic: */
2733         int istatus = count - offset >= gt->cval;
2734         uint64_t nexttick;
2735         int irqstate;
2736 
2737         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2738 
2739         irqstate = (istatus && !(gt->ctl & 2));
2740         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2741 
2742         if (istatus) {
2743             /* Next transition is when count rolls back over to zero */
2744             nexttick = UINT64_MAX;
2745         } else {
2746             /* Next transition is when we hit cval */
2747             nexttick = gt->cval + offset;
2748         }
2749         /* Note that the desired next expiry time might be beyond the
2750          * signed-64-bit range of a QEMUTimer -- in this case we just
2751          * set the timer for as far in the future as possible. When the
2752          * timer expires we will reset the timer for any remaining period.
2753          */
2754         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2755             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2756         } else {
2757             timer_mod(cpu->gt_timer[timeridx], nexttick);
2758         }
2759         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2760     } else {
2761         /* Timer disabled: ISTATUS and timer output always clear */
2762         gt->ctl &= ~4;
2763         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2764         timer_del(cpu->gt_timer[timeridx]);
2765         trace_arm_gt_recalc_disabled(timeridx);
2766     }
2767 }
2768 
2769 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2770                            int timeridx)
2771 {
2772     ARMCPU *cpu = env_archcpu(env);
2773 
2774     timer_del(cpu->gt_timer[timeridx]);
2775 }
2776 
2777 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2778 {
2779     return gt_get_countervalue(env);
2780 }
2781 
2782 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2783 {
2784     uint64_t hcr;
2785 
2786     switch (arm_current_el(env)) {
2787     case 2:
2788         hcr = arm_hcr_el2_eff(env);
2789         if (hcr & HCR_E2H) {
2790             return 0;
2791         }
2792         break;
2793     case 0:
2794         hcr = arm_hcr_el2_eff(env);
2795         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2796             return 0;
2797         }
2798         break;
2799     }
2800 
2801     return env->cp15.cntvoff_el2;
2802 }
2803 
2804 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2805 {
2806     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2807 }
2808 
2809 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2810                           int timeridx,
2811                           uint64_t value)
2812 {
2813     trace_arm_gt_cval_write(timeridx, value);
2814     env->cp15.c14_timer[timeridx].cval = value;
2815     gt_recalc_timer(env_archcpu(env), timeridx);
2816 }
2817 
2818 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2819                              int timeridx)
2820 {
2821     uint64_t offset = 0;
2822 
2823     switch (timeridx) {
2824     case GTIMER_VIRT:
2825     case GTIMER_HYPVIRT:
2826         offset = gt_virt_cnt_offset(env);
2827         break;
2828     }
2829 
2830     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2831                       (gt_get_countervalue(env) - offset));
2832 }
2833 
2834 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2835                           int timeridx,
2836                           uint64_t value)
2837 {
2838     uint64_t offset = 0;
2839 
2840     switch (timeridx) {
2841     case GTIMER_VIRT:
2842     case GTIMER_HYPVIRT:
2843         offset = gt_virt_cnt_offset(env);
2844         break;
2845     }
2846 
2847     trace_arm_gt_tval_write(timeridx, value);
2848     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2849                                          sextract64(value, 0, 32);
2850     gt_recalc_timer(env_archcpu(env), timeridx);
2851 }
2852 
2853 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2854                          int timeridx,
2855                          uint64_t value)
2856 {
2857     ARMCPU *cpu = env_archcpu(env);
2858     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2859 
2860     trace_arm_gt_ctl_write(timeridx, value);
2861     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2862     if ((oldval ^ value) & 1) {
2863         /* Enable toggled */
2864         gt_recalc_timer(cpu, timeridx);
2865     } else if ((oldval ^ value) & 2) {
2866         /* IMASK toggled: don't need to recalculate,
2867          * just set the interrupt line based on ISTATUS
2868          */
2869         int irqstate = (oldval & 4) && !(value & 2);
2870 
2871         trace_arm_gt_imask_toggle(timeridx, irqstate);
2872         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2873     }
2874 }
2875 
2876 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2877 {
2878     gt_timer_reset(env, ri, GTIMER_PHYS);
2879 }
2880 
2881 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2882                                uint64_t value)
2883 {
2884     gt_cval_write(env, ri, GTIMER_PHYS, value);
2885 }
2886 
2887 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2888 {
2889     return gt_tval_read(env, ri, GTIMER_PHYS);
2890 }
2891 
2892 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2893                                uint64_t value)
2894 {
2895     gt_tval_write(env, ri, GTIMER_PHYS, value);
2896 }
2897 
2898 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2899                               uint64_t value)
2900 {
2901     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2902 }
2903 
2904 static int gt_phys_redir_timeridx(CPUARMState *env)
2905 {
2906     switch (arm_mmu_idx(env)) {
2907     case ARMMMUIdx_E20_0:
2908     case ARMMMUIdx_E20_2:
2909     case ARMMMUIdx_E20_2_PAN:
2910         return GTIMER_HYP;
2911     default:
2912         return GTIMER_PHYS;
2913     }
2914 }
2915 
2916 static int gt_virt_redir_timeridx(CPUARMState *env)
2917 {
2918     switch (arm_mmu_idx(env)) {
2919     case ARMMMUIdx_E20_0:
2920     case ARMMMUIdx_E20_2:
2921     case ARMMMUIdx_E20_2_PAN:
2922         return GTIMER_HYPVIRT;
2923     default:
2924         return GTIMER_VIRT;
2925     }
2926 }
2927 
2928 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2929                                         const ARMCPRegInfo *ri)
2930 {
2931     int timeridx = gt_phys_redir_timeridx(env);
2932     return env->cp15.c14_timer[timeridx].cval;
2933 }
2934 
2935 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2936                                      uint64_t value)
2937 {
2938     int timeridx = gt_phys_redir_timeridx(env);
2939     gt_cval_write(env, ri, timeridx, value);
2940 }
2941 
2942 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2943                                         const ARMCPRegInfo *ri)
2944 {
2945     int timeridx = gt_phys_redir_timeridx(env);
2946     return gt_tval_read(env, ri, timeridx);
2947 }
2948 
2949 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2950                                      uint64_t value)
2951 {
2952     int timeridx = gt_phys_redir_timeridx(env);
2953     gt_tval_write(env, ri, timeridx, value);
2954 }
2955 
2956 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2957                                        const ARMCPRegInfo *ri)
2958 {
2959     int timeridx = gt_phys_redir_timeridx(env);
2960     return env->cp15.c14_timer[timeridx].ctl;
2961 }
2962 
2963 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2964                                     uint64_t value)
2965 {
2966     int timeridx = gt_phys_redir_timeridx(env);
2967     gt_ctl_write(env, ri, timeridx, value);
2968 }
2969 
2970 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2971 {
2972     gt_timer_reset(env, ri, GTIMER_VIRT);
2973 }
2974 
2975 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2976                                uint64_t value)
2977 {
2978     gt_cval_write(env, ri, GTIMER_VIRT, value);
2979 }
2980 
2981 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2982 {
2983     return gt_tval_read(env, ri, GTIMER_VIRT);
2984 }
2985 
2986 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2987                                uint64_t value)
2988 {
2989     gt_tval_write(env, ri, GTIMER_VIRT, value);
2990 }
2991 
2992 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2993                               uint64_t value)
2994 {
2995     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2996 }
2997 
2998 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2999                               uint64_t value)
3000 {
3001     ARMCPU *cpu = env_archcpu(env);
3002 
3003     trace_arm_gt_cntvoff_write(value);
3004     raw_write(env, ri, value);
3005     gt_recalc_timer(cpu, GTIMER_VIRT);
3006 }
3007 
3008 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
3009                                         const ARMCPRegInfo *ri)
3010 {
3011     int timeridx = gt_virt_redir_timeridx(env);
3012     return env->cp15.c14_timer[timeridx].cval;
3013 }
3014 
3015 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3016                                      uint64_t value)
3017 {
3018     int timeridx = gt_virt_redir_timeridx(env);
3019     gt_cval_write(env, ri, timeridx, value);
3020 }
3021 
3022 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
3023                                         const ARMCPRegInfo *ri)
3024 {
3025     int timeridx = gt_virt_redir_timeridx(env);
3026     return gt_tval_read(env, ri, timeridx);
3027 }
3028 
3029 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3030                                      uint64_t value)
3031 {
3032     int timeridx = gt_virt_redir_timeridx(env);
3033     gt_tval_write(env, ri, timeridx, value);
3034 }
3035 
3036 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
3037                                        const ARMCPRegInfo *ri)
3038 {
3039     int timeridx = gt_virt_redir_timeridx(env);
3040     return env->cp15.c14_timer[timeridx].ctl;
3041 }
3042 
3043 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3044                                     uint64_t value)
3045 {
3046     int timeridx = gt_virt_redir_timeridx(env);
3047     gt_ctl_write(env, ri, timeridx, value);
3048 }
3049 
3050 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3051 {
3052     gt_timer_reset(env, ri, GTIMER_HYP);
3053 }
3054 
3055 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3056                               uint64_t value)
3057 {
3058     gt_cval_write(env, ri, GTIMER_HYP, value);
3059 }
3060 
3061 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3062 {
3063     return gt_tval_read(env, ri, GTIMER_HYP);
3064 }
3065 
3066 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3067                               uint64_t value)
3068 {
3069     gt_tval_write(env, ri, GTIMER_HYP, value);
3070 }
3071 
3072 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3073                               uint64_t value)
3074 {
3075     gt_ctl_write(env, ri, GTIMER_HYP, value);
3076 }
3077 
3078 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3079 {
3080     gt_timer_reset(env, ri, GTIMER_SEC);
3081 }
3082 
3083 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3084                               uint64_t value)
3085 {
3086     gt_cval_write(env, ri, GTIMER_SEC, value);
3087 }
3088 
3089 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3090 {
3091     return gt_tval_read(env, ri, GTIMER_SEC);
3092 }
3093 
3094 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3095                               uint64_t value)
3096 {
3097     gt_tval_write(env, ri, GTIMER_SEC, value);
3098 }
3099 
3100 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3101                               uint64_t value)
3102 {
3103     gt_ctl_write(env, ri, GTIMER_SEC, value);
3104 }
3105 
3106 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3107 {
3108     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
3109 }
3110 
3111 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3112                              uint64_t value)
3113 {
3114     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
3115 }
3116 
3117 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3118 {
3119     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
3120 }
3121 
3122 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3123                              uint64_t value)
3124 {
3125     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
3126 }
3127 
3128 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3129                             uint64_t value)
3130 {
3131     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
3132 }
3133 
3134 void arm_gt_ptimer_cb(void *opaque)
3135 {
3136     ARMCPU *cpu = opaque;
3137 
3138     gt_recalc_timer(cpu, GTIMER_PHYS);
3139 }
3140 
3141 void arm_gt_vtimer_cb(void *opaque)
3142 {
3143     ARMCPU *cpu = opaque;
3144 
3145     gt_recalc_timer(cpu, GTIMER_VIRT);
3146 }
3147 
3148 void arm_gt_htimer_cb(void *opaque)
3149 {
3150     ARMCPU *cpu = opaque;
3151 
3152     gt_recalc_timer(cpu, GTIMER_HYP);
3153 }
3154 
3155 void arm_gt_stimer_cb(void *opaque)
3156 {
3157     ARMCPU *cpu = opaque;
3158 
3159     gt_recalc_timer(cpu, GTIMER_SEC);
3160 }
3161 
3162 void arm_gt_hvtimer_cb(void *opaque)
3163 {
3164     ARMCPU *cpu = opaque;
3165 
3166     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
3167 }
3168 
3169 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
3170 {
3171     ARMCPU *cpu = env_archcpu(env);
3172 
3173     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
3174 }
3175 
3176 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3177     /* Note that CNTFRQ is purely reads-as-written for the benefit
3178      * of software; writing it doesn't actually change the timer frequency.
3179      * Our reset value matches the fixed frequency we implement the timer at.
3180      */
3181     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
3182       .type = ARM_CP_ALIAS,
3183       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3184       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
3185     },
3186     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3187       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3188       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3189       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3190       .resetfn = arm_gt_cntfrq_reset,
3191     },
3192     /* overall control: mostly access permissions */
3193     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
3194       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
3195       .access = PL1_RW,
3196       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
3197       .resetvalue = 0,
3198     },
3199     /* per-timer control */
3200     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3201       .secure = ARM_CP_SECSTATE_NS,
3202       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3203       .accessfn = gt_ptimer_access,
3204       .fieldoffset = offsetoflow32(CPUARMState,
3205                                    cp15.c14_timer[GTIMER_PHYS].ctl),
3206       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3207       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3208     },
3209     { .name = "CNTP_CTL_S",
3210       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3211       .secure = ARM_CP_SECSTATE_S,
3212       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3213       .accessfn = gt_ptimer_access,
3214       .fieldoffset = offsetoflow32(CPUARMState,
3215                                    cp15.c14_timer[GTIMER_SEC].ctl),
3216       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3217     },
3218     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
3219       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
3220       .type = ARM_CP_IO, .access = PL0_RW,
3221       .accessfn = gt_ptimer_access,
3222       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
3223       .resetvalue = 0,
3224       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3225       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3226     },
3227     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
3228       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3229       .accessfn = gt_vtimer_access,
3230       .fieldoffset = offsetoflow32(CPUARMState,
3231                                    cp15.c14_timer[GTIMER_VIRT].ctl),
3232       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3233       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3234     },
3235     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
3236       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
3237       .type = ARM_CP_IO, .access = PL0_RW,
3238       .accessfn = gt_vtimer_access,
3239       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
3240       .resetvalue = 0,
3241       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3242       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3243     },
3244     /* TimerValue views: a 32 bit downcounting view of the underlying state */
3245     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3246       .secure = ARM_CP_SECSTATE_NS,
3247       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3248       .accessfn = gt_ptimer_access,
3249       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3250     },
3251     { .name = "CNTP_TVAL_S",
3252       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3253       .secure = ARM_CP_SECSTATE_S,
3254       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3255       .accessfn = gt_ptimer_access,
3256       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
3257     },
3258     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3259       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
3260       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3261       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
3262       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3263     },
3264     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
3265       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3266       .accessfn = gt_vtimer_access,
3267       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3268     },
3269     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3270       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
3271       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3272       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
3273       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3274     },
3275     /* The counter itself */
3276     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
3277       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3278       .accessfn = gt_pct_access,
3279       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
3280     },
3281     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3282       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3283       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3284       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3285     },
3286     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3287       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3288       .accessfn = gt_vct_access,
3289       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3290     },
3291     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3292       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3293       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3294       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3295     },
3296     /* Comparison value, indicating when the timer goes off */
3297     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3298       .secure = ARM_CP_SECSTATE_NS,
3299       .access = PL0_RW,
3300       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3301       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3302       .accessfn = gt_ptimer_access,
3303       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3304       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3305     },
3306     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3307       .secure = ARM_CP_SECSTATE_S,
3308       .access = PL0_RW,
3309       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3310       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3311       .accessfn = gt_ptimer_access,
3312       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3313     },
3314     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3315       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3316       .access = PL0_RW,
3317       .type = ARM_CP_IO,
3318       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3319       .resetvalue = 0, .accessfn = gt_ptimer_access,
3320       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3321       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3322     },
3323     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3324       .access = PL0_RW,
3325       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3326       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3327       .accessfn = gt_vtimer_access,
3328       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3329       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3330     },
3331     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3332       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3333       .access = PL0_RW,
3334       .type = ARM_CP_IO,
3335       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3336       .resetvalue = 0, .accessfn = gt_vtimer_access,
3337       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3338       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3339     },
3340     /* Secure timer -- this is actually restricted to only EL3
3341      * and configurably Secure-EL1 via the accessfn.
3342      */
3343     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3344       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3345       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3346       .accessfn = gt_stimer_access,
3347       .readfn = gt_sec_tval_read,
3348       .writefn = gt_sec_tval_write,
3349       .resetfn = gt_sec_timer_reset,
3350     },
3351     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3352       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3353       .type = ARM_CP_IO, .access = PL1_RW,
3354       .accessfn = gt_stimer_access,
3355       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3356       .resetvalue = 0,
3357       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3358     },
3359     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3360       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3361       .type = ARM_CP_IO, .access = PL1_RW,
3362       .accessfn = gt_stimer_access,
3363       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3364       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3365     },
3366     REGINFO_SENTINEL
3367 };
3368 
3369 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3370                                  bool isread)
3371 {
3372     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3373         return CP_ACCESS_TRAP;
3374     }
3375     return CP_ACCESS_OK;
3376 }
3377 
3378 #else
3379 
3380 /* In user-mode most of the generic timer registers are inaccessible
3381  * however modern kernels (4.12+) allow access to cntvct_el0
3382  */
3383 
3384 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3385 {
3386     ARMCPU *cpu = env_archcpu(env);
3387 
3388     /* Currently we have no support for QEMUTimer in linux-user so we
3389      * can't call gt_get_countervalue(env), instead we directly
3390      * call the lower level functions.
3391      */
3392     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3393 }
3394 
3395 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3396     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3397       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3398       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3399       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3400       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3401     },
3402     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3403       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3404       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3405       .readfn = gt_virt_cnt_read,
3406     },
3407     REGINFO_SENTINEL
3408 };
3409 
3410 #endif
3411 
3412 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3413 {
3414     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3415         raw_write(env, ri, value);
3416     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3417         raw_write(env, ri, value & 0xfffff6ff);
3418     } else {
3419         raw_write(env, ri, value & 0xfffff1ff);
3420     }
3421 }
3422 
3423 #ifndef CONFIG_USER_ONLY
3424 /* get_phys_addr() isn't present for user-mode-only targets */
3425 
3426 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3427                                  bool isread)
3428 {
3429     if (ri->opc2 & 4) {
3430         /* The ATS12NSO* operations must trap to EL3 if executed in
3431          * Secure EL1 (which can only happen if EL3 is AArch64).
3432          * They are simply UNDEF if executed from NS EL1.
3433          * They function normally from EL2 or EL3.
3434          */
3435         if (arm_current_el(env) == 1) {
3436             if (arm_is_secure_below_el3(env)) {
3437                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3438             }
3439             return CP_ACCESS_TRAP_UNCATEGORIZED;
3440         }
3441     }
3442     return CP_ACCESS_OK;
3443 }
3444 
3445 #ifdef CONFIG_TCG
3446 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3447                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3448 {
3449     hwaddr phys_addr;
3450     target_ulong page_size;
3451     int prot;
3452     bool ret;
3453     uint64_t par64;
3454     bool format64 = false;
3455     MemTxAttrs attrs = {};
3456     ARMMMUFaultInfo fi = {};
3457     ARMCacheAttrs cacheattrs = {};
3458 
3459     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3460                         &prot, &page_size, &fi, &cacheattrs);
3461 
3462     if (ret) {
3463         /*
3464          * Some kinds of translation fault must cause exceptions rather
3465          * than being reported in the PAR.
3466          */
3467         int current_el = arm_current_el(env);
3468         int target_el;
3469         uint32_t syn, fsr, fsc;
3470         bool take_exc = false;
3471 
3472         if (fi.s1ptw && current_el == 1 && !arm_is_secure(env)
3473             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3474             /*
3475              * Synchronous stage 2 fault on an access made as part of the
3476              * translation table walk for AT S1E0* or AT S1E1* insn
3477              * executed from NS EL1. If this is a synchronous external abort
3478              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3479              * to EL3. Otherwise the fault is taken as an exception to EL2,
3480              * and HPFAR_EL2 holds the faulting IPA.
3481              */
3482             if (fi.type == ARMFault_SyncExternalOnWalk &&
3483                 (env->cp15.scr_el3 & SCR_EA)) {
3484                 target_el = 3;
3485             } else {
3486                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3487                 target_el = 2;
3488             }
3489             take_exc = true;
3490         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3491             /*
3492              * Synchronous external aborts during a translation table walk
3493              * are taken as Data Abort exceptions.
3494              */
3495             if (fi.stage2) {
3496                 if (current_el == 3) {
3497                     target_el = 3;
3498                 } else {
3499                     target_el = 2;
3500                 }
3501             } else {
3502                 target_el = exception_target_el(env);
3503             }
3504             take_exc = true;
3505         }
3506 
3507         if (take_exc) {
3508             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3509             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3510                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3511                 fsr = arm_fi_to_lfsc(&fi);
3512                 fsc = extract32(fsr, 0, 6);
3513             } else {
3514                 fsr = arm_fi_to_sfsc(&fi);
3515                 fsc = 0x3f;
3516             }
3517             /*
3518              * Report exception with ESR indicating a fault due to a
3519              * translation table walk for a cache maintenance instruction.
3520              */
3521             syn = syn_data_abort_no_iss(current_el == target_el,
3522                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3523             env->exception.vaddress = value;
3524             env->exception.fsr = fsr;
3525             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3526         }
3527     }
3528 
3529     if (is_a64(env)) {
3530         format64 = true;
3531     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3532         /*
3533          * ATS1Cxx:
3534          * * TTBCR.EAE determines whether the result is returned using the
3535          *   32-bit or the 64-bit PAR format
3536          * * Instructions executed in Hyp mode always use the 64bit format
3537          *
3538          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3539          * * The Non-secure TTBCR.EAE bit is set to 1
3540          * * The implementation includes EL2, and the value of HCR.VM is 1
3541          *
3542          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3543          *
3544          * ATS1Hx always uses the 64bit format.
3545          */
3546         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3547 
3548         if (arm_feature(env, ARM_FEATURE_EL2)) {
3549             if (mmu_idx == ARMMMUIdx_E10_0 ||
3550                 mmu_idx == ARMMMUIdx_E10_1 ||
3551                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3552                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3553             } else {
3554                 format64 |= arm_current_el(env) == 2;
3555             }
3556         }
3557     }
3558 
3559     if (format64) {
3560         /* Create a 64-bit PAR */
3561         par64 = (1 << 11); /* LPAE bit always set */
3562         if (!ret) {
3563             par64 |= phys_addr & ~0xfffULL;
3564             if (!attrs.secure) {
3565                 par64 |= (1 << 9); /* NS */
3566             }
3567             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3568             par64 |= cacheattrs.shareability << 7; /* SH */
3569         } else {
3570             uint32_t fsr = arm_fi_to_lfsc(&fi);
3571 
3572             par64 |= 1; /* F */
3573             par64 |= (fsr & 0x3f) << 1; /* FS */
3574             if (fi.stage2) {
3575                 par64 |= (1 << 9); /* S */
3576             }
3577             if (fi.s1ptw) {
3578                 par64 |= (1 << 8); /* PTW */
3579             }
3580         }
3581     } else {
3582         /* fsr is a DFSR/IFSR value for the short descriptor
3583          * translation table format (with WnR always clear).
3584          * Convert it to a 32-bit PAR.
3585          */
3586         if (!ret) {
3587             /* We do not set any attribute bits in the PAR */
3588             if (page_size == (1 << 24)
3589                 && arm_feature(env, ARM_FEATURE_V7)) {
3590                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3591             } else {
3592                 par64 = phys_addr & 0xfffff000;
3593             }
3594             if (!attrs.secure) {
3595                 par64 |= (1 << 9); /* NS */
3596             }
3597         } else {
3598             uint32_t fsr = arm_fi_to_sfsc(&fi);
3599 
3600             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3601                     ((fsr & 0xf) << 1) | 1;
3602         }
3603     }
3604     return par64;
3605 }
3606 #endif /* CONFIG_TCG */
3607 
3608 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3609 {
3610 #ifdef CONFIG_TCG
3611     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3612     uint64_t par64;
3613     ARMMMUIdx mmu_idx;
3614     int el = arm_current_el(env);
3615     bool secure = arm_is_secure_below_el3(env);
3616 
3617     switch (ri->opc2 & 6) {
3618     case 0:
3619         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3620         switch (el) {
3621         case 3:
3622             mmu_idx = ARMMMUIdx_SE3;
3623             break;
3624         case 2:
3625             g_assert(!secure);  /* TODO: ARMv8.4-SecEL2 */
3626             /* fall through */
3627         case 1:
3628             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3629                 mmu_idx = (secure ? ARMMMUIdx_SE10_1_PAN
3630                            : ARMMMUIdx_Stage1_E1_PAN);
3631             } else {
3632                 mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_Stage1_E1;
3633             }
3634             break;
3635         default:
3636             g_assert_not_reached();
3637         }
3638         break;
3639     case 2:
3640         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3641         switch (el) {
3642         case 3:
3643             mmu_idx = ARMMMUIdx_SE10_0;
3644             break;
3645         case 2:
3646             mmu_idx = ARMMMUIdx_Stage1_E0;
3647             break;
3648         case 1:
3649             mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_Stage1_E0;
3650             break;
3651         default:
3652             g_assert_not_reached();
3653         }
3654         break;
3655     case 4:
3656         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3657         mmu_idx = ARMMMUIdx_E10_1;
3658         break;
3659     case 6:
3660         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3661         mmu_idx = ARMMMUIdx_E10_0;
3662         break;
3663     default:
3664         g_assert_not_reached();
3665     }
3666 
3667     par64 = do_ats_write(env, value, access_type, mmu_idx);
3668 
3669     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3670 #else
3671     /* Handled by hardware accelerator. */
3672     g_assert_not_reached();
3673 #endif /* CONFIG_TCG */
3674 }
3675 
3676 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3677                         uint64_t value)
3678 {
3679 #ifdef CONFIG_TCG
3680     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3681     uint64_t par64;
3682 
3683     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3684 
3685     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3686 #else
3687     /* Handled by hardware accelerator. */
3688     g_assert_not_reached();
3689 #endif /* CONFIG_TCG */
3690 }
3691 
3692 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3693                                      bool isread)
3694 {
3695     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
3696         return CP_ACCESS_TRAP;
3697     }
3698     return CP_ACCESS_OK;
3699 }
3700 
3701 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3702                         uint64_t value)
3703 {
3704 #ifdef CONFIG_TCG
3705     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3706     ARMMMUIdx mmu_idx;
3707     int secure = arm_is_secure_below_el3(env);
3708 
3709     switch (ri->opc2 & 6) {
3710     case 0:
3711         switch (ri->opc1) {
3712         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3713             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3714                 mmu_idx = (secure ? ARMMMUIdx_SE10_1_PAN
3715                            : ARMMMUIdx_Stage1_E1_PAN);
3716             } else {
3717                 mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_Stage1_E1;
3718             }
3719             break;
3720         case 4: /* AT S1E2R, AT S1E2W */
3721             mmu_idx = ARMMMUIdx_E2;
3722             break;
3723         case 6: /* AT S1E3R, AT S1E3W */
3724             mmu_idx = ARMMMUIdx_SE3;
3725             break;
3726         default:
3727             g_assert_not_reached();
3728         }
3729         break;
3730     case 2: /* AT S1E0R, AT S1E0W */
3731         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_Stage1_E0;
3732         break;
3733     case 4: /* AT S12E1R, AT S12E1W */
3734         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3735         break;
3736     case 6: /* AT S12E0R, AT S12E0W */
3737         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3738         break;
3739     default:
3740         g_assert_not_reached();
3741     }
3742 
3743     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3744 #else
3745     /* Handled by hardware accelerator. */
3746     g_assert_not_reached();
3747 #endif /* CONFIG_TCG */
3748 }
3749 #endif
3750 
3751 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3752     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3753       .access = PL1_RW, .resetvalue = 0,
3754       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3755                              offsetoflow32(CPUARMState, cp15.par_ns) },
3756       .writefn = par_write },
3757 #ifndef CONFIG_USER_ONLY
3758     /* This underdecoding is safe because the reginfo is NO_RAW. */
3759     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3760       .access = PL1_W, .accessfn = ats_access,
3761       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3762 #endif
3763     REGINFO_SENTINEL
3764 };
3765 
3766 /* Return basic MPU access permission bits.  */
3767 static uint32_t simple_mpu_ap_bits(uint32_t val)
3768 {
3769     uint32_t ret;
3770     uint32_t mask;
3771     int i;
3772     ret = 0;
3773     mask = 3;
3774     for (i = 0; i < 16; i += 2) {
3775         ret |= (val >> i) & mask;
3776         mask <<= 2;
3777     }
3778     return ret;
3779 }
3780 
3781 /* Pad basic MPU access permission bits to extended format.  */
3782 static uint32_t extended_mpu_ap_bits(uint32_t val)
3783 {
3784     uint32_t ret;
3785     uint32_t mask;
3786     int i;
3787     ret = 0;
3788     mask = 3;
3789     for (i = 0; i < 16; i += 2) {
3790         ret |= (val & mask) << i;
3791         mask <<= 2;
3792     }
3793     return ret;
3794 }
3795 
3796 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3797                                  uint64_t value)
3798 {
3799     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3800 }
3801 
3802 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3803 {
3804     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3805 }
3806 
3807 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3808                                  uint64_t value)
3809 {
3810     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3811 }
3812 
3813 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3814 {
3815     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3816 }
3817 
3818 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3819 {
3820     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3821 
3822     if (!u32p) {
3823         return 0;
3824     }
3825 
3826     u32p += env->pmsav7.rnr[M_REG_NS];
3827     return *u32p;
3828 }
3829 
3830 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3831                          uint64_t value)
3832 {
3833     ARMCPU *cpu = env_archcpu(env);
3834     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3835 
3836     if (!u32p) {
3837         return;
3838     }
3839 
3840     u32p += env->pmsav7.rnr[M_REG_NS];
3841     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3842     *u32p = value;
3843 }
3844 
3845 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3846                               uint64_t value)
3847 {
3848     ARMCPU *cpu = env_archcpu(env);
3849     uint32_t nrgs = cpu->pmsav7_dregion;
3850 
3851     if (value >= nrgs) {
3852         qemu_log_mask(LOG_GUEST_ERROR,
3853                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3854                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3855         return;
3856     }
3857 
3858     raw_write(env, ri, value);
3859 }
3860 
3861 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3862     /* Reset for all these registers is handled in arm_cpu_reset(),
3863      * because the PMSAv7 is also used by M-profile CPUs, which do
3864      * not register cpregs but still need the state to be reset.
3865      */
3866     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3867       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3868       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3869       .readfn = pmsav7_read, .writefn = pmsav7_write,
3870       .resetfn = arm_cp_reset_ignore },
3871     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3872       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3873       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3874       .readfn = pmsav7_read, .writefn = pmsav7_write,
3875       .resetfn = arm_cp_reset_ignore },
3876     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3877       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3878       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3879       .readfn = pmsav7_read, .writefn = pmsav7_write,
3880       .resetfn = arm_cp_reset_ignore },
3881     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3882       .access = PL1_RW,
3883       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3884       .writefn = pmsav7_rgnr_write,
3885       .resetfn = arm_cp_reset_ignore },
3886     REGINFO_SENTINEL
3887 };
3888 
3889 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3890     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3891       .access = PL1_RW, .type = ARM_CP_ALIAS,
3892       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3893       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3894     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3895       .access = PL1_RW, .type = ARM_CP_ALIAS,
3896       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3897       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3898     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3899       .access = PL1_RW,
3900       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3901       .resetvalue = 0, },
3902     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3903       .access = PL1_RW,
3904       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3905       .resetvalue = 0, },
3906     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3907       .access = PL1_RW,
3908       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3909     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3910       .access = PL1_RW,
3911       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3912     /* Protection region base and size registers */
3913     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3914       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3915       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3916     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3917       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3918       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3919     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3920       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3921       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3922     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3923       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3924       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3925     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3926       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3927       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3928     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3929       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3930       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3931     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3932       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3933       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3934     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3935       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3936       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3937     REGINFO_SENTINEL
3938 };
3939 
3940 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3941                                  uint64_t value)
3942 {
3943     TCR *tcr = raw_ptr(env, ri);
3944     int maskshift = extract32(value, 0, 3);
3945 
3946     if (!arm_feature(env, ARM_FEATURE_V8)) {
3947         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3948             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3949              * using Long-desciptor translation table format */
3950             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3951         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3952             /* In an implementation that includes the Security Extensions
3953              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3954              * Short-descriptor translation table format.
3955              */
3956             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3957         } else {
3958             value &= TTBCR_N;
3959         }
3960     }
3961 
3962     /* Update the masks corresponding to the TCR bank being written
3963      * Note that we always calculate mask and base_mask, but
3964      * they are only used for short-descriptor tables (ie if EAE is 0);
3965      * for long-descriptor tables the TCR fields are used differently
3966      * and the mask and base_mask values are meaningless.
3967      */
3968     tcr->raw_tcr = value;
3969     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3970     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3971 }
3972 
3973 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3974                              uint64_t value)
3975 {
3976     ARMCPU *cpu = env_archcpu(env);
3977     TCR *tcr = raw_ptr(env, ri);
3978 
3979     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3980         /* With LPAE the TTBCR could result in a change of ASID
3981          * via the TTBCR.A1 bit, so do a TLB flush.
3982          */
3983         tlb_flush(CPU(cpu));
3984     }
3985     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3986     value = deposit64(tcr->raw_tcr, 0, 32, value);
3987     vmsa_ttbcr_raw_write(env, ri, value);
3988 }
3989 
3990 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3991 {
3992     TCR *tcr = raw_ptr(env, ri);
3993 
3994     /* Reset both the TCR as well as the masks corresponding to the bank of
3995      * the TCR being reset.
3996      */
3997     tcr->raw_tcr = 0;
3998     tcr->mask = 0;
3999     tcr->base_mask = 0xffffc000u;
4000 }
4001 
4002 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
4003                                uint64_t value)
4004 {
4005     ARMCPU *cpu = env_archcpu(env);
4006     TCR *tcr = raw_ptr(env, ri);
4007 
4008     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
4009     tlb_flush(CPU(cpu));
4010     tcr->raw_tcr = value;
4011 }
4012 
4013 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4014                             uint64_t value)
4015 {
4016     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
4017     if (cpreg_field_is_64bit(ri) &&
4018         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
4019         ARMCPU *cpu = env_archcpu(env);
4020         tlb_flush(CPU(cpu));
4021     }
4022     raw_write(env, ri, value);
4023 }
4024 
4025 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4026                                     uint64_t value)
4027 {
4028     /*
4029      * If we are running with E2&0 regime, then an ASID is active.
4030      * Flush if that might be changing.  Note we're not checking
4031      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
4032      * holds the active ASID, only checking the field that might.
4033      */
4034     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
4035         (arm_hcr_el2_eff(env) & HCR_E2H)) {
4036         tlb_flush_by_mmuidx(env_cpu(env),
4037                             ARMMMUIdxBit_E20_2 |
4038                             ARMMMUIdxBit_E20_2_PAN |
4039                             ARMMMUIdxBit_E20_0);
4040     }
4041     raw_write(env, ri, value);
4042 }
4043 
4044 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4045                         uint64_t value)
4046 {
4047     ARMCPU *cpu = env_archcpu(env);
4048     CPUState *cs = CPU(cpu);
4049 
4050     /*
4051      * A change in VMID to the stage2 page table (Stage2) invalidates
4052      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
4053      */
4054     if (raw_read(env, ri) != value) {
4055         tlb_flush_by_mmuidx(cs,
4056                             ARMMMUIdxBit_E10_1 |
4057                             ARMMMUIdxBit_E10_1_PAN |
4058                             ARMMMUIdxBit_E10_0 |
4059                             ARMMMUIdxBit_Stage2);
4060         raw_write(env, ri, value);
4061     }
4062 }
4063 
4064 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
4065     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
4066       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
4067       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
4068                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
4069     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
4070       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4071       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
4072                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
4073     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
4074       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4075       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
4076                              offsetof(CPUARMState, cp15.dfar_ns) } },
4077     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
4078       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
4079       .access = PL1_RW, .accessfn = access_tvm_trvm,
4080       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
4081       .resetvalue = 0, },
4082     REGINFO_SENTINEL
4083 };
4084 
4085 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
4086     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
4087       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
4088       .access = PL1_RW, .accessfn = access_tvm_trvm,
4089       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
4090     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
4091       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
4092       .access = PL1_RW, .accessfn = access_tvm_trvm,
4093       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4094       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4095                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
4096     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
4097       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
4098       .access = PL1_RW, .accessfn = access_tvm_trvm,
4099       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4100       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4101                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
4102     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
4103       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4104       .access = PL1_RW, .accessfn = access_tvm_trvm,
4105       .writefn = vmsa_tcr_el12_write,
4106       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
4107       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
4108     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4109       .access = PL1_RW, .accessfn = access_tvm_trvm,
4110       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
4111       .raw_writefn = vmsa_ttbcr_raw_write,
4112       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
4113                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
4114     REGINFO_SENTINEL
4115 };
4116 
4117 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
4118  * qemu tlbs nor adjusting cached masks.
4119  */
4120 static const ARMCPRegInfo ttbcr2_reginfo = {
4121     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
4122     .access = PL1_RW, .accessfn = access_tvm_trvm,
4123     .type = ARM_CP_ALIAS,
4124     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
4125                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
4126 };
4127 
4128 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
4129                                 uint64_t value)
4130 {
4131     env->cp15.c15_ticonfig = value & 0xe7;
4132     /* The OS_TYPE bit in this register changes the reported CPUID! */
4133     env->cp15.c0_cpuid = (value & (1 << 5)) ?
4134         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
4135 }
4136 
4137 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
4138                                 uint64_t value)
4139 {
4140     env->cp15.c15_threadid = value & 0xffff;
4141 }
4142 
4143 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
4144                            uint64_t value)
4145 {
4146     /* Wait-for-interrupt (deprecated) */
4147     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
4148 }
4149 
4150 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
4151                                   uint64_t value)
4152 {
4153     /* On OMAP there are registers indicating the max/min index of dcache lines
4154      * containing a dirty line; cache flush operations have to reset these.
4155      */
4156     env->cp15.c15_i_max = 0x000;
4157     env->cp15.c15_i_min = 0xff0;
4158 }
4159 
4160 static const ARMCPRegInfo omap_cp_reginfo[] = {
4161     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
4162       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
4163       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
4164       .resetvalue = 0, },
4165     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
4166       .access = PL1_RW, .type = ARM_CP_NOP },
4167     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
4168       .access = PL1_RW,
4169       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
4170       .writefn = omap_ticonfig_write },
4171     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
4172       .access = PL1_RW,
4173       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
4174     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
4175       .access = PL1_RW, .resetvalue = 0xff0,
4176       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
4177     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
4178       .access = PL1_RW,
4179       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
4180       .writefn = omap_threadid_write },
4181     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
4182       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4183       .type = ARM_CP_NO_RAW,
4184       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
4185     /* TODO: Peripheral port remap register:
4186      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
4187      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
4188      * when MMU is off.
4189      */
4190     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
4191       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
4192       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
4193       .writefn = omap_cachemaint_write },
4194     { .name = "C9", .cp = 15, .crn = 9,
4195       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
4196       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
4197     REGINFO_SENTINEL
4198 };
4199 
4200 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4201                               uint64_t value)
4202 {
4203     env->cp15.c15_cpar = value & 0x3fff;
4204 }
4205 
4206 static const ARMCPRegInfo xscale_cp_reginfo[] = {
4207     { .name = "XSCALE_CPAR",
4208       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4209       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
4210       .writefn = xscale_cpar_write, },
4211     { .name = "XSCALE_AUXCR",
4212       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
4213       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
4214       .resetvalue = 0, },
4215     /* XScale specific cache-lockdown: since we have no cache we NOP these
4216      * and hope the guest does not really rely on cache behaviour.
4217      */
4218     { .name = "XSCALE_LOCK_ICACHE_LINE",
4219       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
4220       .access = PL1_W, .type = ARM_CP_NOP },
4221     { .name = "XSCALE_UNLOCK_ICACHE",
4222       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
4223       .access = PL1_W, .type = ARM_CP_NOP },
4224     { .name = "XSCALE_DCACHE_LOCK",
4225       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
4226       .access = PL1_RW, .type = ARM_CP_NOP },
4227     { .name = "XSCALE_UNLOCK_DCACHE",
4228       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
4229       .access = PL1_W, .type = ARM_CP_NOP },
4230     REGINFO_SENTINEL
4231 };
4232 
4233 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
4234     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
4235      * implementation of this implementation-defined space.
4236      * Ideally this should eventually disappear in favour of actually
4237      * implementing the correct behaviour for all cores.
4238      */
4239     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
4240       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4241       .access = PL1_RW,
4242       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
4243       .resetvalue = 0 },
4244     REGINFO_SENTINEL
4245 };
4246 
4247 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
4248     /* Cache status: RAZ because we have no cache so it's always clean */
4249     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
4250       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4251       .resetvalue = 0 },
4252     REGINFO_SENTINEL
4253 };
4254 
4255 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
4256     /* We never have a a block transfer operation in progress */
4257     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4258       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4259       .resetvalue = 0 },
4260     /* The cache ops themselves: these all NOP for QEMU */
4261     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4262       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4263     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4264       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4265     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4266       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4267     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4268       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4269     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4270       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4271     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4272       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4273     REGINFO_SENTINEL
4274 };
4275 
4276 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4277     /* The cache test-and-clean instructions always return (1 << 30)
4278      * to indicate that there are no dirty cache lines.
4279      */
4280     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4281       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4282       .resetvalue = (1 << 30) },
4283     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4284       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4285       .resetvalue = (1 << 30) },
4286     REGINFO_SENTINEL
4287 };
4288 
4289 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4290     /* Ignore ReadBuffer accesses */
4291     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4292       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4293       .access = PL1_RW, .resetvalue = 0,
4294       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4295     REGINFO_SENTINEL
4296 };
4297 
4298 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4299 {
4300     ARMCPU *cpu = env_archcpu(env);
4301     unsigned int cur_el = arm_current_el(env);
4302     bool secure = arm_is_secure(env);
4303 
4304     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
4305         return env->cp15.vpidr_el2;
4306     }
4307     return raw_read(env, ri);
4308 }
4309 
4310 static uint64_t mpidr_read_val(CPUARMState *env)
4311 {
4312     ARMCPU *cpu = env_archcpu(env);
4313     uint64_t mpidr = cpu->mp_affinity;
4314 
4315     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4316         mpidr |= (1U << 31);
4317         /* Cores which are uniprocessor (non-coherent)
4318          * but still implement the MP extensions set
4319          * bit 30. (For instance, Cortex-R5).
4320          */
4321         if (cpu->mp_is_up) {
4322             mpidr |= (1u << 30);
4323         }
4324     }
4325     return mpidr;
4326 }
4327 
4328 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4329 {
4330     unsigned int cur_el = arm_current_el(env);
4331     bool secure = arm_is_secure(env);
4332 
4333     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
4334         return env->cp15.vmpidr_el2;
4335     }
4336     return mpidr_read_val(env);
4337 }
4338 
4339 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4340     /* NOP AMAIR0/1 */
4341     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4342       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4343       .access = PL1_RW, .accessfn = access_tvm_trvm,
4344       .type = ARM_CP_CONST, .resetvalue = 0 },
4345     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4346     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4347       .access = PL1_RW, .accessfn = access_tvm_trvm,
4348       .type = ARM_CP_CONST, .resetvalue = 0 },
4349     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4350       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4351       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4352                              offsetof(CPUARMState, cp15.par_ns)} },
4353     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4354       .access = PL1_RW, .accessfn = access_tvm_trvm,
4355       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4356       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4357                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4358       .writefn = vmsa_ttbr_write, },
4359     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4360       .access = PL1_RW, .accessfn = access_tvm_trvm,
4361       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4362       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4363                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4364       .writefn = vmsa_ttbr_write, },
4365     REGINFO_SENTINEL
4366 };
4367 
4368 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4369 {
4370     return vfp_get_fpcr(env);
4371 }
4372 
4373 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4374                             uint64_t value)
4375 {
4376     vfp_set_fpcr(env, value);
4377 }
4378 
4379 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4380 {
4381     return vfp_get_fpsr(env);
4382 }
4383 
4384 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4385                             uint64_t value)
4386 {
4387     vfp_set_fpsr(env, value);
4388 }
4389 
4390 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4391                                        bool isread)
4392 {
4393     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4394         return CP_ACCESS_TRAP;
4395     }
4396     return CP_ACCESS_OK;
4397 }
4398 
4399 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4400                             uint64_t value)
4401 {
4402     env->daif = value & PSTATE_DAIF;
4403 }
4404 
4405 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4406 {
4407     return env->pstate & PSTATE_PAN;
4408 }
4409 
4410 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4411                            uint64_t value)
4412 {
4413     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4414 }
4415 
4416 static const ARMCPRegInfo pan_reginfo = {
4417     .name = "PAN", .state = ARM_CP_STATE_AA64,
4418     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4419     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4420     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4421 };
4422 
4423 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4424 {
4425     return env->pstate & PSTATE_UAO;
4426 }
4427 
4428 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4429                            uint64_t value)
4430 {
4431     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4432 }
4433 
4434 static const ARMCPRegInfo uao_reginfo = {
4435     .name = "UAO", .state = ARM_CP_STATE_AA64,
4436     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4437     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4438     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4439 };
4440 
4441 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4442                                               const ARMCPRegInfo *ri,
4443                                               bool isread)
4444 {
4445     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4446     switch (arm_current_el(env)) {
4447     case 0:
4448         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4449         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4450             return CP_ACCESS_TRAP;
4451         }
4452         /* fall through */
4453     case 1:
4454         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4455         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4456             return CP_ACCESS_TRAP_EL2;
4457         }
4458         break;
4459     }
4460     return CP_ACCESS_OK;
4461 }
4462 
4463 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4464                                               const ARMCPRegInfo *ri,
4465                                               bool isread)
4466 {
4467     /* Cache invalidate/clean to Point of Unification... */
4468     switch (arm_current_el(env)) {
4469     case 0:
4470         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4471         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4472             return CP_ACCESS_TRAP;
4473         }
4474         /* fall through */
4475     case 1:
4476         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4477         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4478             return CP_ACCESS_TRAP_EL2;
4479         }
4480         break;
4481     }
4482     return CP_ACCESS_OK;
4483 }
4484 
4485 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4486  * Page D4-1736 (DDI0487A.b)
4487  */
4488 
4489 static int vae1_tlbmask(CPUARMState *env)
4490 {
4491     /* Since we exclude secure first, we may read HCR_EL2 directly. */
4492     if (arm_is_secure_below_el3(env)) {
4493         return ARMMMUIdxBit_SE10_1 |
4494                ARMMMUIdxBit_SE10_1_PAN |
4495                ARMMMUIdxBit_SE10_0;
4496     } else if ((env->cp15.hcr_el2 & (HCR_E2H | HCR_TGE))
4497                == (HCR_E2H | HCR_TGE)) {
4498         return ARMMMUIdxBit_E20_2 |
4499                ARMMMUIdxBit_E20_2_PAN |
4500                ARMMMUIdxBit_E20_0;
4501     } else {
4502         return ARMMMUIdxBit_E10_1 |
4503                ARMMMUIdxBit_E10_1_PAN |
4504                ARMMMUIdxBit_E10_0;
4505     }
4506 }
4507 
4508 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4509                                       uint64_t value)
4510 {
4511     CPUState *cs = env_cpu(env);
4512     int mask = vae1_tlbmask(env);
4513 
4514     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4515 }
4516 
4517 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4518                                     uint64_t value)
4519 {
4520     CPUState *cs = env_cpu(env);
4521     int mask = vae1_tlbmask(env);
4522 
4523     if (tlb_force_broadcast(env)) {
4524         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4525     } else {
4526         tlb_flush_by_mmuidx(cs, mask);
4527     }
4528 }
4529 
4530 static int alle1_tlbmask(CPUARMState *env)
4531 {
4532     /*
4533      * Note that the 'ALL' scope must invalidate both stage 1 and
4534      * stage 2 translations, whereas most other scopes only invalidate
4535      * stage 1 translations.
4536      */
4537     if (arm_is_secure_below_el3(env)) {
4538         return ARMMMUIdxBit_SE10_1 |
4539                ARMMMUIdxBit_SE10_1_PAN |
4540                ARMMMUIdxBit_SE10_0;
4541     } else if (arm_feature(env, ARM_FEATURE_EL2)) {
4542         return ARMMMUIdxBit_E10_1 |
4543                ARMMMUIdxBit_E10_1_PAN |
4544                ARMMMUIdxBit_E10_0 |
4545                ARMMMUIdxBit_Stage2;
4546     } else {
4547         return ARMMMUIdxBit_E10_1 |
4548                ARMMMUIdxBit_E10_1_PAN |
4549                ARMMMUIdxBit_E10_0;
4550     }
4551 }
4552 
4553 static int e2_tlbmask(CPUARMState *env)
4554 {
4555     /* TODO: ARMv8.4-SecEL2 */
4556     return ARMMMUIdxBit_E20_0 |
4557            ARMMMUIdxBit_E20_2 |
4558            ARMMMUIdxBit_E20_2_PAN |
4559            ARMMMUIdxBit_E2;
4560 }
4561 
4562 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4563                                   uint64_t value)
4564 {
4565     CPUState *cs = env_cpu(env);
4566     int mask = alle1_tlbmask(env);
4567 
4568     tlb_flush_by_mmuidx(cs, mask);
4569 }
4570 
4571 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4572                                   uint64_t value)
4573 {
4574     CPUState *cs = env_cpu(env);
4575     int mask = e2_tlbmask(env);
4576 
4577     tlb_flush_by_mmuidx(cs, mask);
4578 }
4579 
4580 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4581                                   uint64_t value)
4582 {
4583     ARMCPU *cpu = env_archcpu(env);
4584     CPUState *cs = CPU(cpu);
4585 
4586     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4587 }
4588 
4589 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4590                                     uint64_t value)
4591 {
4592     CPUState *cs = env_cpu(env);
4593     int mask = alle1_tlbmask(env);
4594 
4595     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4596 }
4597 
4598 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4599                                     uint64_t value)
4600 {
4601     CPUState *cs = env_cpu(env);
4602     int mask = e2_tlbmask(env);
4603 
4604     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4605 }
4606 
4607 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4608                                     uint64_t value)
4609 {
4610     CPUState *cs = env_cpu(env);
4611 
4612     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4613 }
4614 
4615 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4616                                  uint64_t value)
4617 {
4618     /* Invalidate by VA, EL2
4619      * Currently handles both VAE2 and VALE2, since we don't support
4620      * flush-last-level-only.
4621      */
4622     CPUState *cs = env_cpu(env);
4623     int mask = e2_tlbmask(env);
4624     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4625 
4626     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4627 }
4628 
4629 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4630                                  uint64_t value)
4631 {
4632     /* Invalidate by VA, EL3
4633      * Currently handles both VAE3 and VALE3, since we don't support
4634      * flush-last-level-only.
4635      */
4636     ARMCPU *cpu = env_archcpu(env);
4637     CPUState *cs = CPU(cpu);
4638     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4639 
4640     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4641 }
4642 
4643 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4644                                    uint64_t value)
4645 {
4646     CPUState *cs = env_cpu(env);
4647     int mask = vae1_tlbmask(env);
4648     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4649 
4650     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr, mask);
4651 }
4652 
4653 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4654                                  uint64_t value)
4655 {
4656     /* Invalidate by VA, EL1&0 (AArch64 version).
4657      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4658      * since we don't support flush-for-specific-ASID-only or
4659      * flush-last-level-only.
4660      */
4661     CPUState *cs = env_cpu(env);
4662     int mask = vae1_tlbmask(env);
4663     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4664 
4665     if (tlb_force_broadcast(env)) {
4666         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr, mask);
4667     } else {
4668         tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4669     }
4670 }
4671 
4672 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4673                                    uint64_t value)
4674 {
4675     CPUState *cs = env_cpu(env);
4676     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4677 
4678     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4679                                              ARMMMUIdxBit_E2);
4680 }
4681 
4682 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4683                                    uint64_t value)
4684 {
4685     CPUState *cs = env_cpu(env);
4686     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4687 
4688     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4689                                              ARMMMUIdxBit_SE3);
4690 }
4691 
4692 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4693                                     uint64_t value)
4694 {
4695     /* Invalidate by IPA. This has to invalidate any structures that
4696      * contain only stage 2 translation information, but does not need
4697      * to apply to structures that contain combined stage 1 and stage 2
4698      * translation information.
4699      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
4700      */
4701     ARMCPU *cpu = env_archcpu(env);
4702     CPUState *cs = CPU(cpu);
4703     uint64_t pageaddr;
4704 
4705     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4706         return;
4707     }
4708 
4709     pageaddr = sextract64(value << 12, 0, 48);
4710 
4711     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_Stage2);
4712 }
4713 
4714 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4715                                       uint64_t value)
4716 {
4717     CPUState *cs = env_cpu(env);
4718     uint64_t pageaddr;
4719 
4720     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4721         return;
4722     }
4723 
4724     pageaddr = sextract64(value << 12, 0, 48);
4725 
4726     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4727                                              ARMMMUIdxBit_Stage2);
4728 }
4729 
4730 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4731                                       bool isread)
4732 {
4733     int cur_el = arm_current_el(env);
4734 
4735     if (cur_el < 2) {
4736         uint64_t hcr = arm_hcr_el2_eff(env);
4737 
4738         if (cur_el == 0) {
4739             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4740                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4741                     return CP_ACCESS_TRAP_EL2;
4742                 }
4743             } else {
4744                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4745                     return CP_ACCESS_TRAP;
4746                 }
4747                 if (hcr & HCR_TDZ) {
4748                     return CP_ACCESS_TRAP_EL2;
4749                 }
4750             }
4751         } else if (hcr & HCR_TDZ) {
4752             return CP_ACCESS_TRAP_EL2;
4753         }
4754     }
4755     return CP_ACCESS_OK;
4756 }
4757 
4758 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4759 {
4760     ARMCPU *cpu = env_archcpu(env);
4761     int dzp_bit = 1 << 4;
4762 
4763     /* DZP indicates whether DC ZVA access is allowed */
4764     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4765         dzp_bit = 0;
4766     }
4767     return cpu->dcz_blocksize | dzp_bit;
4768 }
4769 
4770 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4771                                     bool isread)
4772 {
4773     if (!(env->pstate & PSTATE_SP)) {
4774         /* Access to SP_EL0 is undefined if it's being used as
4775          * the stack pointer.
4776          */
4777         return CP_ACCESS_TRAP_UNCATEGORIZED;
4778     }
4779     return CP_ACCESS_OK;
4780 }
4781 
4782 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4783 {
4784     return env->pstate & PSTATE_SP;
4785 }
4786 
4787 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4788 {
4789     update_spsel(env, val);
4790 }
4791 
4792 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4793                         uint64_t value)
4794 {
4795     ARMCPU *cpu = env_archcpu(env);
4796 
4797     if (raw_read(env, ri) == value) {
4798         /* Skip the TLB flush if nothing actually changed; Linux likes
4799          * to do a lot of pointless SCTLR writes.
4800          */
4801         return;
4802     }
4803 
4804     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4805         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4806         value &= ~SCTLR_M;
4807     }
4808 
4809     raw_write(env, ri, value);
4810     /* ??? Lots of these bits are not implemented.  */
4811     /* This may enable/disable the MMU, so do a TLB flush.  */
4812     tlb_flush(CPU(cpu));
4813 
4814     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4815         /*
4816          * Normally we would always end the TB on an SCTLR write; see the
4817          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4818          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4819          * of hflags from the translator, so do it here.
4820          */
4821         arm_rebuild_hflags(env);
4822     }
4823 }
4824 
4825 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4826                                      bool isread)
4827 {
4828     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4829         return CP_ACCESS_TRAP_FP_EL2;
4830     }
4831     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4832         return CP_ACCESS_TRAP_FP_EL3;
4833     }
4834     return CP_ACCESS_OK;
4835 }
4836 
4837 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4838                        uint64_t value)
4839 {
4840     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4841 }
4842 
4843 static const ARMCPRegInfo v8_cp_reginfo[] = {
4844     /* Minimal set of EL0-visible registers. This will need to be expanded
4845      * significantly for system emulation of AArch64 CPUs.
4846      */
4847     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4848       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4849       .access = PL0_RW, .type = ARM_CP_NZCV },
4850     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4851       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4852       .type = ARM_CP_NO_RAW,
4853       .access = PL0_RW, .accessfn = aa64_daif_access,
4854       .fieldoffset = offsetof(CPUARMState, daif),
4855       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4856     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4857       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4858       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4859       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4860     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4861       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4862       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4863       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4864     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4865       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4866       .access = PL0_R, .type = ARM_CP_NO_RAW,
4867       .readfn = aa64_dczid_read },
4868     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4869       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4870       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4871 #ifndef CONFIG_USER_ONLY
4872       /* Avoid overhead of an access check that always passes in user-mode */
4873       .accessfn = aa64_zva_access,
4874 #endif
4875     },
4876     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4877       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4878       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4879     /* Cache ops: all NOPs since we don't emulate caches */
4880     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4881       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4882       .access = PL1_W, .type = ARM_CP_NOP,
4883       .accessfn = aa64_cacheop_pou_access },
4884     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4885       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4886       .access = PL1_W, .type = ARM_CP_NOP,
4887       .accessfn = aa64_cacheop_pou_access },
4888     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4889       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4890       .access = PL0_W, .type = ARM_CP_NOP,
4891       .accessfn = aa64_cacheop_pou_access },
4892     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4893       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4894       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4895       .type = ARM_CP_NOP },
4896     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4897       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4898       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4899     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4900       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4901       .access = PL0_W, .type = ARM_CP_NOP,
4902       .accessfn = aa64_cacheop_poc_access },
4903     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4904       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4905       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4906     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4907       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4908       .access = PL0_W, .type = ARM_CP_NOP,
4909       .accessfn = aa64_cacheop_pou_access },
4910     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4911       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4912       .access = PL0_W, .type = ARM_CP_NOP,
4913       .accessfn = aa64_cacheop_poc_access },
4914     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4915       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4916       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4917     /* TLBI operations */
4918     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4919       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4920       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4921       .writefn = tlbi_aa64_vmalle1is_write },
4922     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4923       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4924       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4925       .writefn = tlbi_aa64_vae1is_write },
4926     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4927       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4928       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4929       .writefn = tlbi_aa64_vmalle1is_write },
4930     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4931       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4932       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4933       .writefn = tlbi_aa64_vae1is_write },
4934     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4935       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4936       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4937       .writefn = tlbi_aa64_vae1is_write },
4938     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4939       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4940       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4941       .writefn = tlbi_aa64_vae1is_write },
4942     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4943       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4944       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4945       .writefn = tlbi_aa64_vmalle1_write },
4946     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4947       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4948       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4949       .writefn = tlbi_aa64_vae1_write },
4950     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4951       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4952       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4953       .writefn = tlbi_aa64_vmalle1_write },
4954     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4955       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4956       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4957       .writefn = tlbi_aa64_vae1_write },
4958     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4959       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4960       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4961       .writefn = tlbi_aa64_vae1_write },
4962     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4963       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4964       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4965       .writefn = tlbi_aa64_vae1_write },
4966     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4967       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4968       .access = PL2_W, .type = ARM_CP_NO_RAW,
4969       .writefn = tlbi_aa64_ipas2e1is_write },
4970     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4971       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4972       .access = PL2_W, .type = ARM_CP_NO_RAW,
4973       .writefn = tlbi_aa64_ipas2e1is_write },
4974     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4975       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4976       .access = PL2_W, .type = ARM_CP_NO_RAW,
4977       .writefn = tlbi_aa64_alle1is_write },
4978     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4979       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4980       .access = PL2_W, .type = ARM_CP_NO_RAW,
4981       .writefn = tlbi_aa64_alle1is_write },
4982     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4983       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4984       .access = PL2_W, .type = ARM_CP_NO_RAW,
4985       .writefn = tlbi_aa64_ipas2e1_write },
4986     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4987       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4988       .access = PL2_W, .type = ARM_CP_NO_RAW,
4989       .writefn = tlbi_aa64_ipas2e1_write },
4990     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4991       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4992       .access = PL2_W, .type = ARM_CP_NO_RAW,
4993       .writefn = tlbi_aa64_alle1_write },
4994     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4995       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4996       .access = PL2_W, .type = ARM_CP_NO_RAW,
4997       .writefn = tlbi_aa64_alle1is_write },
4998 #ifndef CONFIG_USER_ONLY
4999     /* 64 bit address translation operations */
5000     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
5001       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
5002       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5003       .writefn = ats_write64 },
5004     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
5005       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
5006       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5007       .writefn = ats_write64 },
5008     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
5009       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
5010       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5011       .writefn = ats_write64 },
5012     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
5013       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
5014       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5015       .writefn = ats_write64 },
5016     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
5017       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
5018       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5019       .writefn = ats_write64 },
5020     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
5021       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
5022       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5023       .writefn = ats_write64 },
5024     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
5025       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
5026       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5027       .writefn = ats_write64 },
5028     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
5029       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
5030       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5031       .writefn = ats_write64 },
5032     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
5033     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
5034       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
5035       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5036       .writefn = ats_write64 },
5037     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
5038       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
5039       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5040       .writefn = ats_write64 },
5041     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
5042       .type = ARM_CP_ALIAS,
5043       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
5044       .access = PL1_RW, .resetvalue = 0,
5045       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
5046       .writefn = par_write },
5047 #endif
5048     /* TLB invalidate last level of translation table walk */
5049     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
5050       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5051       .writefn = tlbimva_is_write },
5052     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
5053       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5054       .writefn = tlbimvaa_is_write },
5055     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
5056       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5057       .writefn = tlbimva_write },
5058     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
5059       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5060       .writefn = tlbimvaa_write },
5061     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5062       .type = ARM_CP_NO_RAW, .access = PL2_W,
5063       .writefn = tlbimva_hyp_write },
5064     { .name = "TLBIMVALHIS",
5065       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5066       .type = ARM_CP_NO_RAW, .access = PL2_W,
5067       .writefn = tlbimva_hyp_is_write },
5068     { .name = "TLBIIPAS2",
5069       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5070       .type = ARM_CP_NO_RAW, .access = PL2_W,
5071       .writefn = tlbiipas2_write },
5072     { .name = "TLBIIPAS2IS",
5073       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5074       .type = ARM_CP_NO_RAW, .access = PL2_W,
5075       .writefn = tlbiipas2_is_write },
5076     { .name = "TLBIIPAS2L",
5077       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5078       .type = ARM_CP_NO_RAW, .access = PL2_W,
5079       .writefn = tlbiipas2_write },
5080     { .name = "TLBIIPAS2LIS",
5081       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5082       .type = ARM_CP_NO_RAW, .access = PL2_W,
5083       .writefn = tlbiipas2_is_write },
5084     /* 32 bit cache operations */
5085     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5086       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5087     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5088       .type = ARM_CP_NOP, .access = PL1_W },
5089     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5090       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5091     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5092       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5093     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5094       .type = ARM_CP_NOP, .access = PL1_W },
5095     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5096       .type = ARM_CP_NOP, .access = PL1_W },
5097     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5098       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5099     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5100       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5101     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5102       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5103     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5104       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5105     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5106       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5107     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5108       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5109     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5110       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5111     /* MMU Domain access control / MPU write buffer control */
5112     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5113       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5114       .writefn = dacr_write, .raw_writefn = raw_write,
5115       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5116                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5117     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5118       .type = ARM_CP_ALIAS,
5119       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5120       .access = PL1_RW,
5121       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5122     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5123       .type = ARM_CP_ALIAS,
5124       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5125       .access = PL1_RW,
5126       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5127     /* We rely on the access checks not allowing the guest to write to the
5128      * state field when SPSel indicates that it's being used as the stack
5129      * pointer.
5130      */
5131     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5132       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5133       .access = PL1_RW, .accessfn = sp_el0_access,
5134       .type = ARM_CP_ALIAS,
5135       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5136     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5137       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5138       .access = PL2_RW, .type = ARM_CP_ALIAS,
5139       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5140     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5141       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5142       .type = ARM_CP_NO_RAW,
5143       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5144     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5145       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5146       .type = ARM_CP_ALIAS,
5147       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
5148       .access = PL2_RW, .accessfn = fpexc32_access },
5149     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5150       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5151       .access = PL2_RW, .resetvalue = 0,
5152       .writefn = dacr_write, .raw_writefn = raw_write,
5153       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5154     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5155       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5156       .access = PL2_RW, .resetvalue = 0,
5157       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5158     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5159       .type = ARM_CP_ALIAS,
5160       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5161       .access = PL2_RW,
5162       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5163     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5164       .type = ARM_CP_ALIAS,
5165       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5166       .access = PL2_RW,
5167       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5168     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5169       .type = ARM_CP_ALIAS,
5170       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5171       .access = PL2_RW,
5172       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5173     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5174       .type = ARM_CP_ALIAS,
5175       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5176       .access = PL2_RW,
5177       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5178     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5179       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5180       .resetvalue = 0,
5181       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5182     { .name = "SDCR", .type = ARM_CP_ALIAS,
5183       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5184       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5185       .writefn = sdcr_write,
5186       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5187     REGINFO_SENTINEL
5188 };
5189 
5190 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
5191 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
5192     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5193       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5194       .access = PL2_RW,
5195       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
5196     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
5197       .type = ARM_CP_NO_RAW,
5198       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5199       .access = PL2_RW,
5200       .type = ARM_CP_CONST, .resetvalue = 0 },
5201     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5202       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5203       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5204     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5205       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5206       .access = PL2_RW,
5207       .type = ARM_CP_CONST, .resetvalue = 0 },
5208     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5209       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5210       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5211     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5212       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5213       .access = PL2_RW, .type = ARM_CP_CONST,
5214       .resetvalue = 0 },
5215     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5216       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5217       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5218     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5219       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5220       .access = PL2_RW, .type = ARM_CP_CONST,
5221       .resetvalue = 0 },
5222     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5223       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5224       .access = PL2_RW, .type = ARM_CP_CONST,
5225       .resetvalue = 0 },
5226     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5227       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5228       .access = PL2_RW, .type = ARM_CP_CONST,
5229       .resetvalue = 0 },
5230     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5231       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5232       .access = PL2_RW, .type = ARM_CP_CONST,
5233       .resetvalue = 0 },
5234     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5235       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5236       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5237     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
5238       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5239       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5240       .type = ARM_CP_CONST, .resetvalue = 0 },
5241     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5242       .cp = 15, .opc1 = 6, .crm = 2,
5243       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5244       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
5245     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5246       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5247       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5248     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5249       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5250       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5251     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5252       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5253       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5254     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5255       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5256       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5257     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5258       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5259       .resetvalue = 0 },
5260     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5261       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5262       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5263     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5264       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5265       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5266     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5267       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5268       .resetvalue = 0 },
5269     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5270       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5271       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5272     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5273       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5274       .resetvalue = 0 },
5275     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5276       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5277       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5278     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5279       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5280       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5281     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5282       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5283       .access = PL2_RW, .accessfn = access_tda,
5284       .type = ARM_CP_CONST, .resetvalue = 0 },
5285     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
5286       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5287       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5288       .type = ARM_CP_CONST, .resetvalue = 0 },
5289     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5290       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5291       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5292     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5293       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5294       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5295     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5296       .type = ARM_CP_CONST,
5297       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5298       .access = PL2_RW, .resetvalue = 0 },
5299     REGINFO_SENTINEL
5300 };
5301 
5302 /* Ditto, but for registers which exist in ARMv8 but not v7 */
5303 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
5304     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5305       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5306       .access = PL2_RW,
5307       .type = ARM_CP_CONST, .resetvalue = 0 },
5308     REGINFO_SENTINEL
5309 };
5310 
5311 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5312 {
5313     ARMCPU *cpu = env_archcpu(env);
5314 
5315     if (arm_feature(env, ARM_FEATURE_V8)) {
5316         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5317     } else {
5318         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5319     }
5320 
5321     if (arm_feature(env, ARM_FEATURE_EL3)) {
5322         valid_mask &= ~HCR_HCD;
5323     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5324         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5325          * However, if we're using the SMC PSCI conduit then QEMU is
5326          * effectively acting like EL3 firmware and so the guest at
5327          * EL2 should retain the ability to prevent EL1 from being
5328          * able to make SMC calls into the ersatz firmware, so in
5329          * that case HCR.TSC should be read/write.
5330          */
5331         valid_mask &= ~HCR_TSC;
5332     }
5333 
5334     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5335         if (cpu_isar_feature(aa64_vh, cpu)) {
5336             valid_mask |= HCR_E2H;
5337         }
5338         if (cpu_isar_feature(aa64_lor, cpu)) {
5339             valid_mask |= HCR_TLOR;
5340         }
5341         if (cpu_isar_feature(aa64_pauth, cpu)) {
5342             valid_mask |= HCR_API | HCR_APK;
5343         }
5344     }
5345 
5346     /* Clear RES0 bits.  */
5347     value &= valid_mask;
5348 
5349     /* These bits change the MMU setup:
5350      * HCR_VM enables stage 2 translation
5351      * HCR_PTW forbids certain page-table setups
5352      * HCR_DC Disables stage1 and enables stage2 translation
5353      */
5354     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
5355         tlb_flush(CPU(cpu));
5356     }
5357     env->cp15.hcr_el2 = value;
5358 
5359     /*
5360      * Updates to VI and VF require us to update the status of
5361      * virtual interrupts, which are the logical OR of these bits
5362      * and the state of the input lines from the GIC. (This requires
5363      * that we have the iothread lock, which is done by marking the
5364      * reginfo structs as ARM_CP_IO.)
5365      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5366      * possible for it to be taken immediately, because VIRQ and
5367      * VFIQ are masked unless running at EL0 or EL1, and HCR
5368      * can only be written at EL2.
5369      */
5370     g_assert(qemu_mutex_iothread_locked());
5371     arm_cpu_update_virq(cpu);
5372     arm_cpu_update_vfiq(cpu);
5373 }
5374 
5375 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5376 {
5377     do_hcr_write(env, value, 0);
5378 }
5379 
5380 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5381                           uint64_t value)
5382 {
5383     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5384     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5385     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5386 }
5387 
5388 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5389                          uint64_t value)
5390 {
5391     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5392     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5393     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5394 }
5395 
5396 /*
5397  * Return the effective value of HCR_EL2.
5398  * Bits that are not included here:
5399  * RW       (read from SCR_EL3.RW as needed)
5400  */
5401 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5402 {
5403     uint64_t ret = env->cp15.hcr_el2;
5404 
5405     if (arm_is_secure_below_el3(env)) {
5406         /*
5407          * "This register has no effect if EL2 is not enabled in the
5408          * current Security state".  This is ARMv8.4-SecEL2 speak for
5409          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5410          *
5411          * Prior to that, the language was "In an implementation that
5412          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5413          * as if this field is 0 for all purposes other than a direct
5414          * read or write access of HCR_EL2".  With lots of enumeration
5415          * on a per-field basis.  In current QEMU, this is condition
5416          * is arm_is_secure_below_el3.
5417          *
5418          * Since the v8.4 language applies to the entire register, and
5419          * appears to be backward compatible, use that.
5420          */
5421         return 0;
5422     }
5423 
5424     /*
5425      * For a cpu that supports both aarch64 and aarch32, we can set bits
5426      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5427      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5428      */
5429     if (!arm_el_is_aa64(env, 2)) {
5430         uint64_t aa32_valid;
5431 
5432         /*
5433          * These bits are up-to-date as of ARMv8.6.
5434          * For HCR, it's easiest to list just the 2 bits that are invalid.
5435          * For HCR2, list those that are valid.
5436          */
5437         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5438         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5439                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5440         ret &= aa32_valid;
5441     }
5442 
5443     if (ret & HCR_TGE) {
5444         /* These bits are up-to-date as of ARMv8.6.  */
5445         if (ret & HCR_E2H) {
5446             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5447                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5448                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5449                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5450                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5451                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5452         } else {
5453             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5454         }
5455         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5456                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5457                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5458                  HCR_TLOR);
5459     }
5460 
5461     return ret;
5462 }
5463 
5464 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5465                            uint64_t value)
5466 {
5467     /*
5468      * For A-profile AArch32 EL3, if NSACR.CP10
5469      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5470      */
5471     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5472         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5473         value &= ~(0x3 << 10);
5474         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5475     }
5476     env->cp15.cptr_el[2] = value;
5477 }
5478 
5479 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5480 {
5481     /*
5482      * For A-profile AArch32 EL3, if NSACR.CP10
5483      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5484      */
5485     uint64_t value = env->cp15.cptr_el[2];
5486 
5487     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5488         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5489         value |= 0x3 << 10;
5490     }
5491     return value;
5492 }
5493 
5494 static const ARMCPRegInfo el2_cp_reginfo[] = {
5495     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5496       .type = ARM_CP_IO,
5497       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5498       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5499       .writefn = hcr_write },
5500     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5501       .type = ARM_CP_ALIAS | ARM_CP_IO,
5502       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5503       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5504       .writefn = hcr_writelow },
5505     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5506       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5507       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5508     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5509       .type = ARM_CP_ALIAS,
5510       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5511       .access = PL2_RW,
5512       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5513     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5514       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5515       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5516     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5517       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5518       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5519     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5520       .type = ARM_CP_ALIAS,
5521       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5522       .access = PL2_RW,
5523       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5524     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5525       .type = ARM_CP_ALIAS,
5526       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5527       .access = PL2_RW,
5528       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5529     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5530       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5531       .access = PL2_RW, .writefn = vbar_write,
5532       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5533       .resetvalue = 0 },
5534     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5535       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5536       .access = PL3_RW, .type = ARM_CP_ALIAS,
5537       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5538     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5539       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5540       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5541       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5542       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5543     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5544       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5545       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5546       .resetvalue = 0 },
5547     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5548       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5549       .access = PL2_RW, .type = ARM_CP_ALIAS,
5550       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5551     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5552       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5553       .access = PL2_RW, .type = ARM_CP_CONST,
5554       .resetvalue = 0 },
5555     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5556     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5557       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5558       .access = PL2_RW, .type = ARM_CP_CONST,
5559       .resetvalue = 0 },
5560     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5561       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5562       .access = PL2_RW, .type = ARM_CP_CONST,
5563       .resetvalue = 0 },
5564     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5565       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5566       .access = PL2_RW, .type = ARM_CP_CONST,
5567       .resetvalue = 0 },
5568     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5569       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5570       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5571       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5572       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5573     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5574       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5575       .type = ARM_CP_ALIAS,
5576       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5577       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5578     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5579       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5580       .access = PL2_RW,
5581       /* no .writefn needed as this can't cause an ASID change;
5582        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5583        */
5584       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5585     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5586       .cp = 15, .opc1 = 6, .crm = 2,
5587       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5588       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5589       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5590       .writefn = vttbr_write },
5591     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5592       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5593       .access = PL2_RW, .writefn = vttbr_write,
5594       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5595     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5596       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5597       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5598       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5599     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5600       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5601       .access = PL2_RW, .resetvalue = 0,
5602       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5603     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5604       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5605       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5606       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5607     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5608       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5609       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5610     { .name = "TLBIALLNSNH",
5611       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5612       .type = ARM_CP_NO_RAW, .access = PL2_W,
5613       .writefn = tlbiall_nsnh_write },
5614     { .name = "TLBIALLNSNHIS",
5615       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5616       .type = ARM_CP_NO_RAW, .access = PL2_W,
5617       .writefn = tlbiall_nsnh_is_write },
5618     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5619       .type = ARM_CP_NO_RAW, .access = PL2_W,
5620       .writefn = tlbiall_hyp_write },
5621     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5622       .type = ARM_CP_NO_RAW, .access = PL2_W,
5623       .writefn = tlbiall_hyp_is_write },
5624     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5625       .type = ARM_CP_NO_RAW, .access = PL2_W,
5626       .writefn = tlbimva_hyp_write },
5627     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5628       .type = ARM_CP_NO_RAW, .access = PL2_W,
5629       .writefn = tlbimva_hyp_is_write },
5630     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5631       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5632       .type = ARM_CP_NO_RAW, .access = PL2_W,
5633       .writefn = tlbi_aa64_alle2_write },
5634     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5635       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5636       .type = ARM_CP_NO_RAW, .access = PL2_W,
5637       .writefn = tlbi_aa64_vae2_write },
5638     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5639       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5640       .access = PL2_W, .type = ARM_CP_NO_RAW,
5641       .writefn = tlbi_aa64_vae2_write },
5642     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5643       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5644       .access = PL2_W, .type = ARM_CP_NO_RAW,
5645       .writefn = tlbi_aa64_alle2is_write },
5646     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5647       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5648       .type = ARM_CP_NO_RAW, .access = PL2_W,
5649       .writefn = tlbi_aa64_vae2is_write },
5650     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5651       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5652       .access = PL2_W, .type = ARM_CP_NO_RAW,
5653       .writefn = tlbi_aa64_vae2is_write },
5654 #ifndef CONFIG_USER_ONLY
5655     /* Unlike the other EL2-related AT operations, these must
5656      * UNDEF from EL3 if EL2 is not implemented, which is why we
5657      * define them here rather than with the rest of the AT ops.
5658      */
5659     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5660       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5661       .access = PL2_W, .accessfn = at_s1e2_access,
5662       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5663     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5664       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5665       .access = PL2_W, .accessfn = at_s1e2_access,
5666       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5667     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5668      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5669      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5670      * to behave as if SCR.NS was 1.
5671      */
5672     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5673       .access = PL2_W,
5674       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5675     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5676       .access = PL2_W,
5677       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5678     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5679       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5680       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5681        * reset values as IMPDEF. We choose to reset to 3 to comply with
5682        * both ARMv7 and ARMv8.
5683        */
5684       .access = PL2_RW, .resetvalue = 3,
5685       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5686     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5687       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5688       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5689       .writefn = gt_cntvoff_write,
5690       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5691     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5692       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5693       .writefn = gt_cntvoff_write,
5694       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5695     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5696       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5697       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5698       .type = ARM_CP_IO, .access = PL2_RW,
5699       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5700     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5701       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5702       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5703       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5704     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5705       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5706       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5707       .resetfn = gt_hyp_timer_reset,
5708       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5709     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5710       .type = ARM_CP_IO,
5711       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5712       .access = PL2_RW,
5713       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5714       .resetvalue = 0,
5715       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5716 #endif
5717     /* The only field of MDCR_EL2 that has a defined architectural reset value
5718      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
5719      * don't implement any PMU event counters, so using zero as a reset
5720      * value for MDCR_EL2 is okay
5721      */
5722     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5723       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5724       .access = PL2_RW, .resetvalue = 0,
5725       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5726     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5727       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5728       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5729       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5730     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5731       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5732       .access = PL2_RW,
5733       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5734     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5735       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5736       .access = PL2_RW,
5737       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5738     REGINFO_SENTINEL
5739 };
5740 
5741 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5742     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5743       .type = ARM_CP_ALIAS | ARM_CP_IO,
5744       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5745       .access = PL2_RW,
5746       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5747       .writefn = hcr_writehigh },
5748     REGINFO_SENTINEL
5749 };
5750 
5751 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5752                                    bool isread)
5753 {
5754     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5755      * At Secure EL1 it traps to EL3.
5756      */
5757     if (arm_current_el(env) == 3) {
5758         return CP_ACCESS_OK;
5759     }
5760     if (arm_is_secure_below_el3(env)) {
5761         return CP_ACCESS_TRAP_EL3;
5762     }
5763     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5764     if (isread) {
5765         return CP_ACCESS_OK;
5766     }
5767     return CP_ACCESS_TRAP_UNCATEGORIZED;
5768 }
5769 
5770 static const ARMCPRegInfo el3_cp_reginfo[] = {
5771     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5772       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5773       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5774       .resetvalue = 0, .writefn = scr_write },
5775     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5776       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5777       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5778       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5779       .writefn = scr_write },
5780     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5781       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5782       .access = PL3_RW, .resetvalue = 0,
5783       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5784     { .name = "SDER",
5785       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5786       .access = PL3_RW, .resetvalue = 0,
5787       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5788     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5789       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5790       .writefn = vbar_write, .resetvalue = 0,
5791       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5792     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5793       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5794       .access = PL3_RW, .resetvalue = 0,
5795       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5796     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5797       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5798       .access = PL3_RW,
5799       /* no .writefn needed as this can't cause an ASID change;
5800        * we must provide a .raw_writefn and .resetfn because we handle
5801        * reset and migration for the AArch32 TTBCR(S), which might be
5802        * using mask and base_mask.
5803        */
5804       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5805       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5806     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5807       .type = ARM_CP_ALIAS,
5808       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5809       .access = PL3_RW,
5810       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5811     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5812       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5813       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5814     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5815       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5816       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5817     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5818       .type = ARM_CP_ALIAS,
5819       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5820       .access = PL3_RW,
5821       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5822     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5823       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5824       .access = PL3_RW, .writefn = vbar_write,
5825       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5826       .resetvalue = 0 },
5827     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5828       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5829       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5830       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5831     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5832       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5833       .access = PL3_RW, .resetvalue = 0,
5834       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5835     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5836       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5837       .access = PL3_RW, .type = ARM_CP_CONST,
5838       .resetvalue = 0 },
5839     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5840       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5841       .access = PL3_RW, .type = ARM_CP_CONST,
5842       .resetvalue = 0 },
5843     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5844       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5845       .access = PL3_RW, .type = ARM_CP_CONST,
5846       .resetvalue = 0 },
5847     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5848       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5849       .access = PL3_W, .type = ARM_CP_NO_RAW,
5850       .writefn = tlbi_aa64_alle3is_write },
5851     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5852       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5853       .access = PL3_W, .type = ARM_CP_NO_RAW,
5854       .writefn = tlbi_aa64_vae3is_write },
5855     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5856       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5857       .access = PL3_W, .type = ARM_CP_NO_RAW,
5858       .writefn = tlbi_aa64_vae3is_write },
5859     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5860       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5861       .access = PL3_W, .type = ARM_CP_NO_RAW,
5862       .writefn = tlbi_aa64_alle3_write },
5863     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5864       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5865       .access = PL3_W, .type = ARM_CP_NO_RAW,
5866       .writefn = tlbi_aa64_vae3_write },
5867     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5868       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5869       .access = PL3_W, .type = ARM_CP_NO_RAW,
5870       .writefn = tlbi_aa64_vae3_write },
5871     REGINFO_SENTINEL
5872 };
5873 
5874 #ifndef CONFIG_USER_ONLY
5875 /* Test if system register redirection is to occur in the current state.  */
5876 static bool redirect_for_e2h(CPUARMState *env)
5877 {
5878     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5879 }
5880 
5881 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5882 {
5883     CPReadFn *readfn;
5884 
5885     if (redirect_for_e2h(env)) {
5886         /* Switch to the saved EL2 version of the register.  */
5887         ri = ri->opaque;
5888         readfn = ri->readfn;
5889     } else {
5890         readfn = ri->orig_readfn;
5891     }
5892     if (readfn == NULL) {
5893         readfn = raw_read;
5894     }
5895     return readfn(env, ri);
5896 }
5897 
5898 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5899                           uint64_t value)
5900 {
5901     CPWriteFn *writefn;
5902 
5903     if (redirect_for_e2h(env)) {
5904         /* Switch to the saved EL2 version of the register.  */
5905         ri = ri->opaque;
5906         writefn = ri->writefn;
5907     } else {
5908         writefn = ri->orig_writefn;
5909     }
5910     if (writefn == NULL) {
5911         writefn = raw_write;
5912     }
5913     writefn(env, ri, value);
5914 }
5915 
5916 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5917 {
5918     struct E2HAlias {
5919         uint32_t src_key, dst_key, new_key;
5920         const char *src_name, *dst_name, *new_name;
5921         bool (*feature)(const ARMISARegisters *id);
5922     };
5923 
5924 #define K(op0, op1, crn, crm, op2) \
5925     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5926 
5927     static const struct E2HAlias aliases[] = {
5928         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5929           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5930         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5931           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5932         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5933           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5934         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5935           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5936         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5937           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5938         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5939           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5940         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5941           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5942         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5943           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5944         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5945           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5946         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5947           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5948         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5949           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5950         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5951           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5952         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5953           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5954         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5955           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5956         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5957           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5958         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5959           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5960 
5961         /*
5962          * Note that redirection of ZCR is mentioned in the description
5963          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5964          * not in the summary table.
5965          */
5966         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5967           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5968 
5969         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5970         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5971     };
5972 #undef K
5973 
5974     size_t i;
5975 
5976     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5977         const struct E2HAlias *a = &aliases[i];
5978         ARMCPRegInfo *src_reg, *dst_reg;
5979 
5980         if (a->feature && !a->feature(&cpu->isar)) {
5981             continue;
5982         }
5983 
5984         src_reg = g_hash_table_lookup(cpu->cp_regs, &a->src_key);
5985         dst_reg = g_hash_table_lookup(cpu->cp_regs, &a->dst_key);
5986         g_assert(src_reg != NULL);
5987         g_assert(dst_reg != NULL);
5988 
5989         /* Cross-compare names to detect typos in the keys.  */
5990         g_assert(strcmp(src_reg->name, a->src_name) == 0);
5991         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
5992 
5993         /* None of the core system registers use opaque; we will.  */
5994         g_assert(src_reg->opaque == NULL);
5995 
5996         /* Create alias before redirection so we dup the right data. */
5997         if (a->new_key) {
5998             ARMCPRegInfo *new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
5999             uint32_t *new_key = g_memdup(&a->new_key, sizeof(uint32_t));
6000             bool ok;
6001 
6002             new_reg->name = a->new_name;
6003             new_reg->type |= ARM_CP_ALIAS;
6004             /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
6005             new_reg->access &= PL2_RW | PL3_RW;
6006 
6007             ok = g_hash_table_insert(cpu->cp_regs, new_key, new_reg);
6008             g_assert(ok);
6009         }
6010 
6011         src_reg->opaque = dst_reg;
6012         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
6013         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
6014         if (!src_reg->raw_readfn) {
6015             src_reg->raw_readfn = raw_read;
6016         }
6017         if (!src_reg->raw_writefn) {
6018             src_reg->raw_writefn = raw_write;
6019         }
6020         src_reg->readfn = el2_e2h_read;
6021         src_reg->writefn = el2_e2h_write;
6022     }
6023 }
6024 #endif
6025 
6026 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
6027                                      bool isread)
6028 {
6029     int cur_el = arm_current_el(env);
6030 
6031     if (cur_el < 2) {
6032         uint64_t hcr = arm_hcr_el2_eff(env);
6033 
6034         if (cur_el == 0) {
6035             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
6036                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
6037                     return CP_ACCESS_TRAP_EL2;
6038                 }
6039             } else {
6040                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
6041                     return CP_ACCESS_TRAP;
6042                 }
6043                 if (hcr & HCR_TID2) {
6044                     return CP_ACCESS_TRAP_EL2;
6045                 }
6046             }
6047         } else if (hcr & HCR_TID2) {
6048             return CP_ACCESS_TRAP_EL2;
6049         }
6050     }
6051 
6052     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
6053         return CP_ACCESS_TRAP_EL2;
6054     }
6055 
6056     return CP_ACCESS_OK;
6057 }
6058 
6059 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
6060                         uint64_t value)
6061 {
6062     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
6063      * read via a bit in OSLSR_EL1.
6064      */
6065     int oslock;
6066 
6067     if (ri->state == ARM_CP_STATE_AA32) {
6068         oslock = (value == 0xC5ACCE55);
6069     } else {
6070         oslock = value & 1;
6071     }
6072 
6073     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
6074 }
6075 
6076 static const ARMCPRegInfo debug_cp_reginfo[] = {
6077     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
6078      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
6079      * unlike DBGDRAR it is never accessible from EL0.
6080      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
6081      * accessor.
6082      */
6083     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
6084       .access = PL0_R, .accessfn = access_tdra,
6085       .type = ARM_CP_CONST, .resetvalue = 0 },
6086     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
6087       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6088       .access = PL1_R, .accessfn = access_tdra,
6089       .type = ARM_CP_CONST, .resetvalue = 0 },
6090     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
6091       .access = PL0_R, .accessfn = access_tdra,
6092       .type = ARM_CP_CONST, .resetvalue = 0 },
6093     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
6094     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
6095       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6096       .access = PL1_RW, .accessfn = access_tda,
6097       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
6098       .resetvalue = 0 },
6099     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
6100      * We don't implement the configurable EL0 access.
6101      */
6102     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
6103       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6104       .type = ARM_CP_ALIAS,
6105       .access = PL1_R, .accessfn = access_tda,
6106       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
6107     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
6108       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
6109       .access = PL1_W, .type = ARM_CP_NO_RAW,
6110       .accessfn = access_tdosa,
6111       .writefn = oslar_write },
6112     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
6113       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
6114       .access = PL1_R, .resetvalue = 10,
6115       .accessfn = access_tdosa,
6116       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6117     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6118     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6119       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6120       .access = PL1_RW, .accessfn = access_tdosa,
6121       .type = ARM_CP_NOP },
6122     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6123      * implement vector catch debug events yet.
6124      */
6125     { .name = "DBGVCR",
6126       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6127       .access = PL1_RW, .accessfn = access_tda,
6128       .type = ARM_CP_NOP },
6129     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6130      * to save and restore a 32-bit guest's DBGVCR)
6131      */
6132     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6133       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6134       .access = PL2_RW, .accessfn = access_tda,
6135       .type = ARM_CP_NOP },
6136     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6137      * Channel but Linux may try to access this register. The 32-bit
6138      * alias is DBGDCCINT.
6139      */
6140     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6141       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6142       .access = PL1_RW, .accessfn = access_tda,
6143       .type = ARM_CP_NOP },
6144     REGINFO_SENTINEL
6145 };
6146 
6147 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6148     /* 64 bit access versions of the (dummy) debug registers */
6149     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6150       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6151     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6152       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6153     REGINFO_SENTINEL
6154 };
6155 
6156 /* Return the exception level to which exceptions should be taken
6157  * via SVEAccessTrap.  If an exception should be routed through
6158  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6159  * take care of raising that exception.
6160  * C.f. the ARM pseudocode function CheckSVEEnabled.
6161  */
6162 int sve_exception_el(CPUARMState *env, int el)
6163 {
6164 #ifndef CONFIG_USER_ONLY
6165     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6166 
6167     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6168         bool disabled = false;
6169 
6170         /* The CPACR.ZEN controls traps to EL1:
6171          * 0, 2 : trap EL0 and EL1 accesses
6172          * 1    : trap only EL0 accesses
6173          * 3    : trap no accesses
6174          */
6175         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
6176             disabled = true;
6177         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
6178             disabled = el == 0;
6179         }
6180         if (disabled) {
6181             /* route_to_el2 */
6182             return hcr_el2 & HCR_TGE ? 2 : 1;
6183         }
6184 
6185         /* Check CPACR.FPEN.  */
6186         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
6187             disabled = true;
6188         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
6189             disabled = el == 0;
6190         }
6191         if (disabled) {
6192             return 0;
6193         }
6194     }
6195 
6196     /* CPTR_EL2.  Since TZ and TFP are positive,
6197      * they will be zero when EL2 is not present.
6198      */
6199     if (el <= 2 && !arm_is_secure_below_el3(env)) {
6200         if (env->cp15.cptr_el[2] & CPTR_TZ) {
6201             return 2;
6202         }
6203         if (env->cp15.cptr_el[2] & CPTR_TFP) {
6204             return 0;
6205         }
6206     }
6207 
6208     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6209     if (arm_feature(env, ARM_FEATURE_EL3)
6210         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6211         return 3;
6212     }
6213 #endif
6214     return 0;
6215 }
6216 
6217 static uint32_t sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6218 {
6219     uint32_t end_len;
6220 
6221     end_len = start_len &= 0xf;
6222     if (!test_bit(start_len, cpu->sve_vq_map)) {
6223         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6224         assert(end_len < start_len);
6225     }
6226     return end_len;
6227 }
6228 
6229 /*
6230  * Given that SVE is enabled, return the vector length for EL.
6231  */
6232 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6233 {
6234     ARMCPU *cpu = env_archcpu(env);
6235     uint32_t zcr_len = cpu->sve_max_vq - 1;
6236 
6237     if (el <= 1) {
6238         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6239     }
6240     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6241         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6242     }
6243     if (arm_feature(env, ARM_FEATURE_EL3)) {
6244         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6245     }
6246 
6247     return sve_zcr_get_valid_len(cpu, zcr_len);
6248 }
6249 
6250 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6251                       uint64_t value)
6252 {
6253     int cur_el = arm_current_el(env);
6254     int old_len = sve_zcr_len_for_el(env, cur_el);
6255     int new_len;
6256 
6257     /* Bits other than [3:0] are RAZ/WI.  */
6258     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6259     raw_write(env, ri, value & 0xf);
6260 
6261     /*
6262      * Because we arrived here, we know both FP and SVE are enabled;
6263      * otherwise we would have trapped access to the ZCR_ELn register.
6264      */
6265     new_len = sve_zcr_len_for_el(env, cur_el);
6266     if (new_len < old_len) {
6267         aarch64_sve_narrow_vq(env, new_len + 1);
6268     }
6269 }
6270 
6271 static const ARMCPRegInfo zcr_el1_reginfo = {
6272     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6273     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6274     .access = PL1_RW, .type = ARM_CP_SVE,
6275     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6276     .writefn = zcr_write, .raw_writefn = raw_write
6277 };
6278 
6279 static const ARMCPRegInfo zcr_el2_reginfo = {
6280     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6281     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6282     .access = PL2_RW, .type = ARM_CP_SVE,
6283     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6284     .writefn = zcr_write, .raw_writefn = raw_write
6285 };
6286 
6287 static const ARMCPRegInfo zcr_no_el2_reginfo = {
6288     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6289     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6290     .access = PL2_RW, .type = ARM_CP_SVE,
6291     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
6292 };
6293 
6294 static const ARMCPRegInfo zcr_el3_reginfo = {
6295     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6296     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6297     .access = PL3_RW, .type = ARM_CP_SVE,
6298     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6299     .writefn = zcr_write, .raw_writefn = raw_write
6300 };
6301 
6302 void hw_watchpoint_update(ARMCPU *cpu, int n)
6303 {
6304     CPUARMState *env = &cpu->env;
6305     vaddr len = 0;
6306     vaddr wvr = env->cp15.dbgwvr[n];
6307     uint64_t wcr = env->cp15.dbgwcr[n];
6308     int mask;
6309     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6310 
6311     if (env->cpu_watchpoint[n]) {
6312         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6313         env->cpu_watchpoint[n] = NULL;
6314     }
6315 
6316     if (!extract64(wcr, 0, 1)) {
6317         /* E bit clear : watchpoint disabled */
6318         return;
6319     }
6320 
6321     switch (extract64(wcr, 3, 2)) {
6322     case 0:
6323         /* LSC 00 is reserved and must behave as if the wp is disabled */
6324         return;
6325     case 1:
6326         flags |= BP_MEM_READ;
6327         break;
6328     case 2:
6329         flags |= BP_MEM_WRITE;
6330         break;
6331     case 3:
6332         flags |= BP_MEM_ACCESS;
6333         break;
6334     }
6335 
6336     /* Attempts to use both MASK and BAS fields simultaneously are
6337      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6338      * thus generating a watchpoint for every byte in the masked region.
6339      */
6340     mask = extract64(wcr, 24, 4);
6341     if (mask == 1 || mask == 2) {
6342         /* Reserved values of MASK; we must act as if the mask value was
6343          * some non-reserved value, or as if the watchpoint were disabled.
6344          * We choose the latter.
6345          */
6346         return;
6347     } else if (mask) {
6348         /* Watchpoint covers an aligned area up to 2GB in size */
6349         len = 1ULL << mask;
6350         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6351          * whether the watchpoint fires when the unmasked bits match; we opt
6352          * to generate the exceptions.
6353          */
6354         wvr &= ~(len - 1);
6355     } else {
6356         /* Watchpoint covers bytes defined by the byte address select bits */
6357         int bas = extract64(wcr, 5, 8);
6358         int basstart;
6359 
6360         if (extract64(wvr, 2, 1)) {
6361             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6362              * ignored, and BAS[3:0] define which bytes to watch.
6363              */
6364             bas &= 0xf;
6365         }
6366 
6367         if (bas == 0) {
6368             /* This must act as if the watchpoint is disabled */
6369             return;
6370         }
6371 
6372         /* The BAS bits are supposed to be programmed to indicate a contiguous
6373          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6374          * we fire for each byte in the word/doubleword addressed by the WVR.
6375          * We choose to ignore any non-zero bits after the first range of 1s.
6376          */
6377         basstart = ctz32(bas);
6378         len = cto32(bas >> basstart);
6379         wvr += basstart;
6380     }
6381 
6382     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6383                           &env->cpu_watchpoint[n]);
6384 }
6385 
6386 void hw_watchpoint_update_all(ARMCPU *cpu)
6387 {
6388     int i;
6389     CPUARMState *env = &cpu->env;
6390 
6391     /* Completely clear out existing QEMU watchpoints and our array, to
6392      * avoid possible stale entries following migration load.
6393      */
6394     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6395     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6396 
6397     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6398         hw_watchpoint_update(cpu, i);
6399     }
6400 }
6401 
6402 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6403                          uint64_t value)
6404 {
6405     ARMCPU *cpu = env_archcpu(env);
6406     int i = ri->crm;
6407 
6408     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
6409      * register reads and behaves as if values written are sign extended.
6410      * Bits [1:0] are RES0.
6411      */
6412     value = sextract64(value, 0, 49) & ~3ULL;
6413 
6414     raw_write(env, ri, value);
6415     hw_watchpoint_update(cpu, i);
6416 }
6417 
6418 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6419                          uint64_t value)
6420 {
6421     ARMCPU *cpu = env_archcpu(env);
6422     int i = ri->crm;
6423 
6424     raw_write(env, ri, value);
6425     hw_watchpoint_update(cpu, i);
6426 }
6427 
6428 void hw_breakpoint_update(ARMCPU *cpu, int n)
6429 {
6430     CPUARMState *env = &cpu->env;
6431     uint64_t bvr = env->cp15.dbgbvr[n];
6432     uint64_t bcr = env->cp15.dbgbcr[n];
6433     vaddr addr;
6434     int bt;
6435     int flags = BP_CPU;
6436 
6437     if (env->cpu_breakpoint[n]) {
6438         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6439         env->cpu_breakpoint[n] = NULL;
6440     }
6441 
6442     if (!extract64(bcr, 0, 1)) {
6443         /* E bit clear : watchpoint disabled */
6444         return;
6445     }
6446 
6447     bt = extract64(bcr, 20, 4);
6448 
6449     switch (bt) {
6450     case 4: /* unlinked address mismatch (reserved if AArch64) */
6451     case 5: /* linked address mismatch (reserved if AArch64) */
6452         qemu_log_mask(LOG_UNIMP,
6453                       "arm: address mismatch breakpoint types not implemented\n");
6454         return;
6455     case 0: /* unlinked address match */
6456     case 1: /* linked address match */
6457     {
6458         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
6459          * we behave as if the register was sign extended. Bits [1:0] are
6460          * RES0. The BAS field is used to allow setting breakpoints on 16
6461          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6462          * a bp will fire if the addresses covered by the bp and the addresses
6463          * covered by the insn overlap but the insn doesn't start at the
6464          * start of the bp address range. We choose to require the insn and
6465          * the bp to have the same address. The constraints on writing to
6466          * BAS enforced in dbgbcr_write mean we have only four cases:
6467          *  0b0000  => no breakpoint
6468          *  0b0011  => breakpoint on addr
6469          *  0b1100  => breakpoint on addr + 2
6470          *  0b1111  => breakpoint on addr
6471          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6472          */
6473         int bas = extract64(bcr, 5, 4);
6474         addr = sextract64(bvr, 0, 49) & ~3ULL;
6475         if (bas == 0) {
6476             return;
6477         }
6478         if (bas == 0xc) {
6479             addr += 2;
6480         }
6481         break;
6482     }
6483     case 2: /* unlinked context ID match */
6484     case 8: /* unlinked VMID match (reserved if no EL2) */
6485     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6486         qemu_log_mask(LOG_UNIMP,
6487                       "arm: unlinked context breakpoint types not implemented\n");
6488         return;
6489     case 9: /* linked VMID match (reserved if no EL2) */
6490     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6491     case 3: /* linked context ID match */
6492     default:
6493         /* We must generate no events for Linked context matches (unless
6494          * they are linked to by some other bp/wp, which is handled in
6495          * updates for the linking bp/wp). We choose to also generate no events
6496          * for reserved values.
6497          */
6498         return;
6499     }
6500 
6501     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6502 }
6503 
6504 void hw_breakpoint_update_all(ARMCPU *cpu)
6505 {
6506     int i;
6507     CPUARMState *env = &cpu->env;
6508 
6509     /* Completely clear out existing QEMU breakpoints and our array, to
6510      * avoid possible stale entries following migration load.
6511      */
6512     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6513     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6514 
6515     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6516         hw_breakpoint_update(cpu, i);
6517     }
6518 }
6519 
6520 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6521                          uint64_t value)
6522 {
6523     ARMCPU *cpu = env_archcpu(env);
6524     int i = ri->crm;
6525 
6526     raw_write(env, ri, value);
6527     hw_breakpoint_update(cpu, i);
6528 }
6529 
6530 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6531                          uint64_t value)
6532 {
6533     ARMCPU *cpu = env_archcpu(env);
6534     int i = ri->crm;
6535 
6536     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6537      * copy of BAS[0].
6538      */
6539     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6540     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6541 
6542     raw_write(env, ri, value);
6543     hw_breakpoint_update(cpu, i);
6544 }
6545 
6546 static void define_debug_regs(ARMCPU *cpu)
6547 {
6548     /* Define v7 and v8 architectural debug registers.
6549      * These are just dummy implementations for now.
6550      */
6551     int i;
6552     int wrps, brps, ctx_cmps;
6553     ARMCPRegInfo dbgdidr = {
6554         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
6555         .access = PL0_R, .accessfn = access_tda,
6556         .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6557     };
6558 
6559     /* Note that all these register fields hold "number of Xs minus 1". */
6560     brps = arm_num_brps(cpu);
6561     wrps = arm_num_wrps(cpu);
6562     ctx_cmps = arm_num_ctx_cmps(cpu);
6563 
6564     assert(ctx_cmps <= brps);
6565 
6566     define_one_arm_cp_reg(cpu, &dbgdidr);
6567     define_arm_cp_regs(cpu, debug_cp_reginfo);
6568 
6569     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6570         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6571     }
6572 
6573     for (i = 0; i < brps; i++) {
6574         ARMCPRegInfo dbgregs[] = {
6575             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6576               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6577               .access = PL1_RW, .accessfn = access_tda,
6578               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6579               .writefn = dbgbvr_write, .raw_writefn = raw_write
6580             },
6581             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6582               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6583               .access = PL1_RW, .accessfn = access_tda,
6584               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6585               .writefn = dbgbcr_write, .raw_writefn = raw_write
6586             },
6587             REGINFO_SENTINEL
6588         };
6589         define_arm_cp_regs(cpu, dbgregs);
6590     }
6591 
6592     for (i = 0; i < wrps; i++) {
6593         ARMCPRegInfo dbgregs[] = {
6594             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6595               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6596               .access = PL1_RW, .accessfn = access_tda,
6597               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6598               .writefn = dbgwvr_write, .raw_writefn = raw_write
6599             },
6600             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6601               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6602               .access = PL1_RW, .accessfn = access_tda,
6603               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6604               .writefn = dbgwcr_write, .raw_writefn = raw_write
6605             },
6606             REGINFO_SENTINEL
6607         };
6608         define_arm_cp_regs(cpu, dbgregs);
6609     }
6610 }
6611 
6612 static void define_pmu_regs(ARMCPU *cpu)
6613 {
6614     /*
6615      * v7 performance monitor control register: same implementor
6616      * field as main ID register, and we implement four counters in
6617      * addition to the cycle count register.
6618      */
6619     unsigned int i, pmcrn = 4;
6620     ARMCPRegInfo pmcr = {
6621         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6622         .access = PL0_RW,
6623         .type = ARM_CP_IO | ARM_CP_ALIAS,
6624         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6625         .accessfn = pmreg_access, .writefn = pmcr_write,
6626         .raw_writefn = raw_write,
6627     };
6628     ARMCPRegInfo pmcr64 = {
6629         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6630         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6631         .access = PL0_RW, .accessfn = pmreg_access,
6632         .type = ARM_CP_IO,
6633         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6634         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6635                       PMCRLC,
6636         .writefn = pmcr_write, .raw_writefn = raw_write,
6637     };
6638     define_one_arm_cp_reg(cpu, &pmcr);
6639     define_one_arm_cp_reg(cpu, &pmcr64);
6640     for (i = 0; i < pmcrn; i++) {
6641         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6642         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6643         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6644         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6645         ARMCPRegInfo pmev_regs[] = {
6646             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6647               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6648               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6649               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6650               .accessfn = pmreg_access },
6651             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6652               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6653               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6654               .type = ARM_CP_IO,
6655               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6656               .raw_readfn = pmevcntr_rawread,
6657               .raw_writefn = pmevcntr_rawwrite },
6658             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6659               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6660               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6661               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6662               .accessfn = pmreg_access },
6663             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6664               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6665               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6666               .type = ARM_CP_IO,
6667               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6668               .raw_writefn = pmevtyper_rawwrite },
6669             REGINFO_SENTINEL
6670         };
6671         define_arm_cp_regs(cpu, pmev_regs);
6672         g_free(pmevcntr_name);
6673         g_free(pmevcntr_el0_name);
6674         g_free(pmevtyper_name);
6675         g_free(pmevtyper_el0_name);
6676     }
6677     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6678         ARMCPRegInfo v81_pmu_regs[] = {
6679             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6680               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6681               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6682               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6683             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6684               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6685               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6686               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6687             REGINFO_SENTINEL
6688         };
6689         define_arm_cp_regs(cpu, v81_pmu_regs);
6690     }
6691     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6692         static const ARMCPRegInfo v84_pmmir = {
6693             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6694             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6695             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6696             .resetvalue = 0
6697         };
6698         define_one_arm_cp_reg(cpu, &v84_pmmir);
6699     }
6700 }
6701 
6702 /* We don't know until after realize whether there's a GICv3
6703  * attached, and that is what registers the gicv3 sysregs.
6704  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6705  * at runtime.
6706  */
6707 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6708 {
6709     ARMCPU *cpu = env_archcpu(env);
6710     uint64_t pfr1 = cpu->id_pfr1;
6711 
6712     if (env->gicv3state) {
6713         pfr1 |= 1 << 28;
6714     }
6715     return pfr1;
6716 }
6717 
6718 #ifndef CONFIG_USER_ONLY
6719 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6720 {
6721     ARMCPU *cpu = env_archcpu(env);
6722     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6723 
6724     if (env->gicv3state) {
6725         pfr0 |= 1 << 24;
6726     }
6727     return pfr0;
6728 }
6729 #endif
6730 
6731 /* Shared logic between LORID and the rest of the LOR* registers.
6732  * Secure state has already been delt with.
6733  */
6734 static CPAccessResult access_lor_ns(CPUARMState *env)
6735 {
6736     int el = arm_current_el(env);
6737 
6738     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6739         return CP_ACCESS_TRAP_EL2;
6740     }
6741     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6742         return CP_ACCESS_TRAP_EL3;
6743     }
6744     return CP_ACCESS_OK;
6745 }
6746 
6747 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
6748                                    bool isread)
6749 {
6750     if (arm_is_secure_below_el3(env)) {
6751         /* Access ok in secure mode.  */
6752         return CP_ACCESS_OK;
6753     }
6754     return access_lor_ns(env);
6755 }
6756 
6757 static CPAccessResult access_lor_other(CPUARMState *env,
6758                                        const ARMCPRegInfo *ri, bool isread)
6759 {
6760     if (arm_is_secure_below_el3(env)) {
6761         /* Access denied in secure mode.  */
6762         return CP_ACCESS_TRAP;
6763     }
6764     return access_lor_ns(env);
6765 }
6766 
6767 /*
6768  * A trivial implementation of ARMv8.1-LOR leaves all of these
6769  * registers fixed at 0, which indicates that there are zero
6770  * supported Limited Ordering regions.
6771  */
6772 static const ARMCPRegInfo lor_reginfo[] = {
6773     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6774       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6775       .access = PL1_RW, .accessfn = access_lor_other,
6776       .type = ARM_CP_CONST, .resetvalue = 0 },
6777     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6778       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6779       .access = PL1_RW, .accessfn = access_lor_other,
6780       .type = ARM_CP_CONST, .resetvalue = 0 },
6781     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6782       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6783       .access = PL1_RW, .accessfn = access_lor_other,
6784       .type = ARM_CP_CONST, .resetvalue = 0 },
6785     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6786       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6787       .access = PL1_RW, .accessfn = access_lor_other,
6788       .type = ARM_CP_CONST, .resetvalue = 0 },
6789     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6790       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6791       .access = PL1_R, .accessfn = access_lorid,
6792       .type = ARM_CP_CONST, .resetvalue = 0 },
6793     REGINFO_SENTINEL
6794 };
6795 
6796 #ifdef TARGET_AARCH64
6797 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6798                                    bool isread)
6799 {
6800     int el = arm_current_el(env);
6801 
6802     if (el < 2 &&
6803         arm_feature(env, ARM_FEATURE_EL2) &&
6804         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6805         return CP_ACCESS_TRAP_EL2;
6806     }
6807     if (el < 3 &&
6808         arm_feature(env, ARM_FEATURE_EL3) &&
6809         !(env->cp15.scr_el3 & SCR_APK)) {
6810         return CP_ACCESS_TRAP_EL3;
6811     }
6812     return CP_ACCESS_OK;
6813 }
6814 
6815 static const ARMCPRegInfo pauth_reginfo[] = {
6816     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6817       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6818       .access = PL1_RW, .accessfn = access_pauth,
6819       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6820     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6821       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6822       .access = PL1_RW, .accessfn = access_pauth,
6823       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6824     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6825       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6826       .access = PL1_RW, .accessfn = access_pauth,
6827       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6828     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6829       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6830       .access = PL1_RW, .accessfn = access_pauth,
6831       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6832     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6833       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6834       .access = PL1_RW, .accessfn = access_pauth,
6835       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6836     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6837       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6838       .access = PL1_RW, .accessfn = access_pauth,
6839       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6840     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6841       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6842       .access = PL1_RW, .accessfn = access_pauth,
6843       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6844     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6845       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6846       .access = PL1_RW, .accessfn = access_pauth,
6847       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6848     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6849       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6850       .access = PL1_RW, .accessfn = access_pauth,
6851       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6852     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6853       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6854       .access = PL1_RW, .accessfn = access_pauth,
6855       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6856     REGINFO_SENTINEL
6857 };
6858 
6859 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
6860 {
6861     Error *err = NULL;
6862     uint64_t ret;
6863 
6864     /* Success sets NZCV = 0000.  */
6865     env->NF = env->CF = env->VF = 0, env->ZF = 1;
6866 
6867     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
6868         /*
6869          * ??? Failed, for unknown reasons in the crypto subsystem.
6870          * The best we can do is log the reason and return the
6871          * timed-out indication to the guest.  There is no reason
6872          * we know to expect this failure to be transitory, so the
6873          * guest may well hang retrying the operation.
6874          */
6875         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
6876                       ri->name, error_get_pretty(err));
6877         error_free(err);
6878 
6879         env->ZF = 0; /* NZCF = 0100 */
6880         return 0;
6881     }
6882     return ret;
6883 }
6884 
6885 /* We do not support re-seeding, so the two registers operate the same.  */
6886 static const ARMCPRegInfo rndr_reginfo[] = {
6887     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
6888       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6889       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
6890       .access = PL0_R, .readfn = rndr_readfn },
6891     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
6892       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6893       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
6894       .access = PL0_R, .readfn = rndr_readfn },
6895     REGINFO_SENTINEL
6896 };
6897 
6898 #ifndef CONFIG_USER_ONLY
6899 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
6900                           uint64_t value)
6901 {
6902     ARMCPU *cpu = env_archcpu(env);
6903     /* CTR_EL0 System register -> DminLine, bits [19:16] */
6904     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
6905     uint64_t vaddr_in = (uint64_t) value;
6906     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
6907     void *haddr;
6908     int mem_idx = cpu_mmu_index(env, false);
6909 
6910     /* This won't be crossing page boundaries */
6911     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
6912     if (haddr) {
6913 
6914         ram_addr_t offset;
6915         MemoryRegion *mr;
6916 
6917         /* RCU lock is already being held */
6918         mr = memory_region_from_host(haddr, &offset);
6919 
6920         if (mr) {
6921             memory_region_do_writeback(mr, offset, dline_size);
6922         }
6923     }
6924 }
6925 
6926 static const ARMCPRegInfo dcpop_reg[] = {
6927     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
6928       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
6929       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6930       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6931     REGINFO_SENTINEL
6932 };
6933 
6934 static const ARMCPRegInfo dcpodp_reg[] = {
6935     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
6936       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
6937       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6938       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6939     REGINFO_SENTINEL
6940 };
6941 #endif /*CONFIG_USER_ONLY*/
6942 
6943 #endif
6944 
6945 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
6946                                      bool isread)
6947 {
6948     int el = arm_current_el(env);
6949 
6950     if (el == 0) {
6951         uint64_t sctlr = arm_sctlr(env, el);
6952         if (!(sctlr & SCTLR_EnRCTX)) {
6953             return CP_ACCESS_TRAP;
6954         }
6955     } else if (el == 1) {
6956         uint64_t hcr = arm_hcr_el2_eff(env);
6957         if (hcr & HCR_NV) {
6958             return CP_ACCESS_TRAP_EL2;
6959         }
6960     }
6961     return CP_ACCESS_OK;
6962 }
6963 
6964 static const ARMCPRegInfo predinv_reginfo[] = {
6965     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
6966       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
6967       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6968     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
6969       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
6970       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6971     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
6972       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
6973       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6974     /*
6975      * Note the AArch32 opcodes have a different OPC1.
6976      */
6977     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
6978       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
6979       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6980     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
6981       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
6982       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6983     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
6984       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
6985       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6986     REGINFO_SENTINEL
6987 };
6988 
6989 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
6990 {
6991     /* Read the high 32 bits of the current CCSIDR */
6992     return extract64(ccsidr_read(env, ri), 32, 32);
6993 }
6994 
6995 static const ARMCPRegInfo ccsidr2_reginfo[] = {
6996     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
6997       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
6998       .access = PL1_R,
6999       .accessfn = access_aa64_tid2,
7000       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7001     REGINFO_SENTINEL
7002 };
7003 
7004 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7005                                        bool isread)
7006 {
7007     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7008         return CP_ACCESS_TRAP_EL2;
7009     }
7010 
7011     return CP_ACCESS_OK;
7012 }
7013 
7014 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7015                                        bool isread)
7016 {
7017     if (arm_feature(env, ARM_FEATURE_V8)) {
7018         return access_aa64_tid3(env, ri, isread);
7019     }
7020 
7021     return CP_ACCESS_OK;
7022 }
7023 
7024 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7025                                      bool isread)
7026 {
7027     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7028         return CP_ACCESS_TRAP_EL2;
7029     }
7030 
7031     return CP_ACCESS_OK;
7032 }
7033 
7034 static const ARMCPRegInfo jazelle_regs[] = {
7035     { .name = "JIDR",
7036       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7037       .access = PL1_R, .accessfn = access_jazelle,
7038       .type = ARM_CP_CONST, .resetvalue = 0 },
7039     { .name = "JOSCR",
7040       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7041       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7042     { .name = "JMCR",
7043       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7044       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7045     REGINFO_SENTINEL
7046 };
7047 
7048 static const ARMCPRegInfo vhe_reginfo[] = {
7049     { .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7050       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7051       .access = PL2_RW,
7052       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2]) },
7053     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7054       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7055       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7056       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7057 #ifndef CONFIG_USER_ONLY
7058     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7059       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7060       .fieldoffset =
7061         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7062       .type = ARM_CP_IO, .access = PL2_RW,
7063       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7064     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7065       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7066       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7067       .resetfn = gt_hv_timer_reset,
7068       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7069     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7070       .type = ARM_CP_IO,
7071       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7072       .access = PL2_RW,
7073       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7074       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7075     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7076       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7077       .type = ARM_CP_IO | ARM_CP_ALIAS,
7078       .access = PL2_RW, .accessfn = e2h_access,
7079       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7080       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7081     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7082       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7083       .type = ARM_CP_IO | ARM_CP_ALIAS,
7084       .access = PL2_RW, .accessfn = e2h_access,
7085       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7086       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7087     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7088       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7089       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7090       .access = PL2_RW, .accessfn = e2h_access,
7091       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7092     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7093       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7094       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7095       .access = PL2_RW, .accessfn = e2h_access,
7096       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7097     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7098       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7099       .type = ARM_CP_IO | ARM_CP_ALIAS,
7100       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7101       .access = PL2_RW, .accessfn = e2h_access,
7102       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7103     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7104       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7105       .type = ARM_CP_IO | ARM_CP_ALIAS,
7106       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7107       .access = PL2_RW, .accessfn = e2h_access,
7108       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7109 #endif
7110     REGINFO_SENTINEL
7111 };
7112 
7113 #ifndef CONFIG_USER_ONLY
7114 static const ARMCPRegInfo ats1e1_reginfo[] = {
7115     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7116       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7117       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7118       .writefn = ats_write64 },
7119     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7120       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7121       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7122       .writefn = ats_write64 },
7123     REGINFO_SENTINEL
7124 };
7125 
7126 static const ARMCPRegInfo ats1cp_reginfo[] = {
7127     { .name = "ATS1CPRP",
7128       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7129       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7130       .writefn = ats_write },
7131     { .name = "ATS1CPWP",
7132       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7133       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7134       .writefn = ats_write },
7135     REGINFO_SENTINEL
7136 };
7137 #endif
7138 
7139 /*
7140  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7141  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7142  * is non-zero, which is never for ARMv7, optionally in ARMv8
7143  * and mandatorily for ARMv8.2 and up.
7144  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7145  * implementation is RAZ/WI we can ignore this detail, as we
7146  * do for ACTLR.
7147  */
7148 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7149     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7150       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7151       .access = PL1_RW, .accessfn = access_tacr,
7152       .type = ARM_CP_CONST, .resetvalue = 0 },
7153     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7154       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7155       .access = PL2_RW, .type = ARM_CP_CONST,
7156       .resetvalue = 0 },
7157     REGINFO_SENTINEL
7158 };
7159 
7160 void register_cp_regs_for_features(ARMCPU *cpu)
7161 {
7162     /* Register all the coprocessor registers based on feature bits */
7163     CPUARMState *env = &cpu->env;
7164     if (arm_feature(env, ARM_FEATURE_M)) {
7165         /* M profile has no coprocessor registers */
7166         return;
7167     }
7168 
7169     define_arm_cp_regs(cpu, cp_reginfo);
7170     if (!arm_feature(env, ARM_FEATURE_V8)) {
7171         /* Must go early as it is full of wildcards that may be
7172          * overridden by later definitions.
7173          */
7174         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7175     }
7176 
7177     if (arm_feature(env, ARM_FEATURE_V6)) {
7178         /* The ID registers all have impdef reset values */
7179         ARMCPRegInfo v6_idregs[] = {
7180             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7181               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7182               .access = PL1_R, .type = ARM_CP_CONST,
7183               .accessfn = access_aa32_tid3,
7184               .resetvalue = cpu->id_pfr0 },
7185             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7186              * the value of the GIC field until after we define these regs.
7187              */
7188             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7189               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7190               .access = PL1_R, .type = ARM_CP_NO_RAW,
7191               .accessfn = access_aa32_tid3,
7192               .readfn = id_pfr1_read,
7193               .writefn = arm_cp_write_ignore },
7194             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7195               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7196               .access = PL1_R, .type = ARM_CP_CONST,
7197               .accessfn = access_aa32_tid3,
7198               .resetvalue = cpu->isar.id_dfr0 },
7199             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7200               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7201               .access = PL1_R, .type = ARM_CP_CONST,
7202               .accessfn = access_aa32_tid3,
7203               .resetvalue = cpu->id_afr0 },
7204             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7205               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7206               .access = PL1_R, .type = ARM_CP_CONST,
7207               .accessfn = access_aa32_tid3,
7208               .resetvalue = cpu->isar.id_mmfr0 },
7209             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7210               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7211               .access = PL1_R, .type = ARM_CP_CONST,
7212               .accessfn = access_aa32_tid3,
7213               .resetvalue = cpu->isar.id_mmfr1 },
7214             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7215               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7216               .access = PL1_R, .type = ARM_CP_CONST,
7217               .accessfn = access_aa32_tid3,
7218               .resetvalue = cpu->isar.id_mmfr2 },
7219             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7220               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7221               .access = PL1_R, .type = ARM_CP_CONST,
7222               .accessfn = access_aa32_tid3,
7223               .resetvalue = cpu->isar.id_mmfr3 },
7224             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7225               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7226               .access = PL1_R, .type = ARM_CP_CONST,
7227               .accessfn = access_aa32_tid3,
7228               .resetvalue = cpu->isar.id_isar0 },
7229             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7230               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7231               .access = PL1_R, .type = ARM_CP_CONST,
7232               .accessfn = access_aa32_tid3,
7233               .resetvalue = cpu->isar.id_isar1 },
7234             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7235               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7236               .access = PL1_R, .type = ARM_CP_CONST,
7237               .accessfn = access_aa32_tid3,
7238               .resetvalue = cpu->isar.id_isar2 },
7239             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7240               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7241               .access = PL1_R, .type = ARM_CP_CONST,
7242               .accessfn = access_aa32_tid3,
7243               .resetvalue = cpu->isar.id_isar3 },
7244             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7245               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7246               .access = PL1_R, .type = ARM_CP_CONST,
7247               .accessfn = access_aa32_tid3,
7248               .resetvalue = cpu->isar.id_isar4 },
7249             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7250               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7251               .access = PL1_R, .type = ARM_CP_CONST,
7252               .accessfn = access_aa32_tid3,
7253               .resetvalue = cpu->isar.id_isar5 },
7254             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7255               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7256               .access = PL1_R, .type = ARM_CP_CONST,
7257               .accessfn = access_aa32_tid3,
7258               .resetvalue = cpu->isar.id_mmfr4 },
7259             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7260               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7261               .access = PL1_R, .type = ARM_CP_CONST,
7262               .accessfn = access_aa32_tid3,
7263               .resetvalue = cpu->isar.id_isar6 },
7264             REGINFO_SENTINEL
7265         };
7266         define_arm_cp_regs(cpu, v6_idregs);
7267         define_arm_cp_regs(cpu, v6_cp_reginfo);
7268     } else {
7269         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7270     }
7271     if (arm_feature(env, ARM_FEATURE_V6K)) {
7272         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7273     }
7274     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7275         !arm_feature(env, ARM_FEATURE_PMSA)) {
7276         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7277     }
7278     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7279         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7280     }
7281     if (arm_feature(env, ARM_FEATURE_V7)) {
7282         ARMCPRegInfo clidr = {
7283             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7284             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7285             .access = PL1_R, .type = ARM_CP_CONST,
7286             .accessfn = access_aa64_tid2,
7287             .resetvalue = cpu->clidr
7288         };
7289         define_one_arm_cp_reg(cpu, &clidr);
7290         define_arm_cp_regs(cpu, v7_cp_reginfo);
7291         define_debug_regs(cpu);
7292         define_pmu_regs(cpu);
7293     } else {
7294         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7295     }
7296     if (arm_feature(env, ARM_FEATURE_V8)) {
7297         /* AArch64 ID registers, which all have impdef reset values.
7298          * Note that within the ID register ranges the unused slots
7299          * must all RAZ, not UNDEF; future architecture versions may
7300          * define new registers here.
7301          */
7302         ARMCPRegInfo v8_idregs[] = {
7303             /*
7304              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7305              * emulation because we don't know the right value for the
7306              * GIC field until after we define these regs.
7307              */
7308             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7309               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7310               .access = PL1_R,
7311 #ifdef CONFIG_USER_ONLY
7312               .type = ARM_CP_CONST,
7313               .resetvalue = cpu->isar.id_aa64pfr0
7314 #else
7315               .type = ARM_CP_NO_RAW,
7316               .accessfn = access_aa64_tid3,
7317               .readfn = id_aa64pfr0_read,
7318               .writefn = arm_cp_write_ignore
7319 #endif
7320             },
7321             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7322               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7323               .access = PL1_R, .type = ARM_CP_CONST,
7324               .accessfn = access_aa64_tid3,
7325               .resetvalue = cpu->isar.id_aa64pfr1},
7326             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7327               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7328               .access = PL1_R, .type = ARM_CP_CONST,
7329               .accessfn = access_aa64_tid3,
7330               .resetvalue = 0 },
7331             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7332               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7333               .access = PL1_R, .type = ARM_CP_CONST,
7334               .accessfn = access_aa64_tid3,
7335               .resetvalue = 0 },
7336             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7337               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7338               .access = PL1_R, .type = ARM_CP_CONST,
7339               .accessfn = access_aa64_tid3,
7340               /* At present, only SVEver == 0 is defined anyway.  */
7341               .resetvalue = 0 },
7342             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7343               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7344               .access = PL1_R, .type = ARM_CP_CONST,
7345               .accessfn = access_aa64_tid3,
7346               .resetvalue = 0 },
7347             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7348               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7349               .access = PL1_R, .type = ARM_CP_CONST,
7350               .accessfn = access_aa64_tid3,
7351               .resetvalue = 0 },
7352             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7353               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7354               .access = PL1_R, .type = ARM_CP_CONST,
7355               .accessfn = access_aa64_tid3,
7356               .resetvalue = 0 },
7357             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7358               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7359               .access = PL1_R, .type = ARM_CP_CONST,
7360               .accessfn = access_aa64_tid3,
7361               .resetvalue = cpu->isar.id_aa64dfr0 },
7362             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7363               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7364               .access = PL1_R, .type = ARM_CP_CONST,
7365               .accessfn = access_aa64_tid3,
7366               .resetvalue = cpu->isar.id_aa64dfr1 },
7367             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7368               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7369               .access = PL1_R, .type = ARM_CP_CONST,
7370               .accessfn = access_aa64_tid3,
7371               .resetvalue = 0 },
7372             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7373               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7374               .access = PL1_R, .type = ARM_CP_CONST,
7375               .accessfn = access_aa64_tid3,
7376               .resetvalue = 0 },
7377             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7378               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7379               .access = PL1_R, .type = ARM_CP_CONST,
7380               .accessfn = access_aa64_tid3,
7381               .resetvalue = cpu->id_aa64afr0 },
7382             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7383               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7384               .access = PL1_R, .type = ARM_CP_CONST,
7385               .accessfn = access_aa64_tid3,
7386               .resetvalue = cpu->id_aa64afr1 },
7387             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7388               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7389               .access = PL1_R, .type = ARM_CP_CONST,
7390               .accessfn = access_aa64_tid3,
7391               .resetvalue = 0 },
7392             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7393               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7394               .access = PL1_R, .type = ARM_CP_CONST,
7395               .accessfn = access_aa64_tid3,
7396               .resetvalue = 0 },
7397             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7398               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7399               .access = PL1_R, .type = ARM_CP_CONST,
7400               .accessfn = access_aa64_tid3,
7401               .resetvalue = cpu->isar.id_aa64isar0 },
7402             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7403               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7404               .access = PL1_R, .type = ARM_CP_CONST,
7405               .accessfn = access_aa64_tid3,
7406               .resetvalue = cpu->isar.id_aa64isar1 },
7407             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7408               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7409               .access = PL1_R, .type = ARM_CP_CONST,
7410               .accessfn = access_aa64_tid3,
7411               .resetvalue = 0 },
7412             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7413               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7414               .access = PL1_R, .type = ARM_CP_CONST,
7415               .accessfn = access_aa64_tid3,
7416               .resetvalue = 0 },
7417             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7418               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7419               .access = PL1_R, .type = ARM_CP_CONST,
7420               .accessfn = access_aa64_tid3,
7421               .resetvalue = 0 },
7422             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7423               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7424               .access = PL1_R, .type = ARM_CP_CONST,
7425               .accessfn = access_aa64_tid3,
7426               .resetvalue = 0 },
7427             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7428               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7429               .access = PL1_R, .type = ARM_CP_CONST,
7430               .accessfn = access_aa64_tid3,
7431               .resetvalue = 0 },
7432             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7433               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7434               .access = PL1_R, .type = ARM_CP_CONST,
7435               .accessfn = access_aa64_tid3,
7436               .resetvalue = 0 },
7437             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7438               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7439               .access = PL1_R, .type = ARM_CP_CONST,
7440               .accessfn = access_aa64_tid3,
7441               .resetvalue = cpu->isar.id_aa64mmfr0 },
7442             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7443               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7444               .access = PL1_R, .type = ARM_CP_CONST,
7445               .accessfn = access_aa64_tid3,
7446               .resetvalue = cpu->isar.id_aa64mmfr1 },
7447             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7448               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7449               .access = PL1_R, .type = ARM_CP_CONST,
7450               .accessfn = access_aa64_tid3,
7451               .resetvalue = cpu->isar.id_aa64mmfr2 },
7452             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7453               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7454               .access = PL1_R, .type = ARM_CP_CONST,
7455               .accessfn = access_aa64_tid3,
7456               .resetvalue = 0 },
7457             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7458               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7459               .access = PL1_R, .type = ARM_CP_CONST,
7460               .accessfn = access_aa64_tid3,
7461               .resetvalue = 0 },
7462             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7463               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7464               .access = PL1_R, .type = ARM_CP_CONST,
7465               .accessfn = access_aa64_tid3,
7466               .resetvalue = 0 },
7467             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7468               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7469               .access = PL1_R, .type = ARM_CP_CONST,
7470               .accessfn = access_aa64_tid3,
7471               .resetvalue = 0 },
7472             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7473               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7474               .access = PL1_R, .type = ARM_CP_CONST,
7475               .accessfn = access_aa64_tid3,
7476               .resetvalue = 0 },
7477             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7478               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7479               .access = PL1_R, .type = ARM_CP_CONST,
7480               .accessfn = access_aa64_tid3,
7481               .resetvalue = cpu->isar.mvfr0 },
7482             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7483               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7484               .access = PL1_R, .type = ARM_CP_CONST,
7485               .accessfn = access_aa64_tid3,
7486               .resetvalue = cpu->isar.mvfr1 },
7487             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7488               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7489               .access = PL1_R, .type = ARM_CP_CONST,
7490               .accessfn = access_aa64_tid3,
7491               .resetvalue = cpu->isar.mvfr2 },
7492             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7493               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7494               .access = PL1_R, .type = ARM_CP_CONST,
7495               .accessfn = access_aa64_tid3,
7496               .resetvalue = 0 },
7497             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7498               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7499               .access = PL1_R, .type = ARM_CP_CONST,
7500               .accessfn = access_aa64_tid3,
7501               .resetvalue = 0 },
7502             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7503               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7504               .access = PL1_R, .type = ARM_CP_CONST,
7505               .accessfn = access_aa64_tid3,
7506               .resetvalue = 0 },
7507             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7508               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7509               .access = PL1_R, .type = ARM_CP_CONST,
7510               .accessfn = access_aa64_tid3,
7511               .resetvalue = 0 },
7512             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7513               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7514               .access = PL1_R, .type = ARM_CP_CONST,
7515               .accessfn = access_aa64_tid3,
7516               .resetvalue = 0 },
7517             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7518               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7519               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7520               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7521             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7522               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7523               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7524               .resetvalue = cpu->pmceid0 },
7525             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7526               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7527               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7528               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7529             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7530               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7531               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7532               .resetvalue = cpu->pmceid1 },
7533             REGINFO_SENTINEL
7534         };
7535 #ifdef CONFIG_USER_ONLY
7536         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7537             { .name = "ID_AA64PFR0_EL1",
7538               .exported_bits = 0x000f000f00ff0000,
7539               .fixed_bits    = 0x0000000000000011 },
7540             { .name = "ID_AA64PFR1_EL1",
7541               .exported_bits = 0x00000000000000f0 },
7542             { .name = "ID_AA64PFR*_EL1_RESERVED",
7543               .is_glob = true                     },
7544             { .name = "ID_AA64ZFR0_EL1"           },
7545             { .name = "ID_AA64MMFR0_EL1",
7546               .fixed_bits    = 0x00000000ff000000 },
7547             { .name = "ID_AA64MMFR1_EL1"          },
7548             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7549               .is_glob = true                     },
7550             { .name = "ID_AA64DFR0_EL1",
7551               .fixed_bits    = 0x0000000000000006 },
7552             { .name = "ID_AA64DFR1_EL1"           },
7553             { .name = "ID_AA64DFR*_EL1_RESERVED",
7554               .is_glob = true                     },
7555             { .name = "ID_AA64AFR*",
7556               .is_glob = true                     },
7557             { .name = "ID_AA64ISAR0_EL1",
7558               .exported_bits = 0x00fffffff0fffff0 },
7559             { .name = "ID_AA64ISAR1_EL1",
7560               .exported_bits = 0x000000f0ffffffff },
7561             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7562               .is_glob = true                     },
7563             REGUSERINFO_SENTINEL
7564         };
7565         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7566 #endif
7567         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7568         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7569             !arm_feature(env, ARM_FEATURE_EL2)) {
7570             ARMCPRegInfo rvbar = {
7571                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7572                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7573                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
7574             };
7575             define_one_arm_cp_reg(cpu, &rvbar);
7576         }
7577         define_arm_cp_regs(cpu, v8_idregs);
7578         define_arm_cp_regs(cpu, v8_cp_reginfo);
7579     }
7580     if (arm_feature(env, ARM_FEATURE_EL2)) {
7581         uint64_t vmpidr_def = mpidr_read_val(env);
7582         ARMCPRegInfo vpidr_regs[] = {
7583             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7584               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7585               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7586               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
7587               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7588             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7589               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7590               .access = PL2_RW, .resetvalue = cpu->midr,
7591               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7592             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7593               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7594               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7595               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
7596               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7597             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7598               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7599               .access = PL2_RW,
7600               .resetvalue = vmpidr_def,
7601               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7602             REGINFO_SENTINEL
7603         };
7604         define_arm_cp_regs(cpu, vpidr_regs);
7605         define_arm_cp_regs(cpu, el2_cp_reginfo);
7606         if (arm_feature(env, ARM_FEATURE_V8)) {
7607             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7608         }
7609         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7610         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7611             ARMCPRegInfo rvbar = {
7612                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
7613                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
7614                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
7615             };
7616             define_one_arm_cp_reg(cpu, &rvbar);
7617         }
7618     } else {
7619         /* If EL2 is missing but higher ELs are enabled, we need to
7620          * register the no_el2 reginfos.
7621          */
7622         if (arm_feature(env, ARM_FEATURE_EL3)) {
7623             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
7624              * of MIDR_EL1 and MPIDR_EL1.
7625              */
7626             ARMCPRegInfo vpidr_regs[] = {
7627                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7628                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7629                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
7630                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
7631                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7632                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7633                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7634                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
7635                   .type = ARM_CP_NO_RAW,
7636                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
7637                 REGINFO_SENTINEL
7638             };
7639             define_arm_cp_regs(cpu, vpidr_regs);
7640             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
7641             if (arm_feature(env, ARM_FEATURE_V8)) {
7642                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
7643             }
7644         }
7645     }
7646     if (arm_feature(env, ARM_FEATURE_EL3)) {
7647         define_arm_cp_regs(cpu, el3_cp_reginfo);
7648         ARMCPRegInfo el3_regs[] = {
7649             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
7650               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
7651               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
7652             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
7653               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
7654               .access = PL3_RW,
7655               .raw_writefn = raw_write, .writefn = sctlr_write,
7656               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
7657               .resetvalue = cpu->reset_sctlr },
7658             REGINFO_SENTINEL
7659         };
7660 
7661         define_arm_cp_regs(cpu, el3_regs);
7662     }
7663     /* The behaviour of NSACR is sufficiently various that we don't
7664      * try to describe it in a single reginfo:
7665      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
7666      *     reads as constant 0xc00 from NS EL1 and NS EL2
7667      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
7668      *  if v7 without EL3, register doesn't exist
7669      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
7670      */
7671     if (arm_feature(env, ARM_FEATURE_EL3)) {
7672         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7673             ARMCPRegInfo nsacr = {
7674                 .name = "NSACR", .type = ARM_CP_CONST,
7675                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7676                 .access = PL1_RW, .accessfn = nsacr_access,
7677                 .resetvalue = 0xc00
7678             };
7679             define_one_arm_cp_reg(cpu, &nsacr);
7680         } else {
7681             ARMCPRegInfo nsacr = {
7682                 .name = "NSACR",
7683                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7684                 .access = PL3_RW | PL1_R,
7685                 .resetvalue = 0,
7686                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
7687             };
7688             define_one_arm_cp_reg(cpu, &nsacr);
7689         }
7690     } else {
7691         if (arm_feature(env, ARM_FEATURE_V8)) {
7692             ARMCPRegInfo nsacr = {
7693                 .name = "NSACR", .type = ARM_CP_CONST,
7694                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7695                 .access = PL1_R,
7696                 .resetvalue = 0xc00
7697             };
7698             define_one_arm_cp_reg(cpu, &nsacr);
7699         }
7700     }
7701 
7702     if (arm_feature(env, ARM_FEATURE_PMSA)) {
7703         if (arm_feature(env, ARM_FEATURE_V6)) {
7704             /* PMSAv6 not implemented */
7705             assert(arm_feature(env, ARM_FEATURE_V7));
7706             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7707             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
7708         } else {
7709             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
7710         }
7711     } else {
7712         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7713         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
7714         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
7715         if (cpu_isar_feature(aa32_hpd, cpu)) {
7716             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
7717         }
7718     }
7719     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
7720         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
7721     }
7722     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
7723         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
7724     }
7725     if (arm_feature(env, ARM_FEATURE_VAPA)) {
7726         define_arm_cp_regs(cpu, vapa_cp_reginfo);
7727     }
7728     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
7729         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
7730     }
7731     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
7732         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
7733     }
7734     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
7735         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
7736     }
7737     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
7738         define_arm_cp_regs(cpu, omap_cp_reginfo);
7739     }
7740     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
7741         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
7742     }
7743     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7744         define_arm_cp_regs(cpu, xscale_cp_reginfo);
7745     }
7746     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
7747         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
7748     }
7749     if (arm_feature(env, ARM_FEATURE_LPAE)) {
7750         define_arm_cp_regs(cpu, lpae_cp_reginfo);
7751     }
7752     if (cpu_isar_feature(aa32_jazelle, cpu)) {
7753         define_arm_cp_regs(cpu, jazelle_regs);
7754     }
7755     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
7756      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
7757      * be read-only (ie write causes UNDEF exception).
7758      */
7759     {
7760         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
7761             /* Pre-v8 MIDR space.
7762              * Note that the MIDR isn't a simple constant register because
7763              * of the TI925 behaviour where writes to another register can
7764              * cause the MIDR value to change.
7765              *
7766              * Unimplemented registers in the c15 0 0 0 space default to
7767              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
7768              * and friends override accordingly.
7769              */
7770             { .name = "MIDR",
7771               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
7772               .access = PL1_R, .resetvalue = cpu->midr,
7773               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
7774               .readfn = midr_read,
7775               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7776               .type = ARM_CP_OVERRIDE },
7777             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
7778             { .name = "DUMMY",
7779               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
7780               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7781             { .name = "DUMMY",
7782               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
7783               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7784             { .name = "DUMMY",
7785               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
7786               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7787             { .name = "DUMMY",
7788               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
7789               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7790             { .name = "DUMMY",
7791               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
7792               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7793             REGINFO_SENTINEL
7794         };
7795         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
7796             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
7797               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
7798               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
7799               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7800               .readfn = midr_read },
7801             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
7802             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7803               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
7804               .access = PL1_R, .resetvalue = cpu->midr },
7805             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7806               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
7807               .access = PL1_R, .resetvalue = cpu->midr },
7808             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
7809               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
7810               .access = PL1_R,
7811               .accessfn = access_aa64_tid1,
7812               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
7813             REGINFO_SENTINEL
7814         };
7815         ARMCPRegInfo id_cp_reginfo[] = {
7816             /* These are common to v8 and pre-v8 */
7817             { .name = "CTR",
7818               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
7819               .access = PL1_R, .accessfn = ctr_el0_access,
7820               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
7821             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
7822               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
7823               .access = PL0_R, .accessfn = ctr_el0_access,
7824               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
7825             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
7826             { .name = "TCMTR",
7827               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
7828               .access = PL1_R,
7829               .accessfn = access_aa32_tid1,
7830               .type = ARM_CP_CONST, .resetvalue = 0 },
7831             REGINFO_SENTINEL
7832         };
7833         /* TLBTR is specific to VMSA */
7834         ARMCPRegInfo id_tlbtr_reginfo = {
7835               .name = "TLBTR",
7836               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
7837               .access = PL1_R,
7838               .accessfn = access_aa32_tid1,
7839               .type = ARM_CP_CONST, .resetvalue = 0,
7840         };
7841         /* MPUIR is specific to PMSA V6+ */
7842         ARMCPRegInfo id_mpuir_reginfo = {
7843               .name = "MPUIR",
7844               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
7845               .access = PL1_R, .type = ARM_CP_CONST,
7846               .resetvalue = cpu->pmsav7_dregion << 8
7847         };
7848         ARMCPRegInfo crn0_wi_reginfo = {
7849             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
7850             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
7851             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
7852         };
7853 #ifdef CONFIG_USER_ONLY
7854         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
7855             { .name = "MIDR_EL1",
7856               .exported_bits = 0x00000000ffffffff },
7857             { .name = "REVIDR_EL1"                },
7858             REGUSERINFO_SENTINEL
7859         };
7860         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
7861 #endif
7862         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
7863             arm_feature(env, ARM_FEATURE_STRONGARM)) {
7864             ARMCPRegInfo *r;
7865             /* Register the blanket "writes ignored" value first to cover the
7866              * whole space. Then update the specific ID registers to allow write
7867              * access, so that they ignore writes rather than causing them to
7868              * UNDEF.
7869              */
7870             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
7871             for (r = id_pre_v8_midr_cp_reginfo;
7872                  r->type != ARM_CP_SENTINEL; r++) {
7873                 r->access = PL1_RW;
7874             }
7875             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
7876                 r->access = PL1_RW;
7877             }
7878             id_mpuir_reginfo.access = PL1_RW;
7879             id_tlbtr_reginfo.access = PL1_RW;
7880         }
7881         if (arm_feature(env, ARM_FEATURE_V8)) {
7882             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
7883         } else {
7884             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
7885         }
7886         define_arm_cp_regs(cpu, id_cp_reginfo);
7887         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
7888             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
7889         } else if (arm_feature(env, ARM_FEATURE_V7)) {
7890             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
7891         }
7892     }
7893 
7894     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
7895         ARMCPRegInfo mpidr_cp_reginfo[] = {
7896             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
7897               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
7898               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
7899             REGINFO_SENTINEL
7900         };
7901 #ifdef CONFIG_USER_ONLY
7902         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
7903             { .name = "MPIDR_EL1",
7904               .fixed_bits = 0x0000000080000000 },
7905             REGUSERINFO_SENTINEL
7906         };
7907         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
7908 #endif
7909         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
7910     }
7911 
7912     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
7913         ARMCPRegInfo auxcr_reginfo[] = {
7914             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
7915               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
7916               .access = PL1_RW, .accessfn = access_tacr,
7917               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
7918             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
7919               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
7920               .access = PL2_RW, .type = ARM_CP_CONST,
7921               .resetvalue = 0 },
7922             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
7923               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
7924               .access = PL3_RW, .type = ARM_CP_CONST,
7925               .resetvalue = 0 },
7926             REGINFO_SENTINEL
7927         };
7928         define_arm_cp_regs(cpu, auxcr_reginfo);
7929         if (cpu_isar_feature(aa32_ac2, cpu)) {
7930             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
7931         }
7932     }
7933 
7934     if (arm_feature(env, ARM_FEATURE_CBAR)) {
7935         /*
7936          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
7937          * There are two flavours:
7938          *  (1) older 32-bit only cores have a simple 32-bit CBAR
7939          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
7940          *      32-bit register visible to AArch32 at a different encoding
7941          *      to the "flavour 1" register and with the bits rearranged to
7942          *      be able to squash a 64-bit address into the 32-bit view.
7943          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
7944          * in future if we support AArch32-only configs of some of the
7945          * AArch64 cores we might need to add a specific feature flag
7946          * to indicate cores with "flavour 2" CBAR.
7947          */
7948         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7949             /* 32 bit view is [31:18] 0...0 [43:32]. */
7950             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
7951                 | extract64(cpu->reset_cbar, 32, 12);
7952             ARMCPRegInfo cbar_reginfo[] = {
7953                 { .name = "CBAR",
7954                   .type = ARM_CP_CONST,
7955                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
7956                   .access = PL1_R, .resetvalue = cbar32 },
7957                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
7958                   .type = ARM_CP_CONST,
7959                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
7960                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
7961                 REGINFO_SENTINEL
7962             };
7963             /* We don't implement a r/w 64 bit CBAR currently */
7964             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
7965             define_arm_cp_regs(cpu, cbar_reginfo);
7966         } else {
7967             ARMCPRegInfo cbar = {
7968                 .name = "CBAR",
7969                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
7970                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
7971                 .fieldoffset = offsetof(CPUARMState,
7972                                         cp15.c15_config_base_address)
7973             };
7974             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
7975                 cbar.access = PL1_R;
7976                 cbar.fieldoffset = 0;
7977                 cbar.type = ARM_CP_CONST;
7978             }
7979             define_one_arm_cp_reg(cpu, &cbar);
7980         }
7981     }
7982 
7983     if (arm_feature(env, ARM_FEATURE_VBAR)) {
7984         ARMCPRegInfo vbar_cp_reginfo[] = {
7985             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
7986               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
7987               .access = PL1_RW, .writefn = vbar_write,
7988               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
7989                                      offsetof(CPUARMState, cp15.vbar_ns) },
7990               .resetvalue = 0 },
7991             REGINFO_SENTINEL
7992         };
7993         define_arm_cp_regs(cpu, vbar_cp_reginfo);
7994     }
7995 
7996     /* Generic registers whose values depend on the implementation */
7997     {
7998         ARMCPRegInfo sctlr = {
7999             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8000             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8001             .access = PL1_RW, .accessfn = access_tvm_trvm,
8002             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8003                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8004             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8005             .raw_writefn = raw_write,
8006         };
8007         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8008             /* Normally we would always end the TB on an SCTLR write, but Linux
8009              * arch/arm/mach-pxa/sleep.S expects two instructions following
8010              * an MMU enable to execute from cache.  Imitate this behaviour.
8011              */
8012             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8013         }
8014         define_one_arm_cp_reg(cpu, &sctlr);
8015     }
8016 
8017     if (cpu_isar_feature(aa64_lor, cpu)) {
8018         define_arm_cp_regs(cpu, lor_reginfo);
8019     }
8020     if (cpu_isar_feature(aa64_pan, cpu)) {
8021         define_one_arm_cp_reg(cpu, &pan_reginfo);
8022     }
8023 #ifndef CONFIG_USER_ONLY
8024     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8025         define_arm_cp_regs(cpu, ats1e1_reginfo);
8026     }
8027     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8028         define_arm_cp_regs(cpu, ats1cp_reginfo);
8029     }
8030 #endif
8031     if (cpu_isar_feature(aa64_uao, cpu)) {
8032         define_one_arm_cp_reg(cpu, &uao_reginfo);
8033     }
8034 
8035     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8036         define_arm_cp_regs(cpu, vhe_reginfo);
8037     }
8038 
8039     if (cpu_isar_feature(aa64_sve, cpu)) {
8040         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
8041         if (arm_feature(env, ARM_FEATURE_EL2)) {
8042             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
8043         } else {
8044             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
8045         }
8046         if (arm_feature(env, ARM_FEATURE_EL3)) {
8047             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
8048         }
8049     }
8050 
8051 #ifdef TARGET_AARCH64
8052     if (cpu_isar_feature(aa64_pauth, cpu)) {
8053         define_arm_cp_regs(cpu, pauth_reginfo);
8054     }
8055     if (cpu_isar_feature(aa64_rndr, cpu)) {
8056         define_arm_cp_regs(cpu, rndr_reginfo);
8057     }
8058 #ifndef CONFIG_USER_ONLY
8059     /* Data Cache clean instructions up to PoP */
8060     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8061         define_one_arm_cp_reg(cpu, dcpop_reg);
8062 
8063         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8064             define_one_arm_cp_reg(cpu, dcpodp_reg);
8065         }
8066     }
8067 #endif /*CONFIG_USER_ONLY*/
8068 #endif
8069 
8070     if (cpu_isar_feature(any_predinv, cpu)) {
8071         define_arm_cp_regs(cpu, predinv_reginfo);
8072     }
8073 
8074     if (cpu_isar_feature(any_ccidx, cpu)) {
8075         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8076     }
8077 
8078 #ifndef CONFIG_USER_ONLY
8079     /*
8080      * Register redirections and aliases must be done last,
8081      * after the registers from the other extensions have been defined.
8082      */
8083     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8084         define_arm_vh_e2h_redirects_aliases(cpu);
8085     }
8086 #endif
8087 }
8088 
8089 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
8090 {
8091     CPUState *cs = CPU(cpu);
8092     CPUARMState *env = &cpu->env;
8093 
8094     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8095         /*
8096          * The lower part of each SVE register aliases to the FPU
8097          * registers so we don't need to include both.
8098          */
8099 #ifdef TARGET_AARCH64
8100         if (isar_feature_aa64_sve(&cpu->isar)) {
8101             gdb_register_coprocessor(cs, arm_gdb_get_svereg, arm_gdb_set_svereg,
8102                                      arm_gen_dynamic_svereg_xml(cs, cs->gdb_num_regs),
8103                                      "sve-registers.xml", 0);
8104         } else
8105 #endif
8106         {
8107             gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
8108                                      aarch64_fpu_gdb_set_reg,
8109                                      34, "aarch64-fpu.xml", 0);
8110         }
8111     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
8112         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8113                                  51, "arm-neon.xml", 0);
8114     } else if (cpu_isar_feature(aa32_simd_r32, cpu)) {
8115         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8116                                  35, "arm-vfp3.xml", 0);
8117     } else if (cpu_isar_feature(aa32_vfp_simd, cpu)) {
8118         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8119                                  19, "arm-vfp.xml", 0);
8120     }
8121     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
8122                              arm_gen_dynamic_sysreg_xml(cs, cs->gdb_num_regs),
8123                              "system-registers.xml", 0);
8124 
8125 }
8126 
8127 /* Sort alphabetically by type name, except for "any". */
8128 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8129 {
8130     ObjectClass *class_a = (ObjectClass *)a;
8131     ObjectClass *class_b = (ObjectClass *)b;
8132     const char *name_a, *name_b;
8133 
8134     name_a = object_class_get_name(class_a);
8135     name_b = object_class_get_name(class_b);
8136     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8137         return 1;
8138     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8139         return -1;
8140     } else {
8141         return strcmp(name_a, name_b);
8142     }
8143 }
8144 
8145 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8146 {
8147     ObjectClass *oc = data;
8148     const char *typename;
8149     char *name;
8150 
8151     typename = object_class_get_name(oc);
8152     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8153     qemu_printf("  %s\n", name);
8154     g_free(name);
8155 }
8156 
8157 void arm_cpu_list(void)
8158 {
8159     GSList *list;
8160 
8161     list = object_class_get_list(TYPE_ARM_CPU, false);
8162     list = g_slist_sort(list, arm_cpu_list_compare);
8163     qemu_printf("Available CPUs:\n");
8164     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8165     g_slist_free(list);
8166 }
8167 
8168 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8169 {
8170     ObjectClass *oc = data;
8171     CpuDefinitionInfoList **cpu_list = user_data;
8172     CpuDefinitionInfoList *entry;
8173     CpuDefinitionInfo *info;
8174     const char *typename;
8175 
8176     typename = object_class_get_name(oc);
8177     info = g_malloc0(sizeof(*info));
8178     info->name = g_strndup(typename,
8179                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8180     info->q_typename = g_strdup(typename);
8181 
8182     entry = g_malloc0(sizeof(*entry));
8183     entry->value = info;
8184     entry->next = *cpu_list;
8185     *cpu_list = entry;
8186 }
8187 
8188 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8189 {
8190     CpuDefinitionInfoList *cpu_list = NULL;
8191     GSList *list;
8192 
8193     list = object_class_get_list(TYPE_ARM_CPU, false);
8194     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8195     g_slist_free(list);
8196 
8197     return cpu_list;
8198 }
8199 
8200 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8201                                    void *opaque, int state, int secstate,
8202                                    int crm, int opc1, int opc2,
8203                                    const char *name)
8204 {
8205     /* Private utility function for define_one_arm_cp_reg_with_opaque():
8206      * add a single reginfo struct to the hash table.
8207      */
8208     uint32_t *key = g_new(uint32_t, 1);
8209     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
8210     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
8211     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
8212 
8213     r2->name = g_strdup(name);
8214     /* Reset the secure state to the specific incoming state.  This is
8215      * necessary as the register may have been defined with both states.
8216      */
8217     r2->secure = secstate;
8218 
8219     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8220         /* Register is banked (using both entries in array).
8221          * Overwriting fieldoffset as the array is only used to define
8222          * banked registers but later only fieldoffset is used.
8223          */
8224         r2->fieldoffset = r->bank_fieldoffsets[ns];
8225     }
8226 
8227     if (state == ARM_CP_STATE_AA32) {
8228         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8229             /* If the register is banked then we don't need to migrate or
8230              * reset the 32-bit instance in certain cases:
8231              *
8232              * 1) If the register has both 32-bit and 64-bit instances then we
8233              *    can count on the 64-bit instance taking care of the
8234              *    non-secure bank.
8235              * 2) If ARMv8 is enabled then we can count on a 64-bit version
8236              *    taking care of the secure bank.  This requires that separate
8237              *    32 and 64-bit definitions are provided.
8238              */
8239             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8240                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
8241                 r2->type |= ARM_CP_ALIAS;
8242             }
8243         } else if ((secstate != r->secure) && !ns) {
8244             /* The register is not banked so we only want to allow migration of
8245              * the non-secure instance.
8246              */
8247             r2->type |= ARM_CP_ALIAS;
8248         }
8249 
8250         if (r->state == ARM_CP_STATE_BOTH) {
8251             /* We assume it is a cp15 register if the .cp field is left unset.
8252              */
8253             if (r2->cp == 0) {
8254                 r2->cp = 15;
8255             }
8256 
8257 #ifdef HOST_WORDS_BIGENDIAN
8258             if (r2->fieldoffset) {
8259                 r2->fieldoffset += sizeof(uint32_t);
8260             }
8261 #endif
8262         }
8263     }
8264     if (state == ARM_CP_STATE_AA64) {
8265         /* To allow abbreviation of ARMCPRegInfo
8266          * definitions, we treat cp == 0 as equivalent to
8267          * the value for "standard guest-visible sysreg".
8268          * STATE_BOTH definitions are also always "standard
8269          * sysreg" in their AArch64 view (the .cp value may
8270          * be non-zero for the benefit of the AArch32 view).
8271          */
8272         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8273             r2->cp = CP_REG_ARM64_SYSREG_CP;
8274         }
8275         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
8276                                   r2->opc0, opc1, opc2);
8277     } else {
8278         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
8279     }
8280     if (opaque) {
8281         r2->opaque = opaque;
8282     }
8283     /* reginfo passed to helpers is correct for the actual access,
8284      * and is never ARM_CP_STATE_BOTH:
8285      */
8286     r2->state = state;
8287     /* Make sure reginfo passed to helpers for wildcarded regs
8288      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
8289      */
8290     r2->crm = crm;
8291     r2->opc1 = opc1;
8292     r2->opc2 = opc2;
8293     /* By convention, for wildcarded registers only the first
8294      * entry is used for migration; the others are marked as
8295      * ALIAS so we don't try to transfer the register
8296      * multiple times. Special registers (ie NOP/WFI) are
8297      * never migratable and not even raw-accessible.
8298      */
8299     if ((r->type & ARM_CP_SPECIAL)) {
8300         r2->type |= ARM_CP_NO_RAW;
8301     }
8302     if (((r->crm == CP_ANY) && crm != 0) ||
8303         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8304         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8305         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8306     }
8307 
8308     /* Check that raw accesses are either forbidden or handled. Note that
8309      * we can't assert this earlier because the setup of fieldoffset for
8310      * banked registers has to be done first.
8311      */
8312     if (!(r2->type & ARM_CP_NO_RAW)) {
8313         assert(!raw_accessors_invalid(r2));
8314     }
8315 
8316     /* Overriding of an existing definition must be explicitly
8317      * requested.
8318      */
8319     if (!(r->type & ARM_CP_OVERRIDE)) {
8320         ARMCPRegInfo *oldreg;
8321         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
8322         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
8323             fprintf(stderr, "Register redefined: cp=%d %d bit "
8324                     "crn=%d crm=%d opc1=%d opc2=%d, "
8325                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
8326                     r2->crn, r2->crm, r2->opc1, r2->opc2,
8327                     oldreg->name, r2->name);
8328             g_assert_not_reached();
8329         }
8330     }
8331     g_hash_table_insert(cpu->cp_regs, key, r2);
8332 }
8333 
8334 
8335 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8336                                        const ARMCPRegInfo *r, void *opaque)
8337 {
8338     /* Define implementations of coprocessor registers.
8339      * We store these in a hashtable because typically
8340      * there are less than 150 registers in a space which
8341      * is 16*16*16*8*8 = 262144 in size.
8342      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8343      * If a register is defined twice then the second definition is
8344      * used, so this can be used to define some generic registers and
8345      * then override them with implementation specific variations.
8346      * At least one of the original and the second definition should
8347      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8348      * against accidental use.
8349      *
8350      * The state field defines whether the register is to be
8351      * visible in the AArch32 or AArch64 execution state. If the
8352      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8353      * reginfo structure for the AArch32 view, which sees the lower
8354      * 32 bits of the 64 bit register.
8355      *
8356      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8357      * be wildcarded. AArch64 registers are always considered to be 64
8358      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8359      * the register, if any.
8360      */
8361     int crm, opc1, opc2, state;
8362     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8363     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8364     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8365     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8366     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8367     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8368     /* 64 bit registers have only CRm and Opc1 fields */
8369     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8370     /* op0 only exists in the AArch64 encodings */
8371     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8372     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8373     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8374     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8375      * encodes a minimum access level for the register. We roll this
8376      * runtime check into our general permission check code, so check
8377      * here that the reginfo's specified permissions are strict enough
8378      * to encompass the generic architectural permission check.
8379      */
8380     if (r->state != ARM_CP_STATE_AA32) {
8381         int mask = 0;
8382         switch (r->opc1) {
8383         case 0:
8384             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8385             mask = PL0U_R | PL1_RW;
8386             break;
8387         case 1: case 2:
8388             /* min_EL EL1 */
8389             mask = PL1_RW;
8390             break;
8391         case 3:
8392             /* min_EL EL0 */
8393             mask = PL0_RW;
8394             break;
8395         case 4:
8396         case 5:
8397             /* min_EL EL2 */
8398             mask = PL2_RW;
8399             break;
8400         case 6:
8401             /* min_EL EL3 */
8402             mask = PL3_RW;
8403             break;
8404         case 7:
8405             /* min_EL EL1, secure mode only (we don't check the latter) */
8406             mask = PL1_RW;
8407             break;
8408         default:
8409             /* broken reginfo with out-of-range opc1 */
8410             assert(false);
8411             break;
8412         }
8413         /* assert our permissions are not too lax (stricter is fine) */
8414         assert((r->access & ~mask) == 0);
8415     }
8416 
8417     /* Check that the register definition has enough info to handle
8418      * reads and writes if they are permitted.
8419      */
8420     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
8421         if (r->access & PL3_R) {
8422             assert((r->fieldoffset ||
8423                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8424                    r->readfn);
8425         }
8426         if (r->access & PL3_W) {
8427             assert((r->fieldoffset ||
8428                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8429                    r->writefn);
8430         }
8431     }
8432     /* Bad type field probably means missing sentinel at end of reg list */
8433     assert(cptype_valid(r->type));
8434     for (crm = crmmin; crm <= crmmax; crm++) {
8435         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8436             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8437                 for (state = ARM_CP_STATE_AA32;
8438                      state <= ARM_CP_STATE_AA64; state++) {
8439                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8440                         continue;
8441                     }
8442                     if (state == ARM_CP_STATE_AA32) {
8443                         /* Under AArch32 CP registers can be common
8444                          * (same for secure and non-secure world) or banked.
8445                          */
8446                         char *name;
8447 
8448                         switch (r->secure) {
8449                         case ARM_CP_SECSTATE_S:
8450                         case ARM_CP_SECSTATE_NS:
8451                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8452                                                    r->secure, crm, opc1, opc2,
8453                                                    r->name);
8454                             break;
8455                         default:
8456                             name = g_strdup_printf("%s_S", r->name);
8457                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8458                                                    ARM_CP_SECSTATE_S,
8459                                                    crm, opc1, opc2, name);
8460                             g_free(name);
8461                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8462                                                    ARM_CP_SECSTATE_NS,
8463                                                    crm, opc1, opc2, r->name);
8464                             break;
8465                         }
8466                     } else {
8467                         /* AArch64 registers get mapped to non-secure instance
8468                          * of AArch32 */
8469                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8470                                                ARM_CP_SECSTATE_NS,
8471                                                crm, opc1, opc2, r->name);
8472                     }
8473                 }
8474             }
8475         }
8476     }
8477 }
8478 
8479 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
8480                                     const ARMCPRegInfo *regs, void *opaque)
8481 {
8482     /* Define a whole list of registers */
8483     const ARMCPRegInfo *r;
8484     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8485         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
8486     }
8487 }
8488 
8489 /*
8490  * Modify ARMCPRegInfo for access from userspace.
8491  *
8492  * This is a data driven modification directed by
8493  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8494  * user-space cannot alter any values and dynamic values pertaining to
8495  * execution state are hidden from user space view anyway.
8496  */
8497 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
8498 {
8499     const ARMCPRegUserSpaceInfo *m;
8500     ARMCPRegInfo *r;
8501 
8502     for (m = mods; m->name; m++) {
8503         GPatternSpec *pat = NULL;
8504         if (m->is_glob) {
8505             pat = g_pattern_spec_new(m->name);
8506         }
8507         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8508             if (pat && g_pattern_match_string(pat, r->name)) {
8509                 r->type = ARM_CP_CONST;
8510                 r->access = PL0U_R;
8511                 r->resetvalue = 0;
8512                 /* continue */
8513             } else if (strcmp(r->name, m->name) == 0) {
8514                 r->type = ARM_CP_CONST;
8515                 r->access = PL0U_R;
8516                 r->resetvalue &= m->exported_bits;
8517                 r->resetvalue |= m->fixed_bits;
8518                 break;
8519             }
8520         }
8521         if (pat) {
8522             g_pattern_spec_free(pat);
8523         }
8524     }
8525 }
8526 
8527 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8528 {
8529     return g_hash_table_lookup(cpregs, &encoded_cp);
8530 }
8531 
8532 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8533                          uint64_t value)
8534 {
8535     /* Helper coprocessor write function for write-ignore registers */
8536 }
8537 
8538 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8539 {
8540     /* Helper coprocessor write function for read-as-zero registers */
8541     return 0;
8542 }
8543 
8544 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8545 {
8546     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8547 }
8548 
8549 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8550 {
8551     /* Return true if it is not valid for us to switch to
8552      * this CPU mode (ie all the UNPREDICTABLE cases in
8553      * the ARM ARM CPSRWriteByInstr pseudocode).
8554      */
8555 
8556     /* Changes to or from Hyp via MSR and CPS are illegal. */
8557     if (write_type == CPSRWriteByInstr &&
8558         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8559          mode == ARM_CPU_MODE_HYP)) {
8560         return 1;
8561     }
8562 
8563     switch (mode) {
8564     case ARM_CPU_MODE_USR:
8565         return 0;
8566     case ARM_CPU_MODE_SYS:
8567     case ARM_CPU_MODE_SVC:
8568     case ARM_CPU_MODE_ABT:
8569     case ARM_CPU_MODE_UND:
8570     case ARM_CPU_MODE_IRQ:
8571     case ARM_CPU_MODE_FIQ:
8572         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
8573          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
8574          */
8575         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
8576          * and CPS are treated as illegal mode changes.
8577          */
8578         if (write_type == CPSRWriteByInstr &&
8579             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
8580             (arm_hcr_el2_eff(env) & HCR_TGE)) {
8581             return 1;
8582         }
8583         return 0;
8584     case ARM_CPU_MODE_HYP:
8585         return !arm_feature(env, ARM_FEATURE_EL2)
8586             || arm_current_el(env) < 2 || arm_is_secure_below_el3(env);
8587     case ARM_CPU_MODE_MON:
8588         return arm_current_el(env) < 3;
8589     default:
8590         return 1;
8591     }
8592 }
8593 
8594 uint32_t cpsr_read(CPUARMState *env)
8595 {
8596     int ZF;
8597     ZF = (env->ZF == 0);
8598     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
8599         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
8600         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
8601         | ((env->condexec_bits & 0xfc) << 8)
8602         | (env->GE << 16) | (env->daif & CPSR_AIF);
8603 }
8604 
8605 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
8606                 CPSRWriteType write_type)
8607 {
8608     uint32_t changed_daif;
8609 
8610     if (mask & CPSR_NZCV) {
8611         env->ZF = (~val) & CPSR_Z;
8612         env->NF = val;
8613         env->CF = (val >> 29) & 1;
8614         env->VF = (val << 3) & 0x80000000;
8615     }
8616     if (mask & CPSR_Q)
8617         env->QF = ((val & CPSR_Q) != 0);
8618     if (mask & CPSR_T)
8619         env->thumb = ((val & CPSR_T) != 0);
8620     if (mask & CPSR_IT_0_1) {
8621         env->condexec_bits &= ~3;
8622         env->condexec_bits |= (val >> 25) & 3;
8623     }
8624     if (mask & CPSR_IT_2_7) {
8625         env->condexec_bits &= 3;
8626         env->condexec_bits |= (val >> 8) & 0xfc;
8627     }
8628     if (mask & CPSR_GE) {
8629         env->GE = (val >> 16) & 0xf;
8630     }
8631 
8632     /* In a V7 implementation that includes the security extensions but does
8633      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
8634      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
8635      * bits respectively.
8636      *
8637      * In a V8 implementation, it is permitted for privileged software to
8638      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
8639      */
8640     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
8641         arm_feature(env, ARM_FEATURE_EL3) &&
8642         !arm_feature(env, ARM_FEATURE_EL2) &&
8643         !arm_is_secure(env)) {
8644 
8645         changed_daif = (env->daif ^ val) & mask;
8646 
8647         if (changed_daif & CPSR_A) {
8648             /* Check to see if we are allowed to change the masking of async
8649              * abort exceptions from a non-secure state.
8650              */
8651             if (!(env->cp15.scr_el3 & SCR_AW)) {
8652                 qemu_log_mask(LOG_GUEST_ERROR,
8653                               "Ignoring attempt to switch CPSR_A flag from "
8654                               "non-secure world with SCR.AW bit clear\n");
8655                 mask &= ~CPSR_A;
8656             }
8657         }
8658 
8659         if (changed_daif & CPSR_F) {
8660             /* Check to see if we are allowed to change the masking of FIQ
8661              * exceptions from a non-secure state.
8662              */
8663             if (!(env->cp15.scr_el3 & SCR_FW)) {
8664                 qemu_log_mask(LOG_GUEST_ERROR,
8665                               "Ignoring attempt to switch CPSR_F flag from "
8666                               "non-secure world with SCR.FW bit clear\n");
8667                 mask &= ~CPSR_F;
8668             }
8669 
8670             /* Check whether non-maskable FIQ (NMFI) support is enabled.
8671              * If this bit is set software is not allowed to mask
8672              * FIQs, but is allowed to set CPSR_F to 0.
8673              */
8674             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
8675                 (val & CPSR_F)) {
8676                 qemu_log_mask(LOG_GUEST_ERROR,
8677                               "Ignoring attempt to enable CPSR_F flag "
8678                               "(non-maskable FIQ [NMFI] support enabled)\n");
8679                 mask &= ~CPSR_F;
8680             }
8681         }
8682     }
8683 
8684     env->daif &= ~(CPSR_AIF & mask);
8685     env->daif |= val & CPSR_AIF & mask;
8686 
8687     if (write_type != CPSRWriteRaw &&
8688         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
8689         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
8690             /* Note that we can only get here in USR mode if this is a
8691              * gdb stub write; for this case we follow the architectural
8692              * behaviour for guest writes in USR mode of ignoring an attempt
8693              * to switch mode. (Those are caught by translate.c for writes
8694              * triggered by guest instructions.)
8695              */
8696             mask &= ~CPSR_M;
8697         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
8698             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
8699              * v7, and has defined behaviour in v8:
8700              *  + leave CPSR.M untouched
8701              *  + allow changes to the other CPSR fields
8702              *  + set PSTATE.IL
8703              * For user changes via the GDB stub, we don't set PSTATE.IL,
8704              * as this would be unnecessarily harsh for a user error.
8705              */
8706             mask &= ~CPSR_M;
8707             if (write_type != CPSRWriteByGDBStub &&
8708                 arm_feature(env, ARM_FEATURE_V8)) {
8709                 mask |= CPSR_IL;
8710                 val |= CPSR_IL;
8711             }
8712             qemu_log_mask(LOG_GUEST_ERROR,
8713                           "Illegal AArch32 mode switch attempt from %s to %s\n",
8714                           aarch32_mode_name(env->uncached_cpsr),
8715                           aarch32_mode_name(val));
8716         } else {
8717             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
8718                           write_type == CPSRWriteExceptionReturn ?
8719                           "Exception return from AArch32" :
8720                           "AArch32 mode switch from",
8721                           aarch32_mode_name(env->uncached_cpsr),
8722                           aarch32_mode_name(val), env->regs[15]);
8723             switch_mode(env, val & CPSR_M);
8724         }
8725     }
8726     mask &= ~CACHED_CPSR_BITS;
8727     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
8728 }
8729 
8730 /* Sign/zero extend */
8731 uint32_t HELPER(sxtb16)(uint32_t x)
8732 {
8733     uint32_t res;
8734     res = (uint16_t)(int8_t)x;
8735     res |= (uint32_t)(int8_t)(x >> 16) << 16;
8736     return res;
8737 }
8738 
8739 uint32_t HELPER(uxtb16)(uint32_t x)
8740 {
8741     uint32_t res;
8742     res = (uint16_t)(uint8_t)x;
8743     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
8744     return res;
8745 }
8746 
8747 int32_t HELPER(sdiv)(int32_t num, int32_t den)
8748 {
8749     if (den == 0)
8750       return 0;
8751     if (num == INT_MIN && den == -1)
8752       return INT_MIN;
8753     return num / den;
8754 }
8755 
8756 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
8757 {
8758     if (den == 0)
8759       return 0;
8760     return num / den;
8761 }
8762 
8763 uint32_t HELPER(rbit)(uint32_t x)
8764 {
8765     return revbit32(x);
8766 }
8767 
8768 #ifdef CONFIG_USER_ONLY
8769 
8770 static void switch_mode(CPUARMState *env, int mode)
8771 {
8772     ARMCPU *cpu = env_archcpu(env);
8773 
8774     if (mode != ARM_CPU_MODE_USR) {
8775         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
8776     }
8777 }
8778 
8779 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
8780                                  uint32_t cur_el, bool secure)
8781 {
8782     return 1;
8783 }
8784 
8785 void aarch64_sync_64_to_32(CPUARMState *env)
8786 {
8787     g_assert_not_reached();
8788 }
8789 
8790 #else
8791 
8792 static void switch_mode(CPUARMState *env, int mode)
8793 {
8794     int old_mode;
8795     int i;
8796 
8797     old_mode = env->uncached_cpsr & CPSR_M;
8798     if (mode == old_mode)
8799         return;
8800 
8801     if (old_mode == ARM_CPU_MODE_FIQ) {
8802         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
8803         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
8804     } else if (mode == ARM_CPU_MODE_FIQ) {
8805         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
8806         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
8807     }
8808 
8809     i = bank_number(old_mode);
8810     env->banked_r13[i] = env->regs[13];
8811     env->banked_spsr[i] = env->spsr;
8812 
8813     i = bank_number(mode);
8814     env->regs[13] = env->banked_r13[i];
8815     env->spsr = env->banked_spsr[i];
8816 
8817     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
8818     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
8819 }
8820 
8821 /* Physical Interrupt Target EL Lookup Table
8822  *
8823  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
8824  *
8825  * The below multi-dimensional table is used for looking up the target
8826  * exception level given numerous condition criteria.  Specifically, the
8827  * target EL is based on SCR and HCR routing controls as well as the
8828  * currently executing EL and secure state.
8829  *
8830  *    Dimensions:
8831  *    target_el_table[2][2][2][2][2][4]
8832  *                    |  |  |  |  |  +--- Current EL
8833  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
8834  *                    |  |  |  +--------- HCR mask override
8835  *                    |  |  +------------ SCR exec state control
8836  *                    |  +--------------- SCR mask override
8837  *                    +------------------ 32-bit(0)/64-bit(1) EL3
8838  *
8839  *    The table values are as such:
8840  *    0-3 = EL0-EL3
8841  *     -1 = Cannot occur
8842  *
8843  * The ARM ARM target EL table includes entries indicating that an "exception
8844  * is not taken".  The two cases where this is applicable are:
8845  *    1) An exception is taken from EL3 but the SCR does not have the exception
8846  *    routed to EL3.
8847  *    2) An exception is taken from EL2 but the HCR does not have the exception
8848  *    routed to EL2.
8849  * In these two cases, the below table contain a target of EL1.  This value is
8850  * returned as it is expected that the consumer of the table data will check
8851  * for "target EL >= current EL" to ensure the exception is not taken.
8852  *
8853  *            SCR     HCR
8854  *         64  EA     AMO                 From
8855  *        BIT IRQ     IMO      Non-secure         Secure
8856  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
8857  */
8858 static const int8_t target_el_table[2][2][2][2][2][4] = {
8859     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
8860        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
8861       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
8862        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
8863      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
8864        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
8865       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
8866        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
8867     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
8868        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
8869       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
8870        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
8871      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
8872        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
8873       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
8874        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
8875 };
8876 
8877 /*
8878  * Determine the target EL for physical exceptions
8879  */
8880 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
8881                                  uint32_t cur_el, bool secure)
8882 {
8883     CPUARMState *env = cs->env_ptr;
8884     bool rw;
8885     bool scr;
8886     bool hcr;
8887     int target_el;
8888     /* Is the highest EL AArch64? */
8889     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
8890     uint64_t hcr_el2;
8891 
8892     if (arm_feature(env, ARM_FEATURE_EL3)) {
8893         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
8894     } else {
8895         /* Either EL2 is the highest EL (and so the EL2 register width
8896          * is given by is64); or there is no EL2 or EL3, in which case
8897          * the value of 'rw' does not affect the table lookup anyway.
8898          */
8899         rw = is64;
8900     }
8901 
8902     hcr_el2 = arm_hcr_el2_eff(env);
8903     switch (excp_idx) {
8904     case EXCP_IRQ:
8905         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
8906         hcr = hcr_el2 & HCR_IMO;
8907         break;
8908     case EXCP_FIQ:
8909         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
8910         hcr = hcr_el2 & HCR_FMO;
8911         break;
8912     default:
8913         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
8914         hcr = hcr_el2 & HCR_AMO;
8915         break;
8916     };
8917 
8918     /*
8919      * For these purposes, TGE and AMO/IMO/FMO both force the
8920      * interrupt to EL2.  Fold TGE into the bit extracted above.
8921      */
8922     hcr |= (hcr_el2 & HCR_TGE) != 0;
8923 
8924     /* Perform a table-lookup for the target EL given the current state */
8925     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
8926 
8927     assert(target_el > 0);
8928 
8929     return target_el;
8930 }
8931 
8932 void arm_log_exception(int idx)
8933 {
8934     if (qemu_loglevel_mask(CPU_LOG_INT)) {
8935         const char *exc = NULL;
8936         static const char * const excnames[] = {
8937             [EXCP_UDEF] = "Undefined Instruction",
8938             [EXCP_SWI] = "SVC",
8939             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
8940             [EXCP_DATA_ABORT] = "Data Abort",
8941             [EXCP_IRQ] = "IRQ",
8942             [EXCP_FIQ] = "FIQ",
8943             [EXCP_BKPT] = "Breakpoint",
8944             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
8945             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
8946             [EXCP_HVC] = "Hypervisor Call",
8947             [EXCP_HYP_TRAP] = "Hypervisor Trap",
8948             [EXCP_SMC] = "Secure Monitor Call",
8949             [EXCP_VIRQ] = "Virtual IRQ",
8950             [EXCP_VFIQ] = "Virtual FIQ",
8951             [EXCP_SEMIHOST] = "Semihosting call",
8952             [EXCP_NOCP] = "v7M NOCP UsageFault",
8953             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
8954             [EXCP_STKOF] = "v8M STKOF UsageFault",
8955             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
8956             [EXCP_LSERR] = "v8M LSERR UsageFault",
8957             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
8958         };
8959 
8960         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
8961             exc = excnames[idx];
8962         }
8963         if (!exc) {
8964             exc = "unknown";
8965         }
8966         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
8967     }
8968 }
8969 
8970 /*
8971  * Function used to synchronize QEMU's AArch64 register set with AArch32
8972  * register set.  This is necessary when switching between AArch32 and AArch64
8973  * execution state.
8974  */
8975 void aarch64_sync_32_to_64(CPUARMState *env)
8976 {
8977     int i;
8978     uint32_t mode = env->uncached_cpsr & CPSR_M;
8979 
8980     /* We can blanket copy R[0:7] to X[0:7] */
8981     for (i = 0; i < 8; i++) {
8982         env->xregs[i] = env->regs[i];
8983     }
8984 
8985     /*
8986      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
8987      * Otherwise, they come from the banked user regs.
8988      */
8989     if (mode == ARM_CPU_MODE_FIQ) {
8990         for (i = 8; i < 13; i++) {
8991             env->xregs[i] = env->usr_regs[i - 8];
8992         }
8993     } else {
8994         for (i = 8; i < 13; i++) {
8995             env->xregs[i] = env->regs[i];
8996         }
8997     }
8998 
8999     /*
9000      * Registers x13-x23 are the various mode SP and FP registers. Registers
9001      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9002      * from the mode banked register.
9003      */
9004     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9005         env->xregs[13] = env->regs[13];
9006         env->xregs[14] = env->regs[14];
9007     } else {
9008         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9009         /* HYP is an exception in that it is copied from r14 */
9010         if (mode == ARM_CPU_MODE_HYP) {
9011             env->xregs[14] = env->regs[14];
9012         } else {
9013             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9014         }
9015     }
9016 
9017     if (mode == ARM_CPU_MODE_HYP) {
9018         env->xregs[15] = env->regs[13];
9019     } else {
9020         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9021     }
9022 
9023     if (mode == ARM_CPU_MODE_IRQ) {
9024         env->xregs[16] = env->regs[14];
9025         env->xregs[17] = env->regs[13];
9026     } else {
9027         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9028         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9029     }
9030 
9031     if (mode == ARM_CPU_MODE_SVC) {
9032         env->xregs[18] = env->regs[14];
9033         env->xregs[19] = env->regs[13];
9034     } else {
9035         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9036         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9037     }
9038 
9039     if (mode == ARM_CPU_MODE_ABT) {
9040         env->xregs[20] = env->regs[14];
9041         env->xregs[21] = env->regs[13];
9042     } else {
9043         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9044         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9045     }
9046 
9047     if (mode == ARM_CPU_MODE_UND) {
9048         env->xregs[22] = env->regs[14];
9049         env->xregs[23] = env->regs[13];
9050     } else {
9051         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9052         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9053     }
9054 
9055     /*
9056      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9057      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9058      * FIQ bank for r8-r14.
9059      */
9060     if (mode == ARM_CPU_MODE_FIQ) {
9061         for (i = 24; i < 31; i++) {
9062             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9063         }
9064     } else {
9065         for (i = 24; i < 29; i++) {
9066             env->xregs[i] = env->fiq_regs[i - 24];
9067         }
9068         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9069         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9070     }
9071 
9072     env->pc = env->regs[15];
9073 }
9074 
9075 /*
9076  * Function used to synchronize QEMU's AArch32 register set with AArch64
9077  * register set.  This is necessary when switching between AArch32 and AArch64
9078  * execution state.
9079  */
9080 void aarch64_sync_64_to_32(CPUARMState *env)
9081 {
9082     int i;
9083     uint32_t mode = env->uncached_cpsr & CPSR_M;
9084 
9085     /* We can blanket copy X[0:7] to R[0:7] */
9086     for (i = 0; i < 8; i++) {
9087         env->regs[i] = env->xregs[i];
9088     }
9089 
9090     /*
9091      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9092      * Otherwise, we copy x8-x12 into the banked user regs.
9093      */
9094     if (mode == ARM_CPU_MODE_FIQ) {
9095         for (i = 8; i < 13; i++) {
9096             env->usr_regs[i - 8] = env->xregs[i];
9097         }
9098     } else {
9099         for (i = 8; i < 13; i++) {
9100             env->regs[i] = env->xregs[i];
9101         }
9102     }
9103 
9104     /*
9105      * Registers r13 & r14 depend on the current mode.
9106      * If we are in a given mode, we copy the corresponding x registers to r13
9107      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9108      * for the mode.
9109      */
9110     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9111         env->regs[13] = env->xregs[13];
9112         env->regs[14] = env->xregs[14];
9113     } else {
9114         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9115 
9116         /*
9117          * HYP is an exception in that it does not have its own banked r14 but
9118          * shares the USR r14
9119          */
9120         if (mode == ARM_CPU_MODE_HYP) {
9121             env->regs[14] = env->xregs[14];
9122         } else {
9123             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9124         }
9125     }
9126 
9127     if (mode == ARM_CPU_MODE_HYP) {
9128         env->regs[13] = env->xregs[15];
9129     } else {
9130         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9131     }
9132 
9133     if (mode == ARM_CPU_MODE_IRQ) {
9134         env->regs[14] = env->xregs[16];
9135         env->regs[13] = env->xregs[17];
9136     } else {
9137         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9138         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9139     }
9140 
9141     if (mode == ARM_CPU_MODE_SVC) {
9142         env->regs[14] = env->xregs[18];
9143         env->regs[13] = env->xregs[19];
9144     } else {
9145         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9146         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9147     }
9148 
9149     if (mode == ARM_CPU_MODE_ABT) {
9150         env->regs[14] = env->xregs[20];
9151         env->regs[13] = env->xregs[21];
9152     } else {
9153         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9154         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9155     }
9156 
9157     if (mode == ARM_CPU_MODE_UND) {
9158         env->regs[14] = env->xregs[22];
9159         env->regs[13] = env->xregs[23];
9160     } else {
9161         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9162         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9163     }
9164 
9165     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9166      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9167      * FIQ bank for r8-r14.
9168      */
9169     if (mode == ARM_CPU_MODE_FIQ) {
9170         for (i = 24; i < 31; i++) {
9171             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9172         }
9173     } else {
9174         for (i = 24; i < 29; i++) {
9175             env->fiq_regs[i - 24] = env->xregs[i];
9176         }
9177         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9178         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9179     }
9180 
9181     env->regs[15] = env->pc;
9182 }
9183 
9184 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9185                                    uint32_t mask, uint32_t offset,
9186                                    uint32_t newpc)
9187 {
9188     int new_el;
9189 
9190     /* Change the CPU state so as to actually take the exception. */
9191     switch_mode(env, new_mode);
9192 
9193     /*
9194      * For exceptions taken to AArch32 we must clear the SS bit in both
9195      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9196      */
9197     env->uncached_cpsr &= ~PSTATE_SS;
9198     env->spsr = cpsr_read(env);
9199     /* Clear IT bits.  */
9200     env->condexec_bits = 0;
9201     /* Switch to the new mode, and to the correct instruction set.  */
9202     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9203 
9204     /* This must be after mode switching. */
9205     new_el = arm_current_el(env);
9206 
9207     /* Set new mode endianness */
9208     env->uncached_cpsr &= ~CPSR_E;
9209     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9210         env->uncached_cpsr |= CPSR_E;
9211     }
9212     /* J and IL must always be cleared for exception entry */
9213     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9214     env->daif |= mask;
9215 
9216     if (new_mode == ARM_CPU_MODE_HYP) {
9217         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9218         env->elr_el[2] = env->regs[15];
9219     } else {
9220         /* CPSR.PAN is normally preserved preserved unless...  */
9221         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9222             switch (new_el) {
9223             case 3:
9224                 if (!arm_is_secure_below_el3(env)) {
9225                     /* ... the target is EL3, from non-secure state.  */
9226                     env->uncached_cpsr &= ~CPSR_PAN;
9227                     break;
9228                 }
9229                 /* ... the target is EL3, from secure state ... */
9230                 /* fall through */
9231             case 1:
9232                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9233                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9234                     env->uncached_cpsr |= CPSR_PAN;
9235                 }
9236                 break;
9237             }
9238         }
9239         /*
9240          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9241          * and we should just guard the thumb mode on V4
9242          */
9243         if (arm_feature(env, ARM_FEATURE_V4T)) {
9244             env->thumb =
9245                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9246         }
9247         env->regs[14] = env->regs[15] + offset;
9248     }
9249     env->regs[15] = newpc;
9250     arm_rebuild_hflags(env);
9251 }
9252 
9253 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9254 {
9255     /*
9256      * Handle exception entry to Hyp mode; this is sufficiently
9257      * different to entry to other AArch32 modes that we handle it
9258      * separately here.
9259      *
9260      * The vector table entry used is always the 0x14 Hyp mode entry point,
9261      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
9262      * The offset applied to the preferred return address is always zero
9263      * (see DDI0487C.a section G1.12.3).
9264      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9265      */
9266     uint32_t addr, mask;
9267     ARMCPU *cpu = ARM_CPU(cs);
9268     CPUARMState *env = &cpu->env;
9269 
9270     switch (cs->exception_index) {
9271     case EXCP_UDEF:
9272         addr = 0x04;
9273         break;
9274     case EXCP_SWI:
9275         addr = 0x14;
9276         break;
9277     case EXCP_BKPT:
9278         /* Fall through to prefetch abort.  */
9279     case EXCP_PREFETCH_ABORT:
9280         env->cp15.ifar_s = env->exception.vaddress;
9281         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9282                       (uint32_t)env->exception.vaddress);
9283         addr = 0x0c;
9284         break;
9285     case EXCP_DATA_ABORT:
9286         env->cp15.dfar_s = env->exception.vaddress;
9287         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9288                       (uint32_t)env->exception.vaddress);
9289         addr = 0x10;
9290         break;
9291     case EXCP_IRQ:
9292         addr = 0x18;
9293         break;
9294     case EXCP_FIQ:
9295         addr = 0x1c;
9296         break;
9297     case EXCP_HVC:
9298         addr = 0x08;
9299         break;
9300     case EXCP_HYP_TRAP:
9301         addr = 0x14;
9302         break;
9303     default:
9304         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9305     }
9306 
9307     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9308         if (!arm_feature(env, ARM_FEATURE_V8)) {
9309             /*
9310              * QEMU syndrome values are v8-style. v7 has the IL bit
9311              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9312              * If this is a v7 CPU, squash the IL bit in those cases.
9313              */
9314             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9315                 (cs->exception_index == EXCP_DATA_ABORT &&
9316                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9317                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9318                 env->exception.syndrome &= ~ARM_EL_IL;
9319             }
9320         }
9321         env->cp15.esr_el[2] = env->exception.syndrome;
9322     }
9323 
9324     if (arm_current_el(env) != 2 && addr < 0x14) {
9325         addr = 0x14;
9326     }
9327 
9328     mask = 0;
9329     if (!(env->cp15.scr_el3 & SCR_EA)) {
9330         mask |= CPSR_A;
9331     }
9332     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9333         mask |= CPSR_I;
9334     }
9335     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9336         mask |= CPSR_F;
9337     }
9338 
9339     addr += env->cp15.hvbar;
9340 
9341     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9342 }
9343 
9344 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9345 {
9346     ARMCPU *cpu = ARM_CPU(cs);
9347     CPUARMState *env = &cpu->env;
9348     uint32_t addr;
9349     uint32_t mask;
9350     int new_mode;
9351     uint32_t offset;
9352     uint32_t moe;
9353 
9354     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9355     switch (syn_get_ec(env->exception.syndrome)) {
9356     case EC_BREAKPOINT:
9357     case EC_BREAKPOINT_SAME_EL:
9358         moe = 1;
9359         break;
9360     case EC_WATCHPOINT:
9361     case EC_WATCHPOINT_SAME_EL:
9362         moe = 10;
9363         break;
9364     case EC_AA32_BKPT:
9365         moe = 3;
9366         break;
9367     case EC_VECTORCATCH:
9368         moe = 5;
9369         break;
9370     default:
9371         moe = 0;
9372         break;
9373     }
9374 
9375     if (moe) {
9376         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9377     }
9378 
9379     if (env->exception.target_el == 2) {
9380         arm_cpu_do_interrupt_aarch32_hyp(cs);
9381         return;
9382     }
9383 
9384     switch (cs->exception_index) {
9385     case EXCP_UDEF:
9386         new_mode = ARM_CPU_MODE_UND;
9387         addr = 0x04;
9388         mask = CPSR_I;
9389         if (env->thumb)
9390             offset = 2;
9391         else
9392             offset = 4;
9393         break;
9394     case EXCP_SWI:
9395         new_mode = ARM_CPU_MODE_SVC;
9396         addr = 0x08;
9397         mask = CPSR_I;
9398         /* The PC already points to the next instruction.  */
9399         offset = 0;
9400         break;
9401     case EXCP_BKPT:
9402         /* Fall through to prefetch abort.  */
9403     case EXCP_PREFETCH_ABORT:
9404         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9405         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9406         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9407                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9408         new_mode = ARM_CPU_MODE_ABT;
9409         addr = 0x0c;
9410         mask = CPSR_A | CPSR_I;
9411         offset = 4;
9412         break;
9413     case EXCP_DATA_ABORT:
9414         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9415         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9416         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9417                       env->exception.fsr,
9418                       (uint32_t)env->exception.vaddress);
9419         new_mode = ARM_CPU_MODE_ABT;
9420         addr = 0x10;
9421         mask = CPSR_A | CPSR_I;
9422         offset = 8;
9423         break;
9424     case EXCP_IRQ:
9425         new_mode = ARM_CPU_MODE_IRQ;
9426         addr = 0x18;
9427         /* Disable IRQ and imprecise data aborts.  */
9428         mask = CPSR_A | CPSR_I;
9429         offset = 4;
9430         if (env->cp15.scr_el3 & SCR_IRQ) {
9431             /* IRQ routed to monitor mode */
9432             new_mode = ARM_CPU_MODE_MON;
9433             mask |= CPSR_F;
9434         }
9435         break;
9436     case EXCP_FIQ:
9437         new_mode = ARM_CPU_MODE_FIQ;
9438         addr = 0x1c;
9439         /* Disable FIQ, IRQ and imprecise data aborts.  */
9440         mask = CPSR_A | CPSR_I | CPSR_F;
9441         if (env->cp15.scr_el3 & SCR_FIQ) {
9442             /* FIQ routed to monitor mode */
9443             new_mode = ARM_CPU_MODE_MON;
9444         }
9445         offset = 4;
9446         break;
9447     case EXCP_VIRQ:
9448         new_mode = ARM_CPU_MODE_IRQ;
9449         addr = 0x18;
9450         /* Disable IRQ and imprecise data aborts.  */
9451         mask = CPSR_A | CPSR_I;
9452         offset = 4;
9453         break;
9454     case EXCP_VFIQ:
9455         new_mode = ARM_CPU_MODE_FIQ;
9456         addr = 0x1c;
9457         /* Disable FIQ, IRQ and imprecise data aborts.  */
9458         mask = CPSR_A | CPSR_I | CPSR_F;
9459         offset = 4;
9460         break;
9461     case EXCP_SMC:
9462         new_mode = ARM_CPU_MODE_MON;
9463         addr = 0x08;
9464         mask = CPSR_A | CPSR_I | CPSR_F;
9465         offset = 0;
9466         break;
9467     default:
9468         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9469         return; /* Never happens.  Keep compiler happy.  */
9470     }
9471 
9472     if (new_mode == ARM_CPU_MODE_MON) {
9473         addr += env->cp15.mvbar;
9474     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9475         /* High vectors. When enabled, base address cannot be remapped. */
9476         addr += 0xffff0000;
9477     } else {
9478         /* ARM v7 architectures provide a vector base address register to remap
9479          * the interrupt vector table.
9480          * This register is only followed in non-monitor mode, and is banked.
9481          * Note: only bits 31:5 are valid.
9482          */
9483         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9484     }
9485 
9486     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9487         env->cp15.scr_el3 &= ~SCR_NS;
9488     }
9489 
9490     take_aarch32_exception(env, new_mode, mask, offset, addr);
9491 }
9492 
9493 /* Handle exception entry to a target EL which is using AArch64 */
9494 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
9495 {
9496     ARMCPU *cpu = ARM_CPU(cs);
9497     CPUARMState *env = &cpu->env;
9498     unsigned int new_el = env->exception.target_el;
9499     target_ulong addr = env->cp15.vbar_el[new_el];
9500     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
9501     unsigned int old_mode;
9502     unsigned int cur_el = arm_current_el(env);
9503 
9504     /*
9505      * Note that new_el can never be 0.  If cur_el is 0, then
9506      * el0_a64 is is_a64(), else el0_a64 is ignored.
9507      */
9508     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
9509 
9510     if (cur_el < new_el) {
9511         /* Entry vector offset depends on whether the implemented EL
9512          * immediately lower than the target level is using AArch32 or AArch64
9513          */
9514         bool is_aa64;
9515         uint64_t hcr;
9516 
9517         switch (new_el) {
9518         case 3:
9519             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
9520             break;
9521         case 2:
9522             hcr = arm_hcr_el2_eff(env);
9523             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
9524                 is_aa64 = (hcr & HCR_RW) != 0;
9525                 break;
9526             }
9527             /* fall through */
9528         case 1:
9529             is_aa64 = is_a64(env);
9530             break;
9531         default:
9532             g_assert_not_reached();
9533         }
9534 
9535         if (is_aa64) {
9536             addr += 0x400;
9537         } else {
9538             addr += 0x600;
9539         }
9540     } else if (pstate_read(env) & PSTATE_SP) {
9541         addr += 0x200;
9542     }
9543 
9544     switch (cs->exception_index) {
9545     case EXCP_PREFETCH_ABORT:
9546     case EXCP_DATA_ABORT:
9547         env->cp15.far_el[new_el] = env->exception.vaddress;
9548         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
9549                       env->cp15.far_el[new_el]);
9550         /* fall through */
9551     case EXCP_BKPT:
9552     case EXCP_UDEF:
9553     case EXCP_SWI:
9554     case EXCP_HVC:
9555     case EXCP_HYP_TRAP:
9556     case EXCP_SMC:
9557         if (syn_get_ec(env->exception.syndrome) == EC_ADVSIMDFPACCESSTRAP) {
9558             /*
9559              * QEMU internal FP/SIMD syndromes from AArch32 include the
9560              * TA and coproc fields which are only exposed if the exception
9561              * is taken to AArch32 Hyp mode. Mask them out to get a valid
9562              * AArch64 format syndrome.
9563              */
9564             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
9565         }
9566         env->cp15.esr_el[new_el] = env->exception.syndrome;
9567         break;
9568     case EXCP_IRQ:
9569     case EXCP_VIRQ:
9570         addr += 0x80;
9571         break;
9572     case EXCP_FIQ:
9573     case EXCP_VFIQ:
9574         addr += 0x100;
9575         break;
9576     default:
9577         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9578     }
9579 
9580     if (is_a64(env)) {
9581         old_mode = pstate_read(env);
9582         aarch64_save_sp(env, arm_current_el(env));
9583         env->elr_el[new_el] = env->pc;
9584     } else {
9585         old_mode = cpsr_read(env);
9586         env->elr_el[new_el] = env->regs[15];
9587 
9588         aarch64_sync_32_to_64(env);
9589 
9590         env->condexec_bits = 0;
9591     }
9592     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
9593 
9594     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
9595                   env->elr_el[new_el]);
9596 
9597     if (cpu_isar_feature(aa64_pan, cpu)) {
9598         /* The value of PSTATE.PAN is normally preserved, except when ... */
9599         new_mode |= old_mode & PSTATE_PAN;
9600         switch (new_el) {
9601         case 2:
9602             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
9603             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
9604                 != (HCR_E2H | HCR_TGE)) {
9605                 break;
9606             }
9607             /* fall through */
9608         case 1:
9609             /* ... the target is EL1 ... */
9610             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
9611             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
9612                 new_mode |= PSTATE_PAN;
9613             }
9614             break;
9615         }
9616     }
9617 
9618     pstate_write(env, PSTATE_DAIF | new_mode);
9619     env->aarch64 = 1;
9620     aarch64_restore_sp(env, new_el);
9621     helper_rebuild_hflags_a64(env, new_el);
9622 
9623     env->pc = addr;
9624 
9625     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
9626                   new_el, env->pc, pstate_read(env));
9627 }
9628 
9629 /*
9630  * Do semihosting call and set the appropriate return value. All the
9631  * permission and validity checks have been done at translate time.
9632  *
9633  * We only see semihosting exceptions in TCG only as they are not
9634  * trapped to the hypervisor in KVM.
9635  */
9636 #ifdef CONFIG_TCG
9637 static void handle_semihosting(CPUState *cs)
9638 {
9639     ARMCPU *cpu = ARM_CPU(cs);
9640     CPUARMState *env = &cpu->env;
9641 
9642     if (is_a64(env)) {
9643         qemu_log_mask(CPU_LOG_INT,
9644                       "...handling as semihosting call 0x%" PRIx64 "\n",
9645                       env->xregs[0]);
9646         env->xregs[0] = do_arm_semihosting(env);
9647         env->pc += 4;
9648     } else {
9649         qemu_log_mask(CPU_LOG_INT,
9650                       "...handling as semihosting call 0x%x\n",
9651                       env->regs[0]);
9652         env->regs[0] = do_arm_semihosting(env);
9653         env->regs[15] += env->thumb ? 2 : 4;
9654     }
9655 }
9656 #endif
9657 
9658 /* Handle a CPU exception for A and R profile CPUs.
9659  * Do any appropriate logging, handle PSCI calls, and then hand off
9660  * to the AArch64-entry or AArch32-entry function depending on the
9661  * target exception level's register width.
9662  */
9663 void arm_cpu_do_interrupt(CPUState *cs)
9664 {
9665     ARMCPU *cpu = ARM_CPU(cs);
9666     CPUARMState *env = &cpu->env;
9667     unsigned int new_el = env->exception.target_el;
9668 
9669     assert(!arm_feature(env, ARM_FEATURE_M));
9670 
9671     arm_log_exception(cs->exception_index);
9672     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
9673                   new_el);
9674     if (qemu_loglevel_mask(CPU_LOG_INT)
9675         && !excp_is_internal(cs->exception_index)) {
9676         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
9677                       syn_get_ec(env->exception.syndrome),
9678                       env->exception.syndrome);
9679     }
9680 
9681     if (arm_is_psci_call(cpu, cs->exception_index)) {
9682         arm_handle_psci_call(cpu);
9683         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
9684         return;
9685     }
9686 
9687     /*
9688      * Semihosting semantics depend on the register width of the code
9689      * that caused the exception, not the target exception level, so
9690      * must be handled here.
9691      */
9692 #ifdef CONFIG_TCG
9693     if (cs->exception_index == EXCP_SEMIHOST) {
9694         handle_semihosting(cs);
9695         return;
9696     }
9697 #endif
9698 
9699     /* Hooks may change global state so BQL should be held, also the
9700      * BQL needs to be held for any modification of
9701      * cs->interrupt_request.
9702      */
9703     g_assert(qemu_mutex_iothread_locked());
9704 
9705     arm_call_pre_el_change_hook(cpu);
9706 
9707     assert(!excp_is_internal(cs->exception_index));
9708     if (arm_el_is_aa64(env, new_el)) {
9709         arm_cpu_do_interrupt_aarch64(cs);
9710     } else {
9711         arm_cpu_do_interrupt_aarch32(cs);
9712     }
9713 
9714     arm_call_el_change_hook(cpu);
9715 
9716     if (!kvm_enabled()) {
9717         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
9718     }
9719 }
9720 #endif /* !CONFIG_USER_ONLY */
9721 
9722 /* Return the exception level which controls this address translation regime */
9723 static uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
9724 {
9725     switch (mmu_idx) {
9726     case ARMMMUIdx_E20_0:
9727     case ARMMMUIdx_E20_2:
9728     case ARMMMUIdx_E20_2_PAN:
9729     case ARMMMUIdx_Stage2:
9730     case ARMMMUIdx_E2:
9731         return 2;
9732     case ARMMMUIdx_SE3:
9733         return 3;
9734     case ARMMMUIdx_SE10_0:
9735         return arm_el_is_aa64(env, 3) ? 1 : 3;
9736     case ARMMMUIdx_SE10_1:
9737     case ARMMMUIdx_SE10_1_PAN:
9738     case ARMMMUIdx_Stage1_E0:
9739     case ARMMMUIdx_Stage1_E1:
9740     case ARMMMUIdx_Stage1_E1_PAN:
9741     case ARMMMUIdx_E10_0:
9742     case ARMMMUIdx_E10_1:
9743     case ARMMMUIdx_E10_1_PAN:
9744     case ARMMMUIdx_MPrivNegPri:
9745     case ARMMMUIdx_MUserNegPri:
9746     case ARMMMUIdx_MPriv:
9747     case ARMMMUIdx_MUser:
9748     case ARMMMUIdx_MSPrivNegPri:
9749     case ARMMMUIdx_MSUserNegPri:
9750     case ARMMMUIdx_MSPriv:
9751     case ARMMMUIdx_MSUser:
9752         return 1;
9753     default:
9754         g_assert_not_reached();
9755     }
9756 }
9757 
9758 uint64_t arm_sctlr(CPUARMState *env, int el)
9759 {
9760     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
9761     if (el == 0) {
9762         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
9763         el = (mmu_idx == ARMMMUIdx_E20_0 ? 2 : 1);
9764     }
9765     return env->cp15.sctlr_el[el];
9766 }
9767 
9768 /* Return the SCTLR value which controls this address translation regime */
9769 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
9770 {
9771     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
9772 }
9773 
9774 #ifndef CONFIG_USER_ONLY
9775 
9776 /* Return true if the specified stage of address translation is disabled */
9777 static inline bool regime_translation_disabled(CPUARMState *env,
9778                                                ARMMMUIdx mmu_idx)
9779 {
9780     if (arm_feature(env, ARM_FEATURE_M)) {
9781         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
9782                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
9783         case R_V7M_MPU_CTRL_ENABLE_MASK:
9784             /* Enabled, but not for HardFault and NMI */
9785             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
9786         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
9787             /* Enabled for all cases */
9788             return false;
9789         case 0:
9790         default:
9791             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
9792              * we warned about that in armv7m_nvic.c when the guest set it.
9793              */
9794             return true;
9795         }
9796     }
9797 
9798     if (mmu_idx == ARMMMUIdx_Stage2) {
9799         /* HCR.DC means HCR.VM behaves as 1 */
9800         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
9801     }
9802 
9803     if (env->cp15.hcr_el2 & HCR_TGE) {
9804         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
9805         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
9806             return true;
9807         }
9808     }
9809 
9810     if ((env->cp15.hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
9811         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
9812         return true;
9813     }
9814 
9815     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
9816 }
9817 
9818 static inline bool regime_translation_big_endian(CPUARMState *env,
9819                                                  ARMMMUIdx mmu_idx)
9820 {
9821     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
9822 }
9823 
9824 /* Return the TTBR associated with this translation regime */
9825 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
9826                                    int ttbrn)
9827 {
9828     if (mmu_idx == ARMMMUIdx_Stage2) {
9829         return env->cp15.vttbr_el2;
9830     }
9831     if (ttbrn == 0) {
9832         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
9833     } else {
9834         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
9835     }
9836 }
9837 
9838 #endif /* !CONFIG_USER_ONLY */
9839 
9840 /* Return the TCR controlling this translation regime */
9841 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
9842 {
9843     if (mmu_idx == ARMMMUIdx_Stage2) {
9844         return &env->cp15.vtcr_el2;
9845     }
9846     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
9847 }
9848 
9849 /* Convert a possible stage1+2 MMU index into the appropriate
9850  * stage 1 MMU index
9851  */
9852 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
9853 {
9854     switch (mmu_idx) {
9855     case ARMMMUIdx_E10_0:
9856         return ARMMMUIdx_Stage1_E0;
9857     case ARMMMUIdx_E10_1:
9858         return ARMMMUIdx_Stage1_E1;
9859     case ARMMMUIdx_E10_1_PAN:
9860         return ARMMMUIdx_Stage1_E1_PAN;
9861     default:
9862         return mmu_idx;
9863     }
9864 }
9865 
9866 /* Return true if the translation regime is using LPAE format page tables */
9867 static inline bool regime_using_lpae_format(CPUARMState *env,
9868                                             ARMMMUIdx mmu_idx)
9869 {
9870     int el = regime_el(env, mmu_idx);
9871     if (el == 2 || arm_el_is_aa64(env, el)) {
9872         return true;
9873     }
9874     if (arm_feature(env, ARM_FEATURE_LPAE)
9875         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
9876         return true;
9877     }
9878     return false;
9879 }
9880 
9881 /* Returns true if the stage 1 translation regime is using LPAE format page
9882  * tables. Used when raising alignment exceptions, whose FSR changes depending
9883  * on whether the long or short descriptor format is in use. */
9884 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
9885 {
9886     mmu_idx = stage_1_mmu_idx(mmu_idx);
9887 
9888     return regime_using_lpae_format(env, mmu_idx);
9889 }
9890 
9891 #ifndef CONFIG_USER_ONLY
9892 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
9893 {
9894     switch (mmu_idx) {
9895     case ARMMMUIdx_SE10_0:
9896     case ARMMMUIdx_E20_0:
9897     case ARMMMUIdx_Stage1_E0:
9898     case ARMMMUIdx_MUser:
9899     case ARMMMUIdx_MSUser:
9900     case ARMMMUIdx_MUserNegPri:
9901     case ARMMMUIdx_MSUserNegPri:
9902         return true;
9903     default:
9904         return false;
9905     case ARMMMUIdx_E10_0:
9906     case ARMMMUIdx_E10_1:
9907     case ARMMMUIdx_E10_1_PAN:
9908         g_assert_not_reached();
9909     }
9910 }
9911 
9912 /* Translate section/page access permissions to page
9913  * R/W protection flags
9914  *
9915  * @env:         CPUARMState
9916  * @mmu_idx:     MMU index indicating required translation regime
9917  * @ap:          The 3-bit access permissions (AP[2:0])
9918  * @domain_prot: The 2-bit domain access permissions
9919  */
9920 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
9921                                 int ap, int domain_prot)
9922 {
9923     bool is_user = regime_is_user(env, mmu_idx);
9924 
9925     if (domain_prot == 3) {
9926         return PAGE_READ | PAGE_WRITE;
9927     }
9928 
9929     switch (ap) {
9930     case 0:
9931         if (arm_feature(env, ARM_FEATURE_V7)) {
9932             return 0;
9933         }
9934         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
9935         case SCTLR_S:
9936             return is_user ? 0 : PAGE_READ;
9937         case SCTLR_R:
9938             return PAGE_READ;
9939         default:
9940             return 0;
9941         }
9942     case 1:
9943         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
9944     case 2:
9945         if (is_user) {
9946             return PAGE_READ;
9947         } else {
9948             return PAGE_READ | PAGE_WRITE;
9949         }
9950     case 3:
9951         return PAGE_READ | PAGE_WRITE;
9952     case 4: /* Reserved.  */
9953         return 0;
9954     case 5:
9955         return is_user ? 0 : PAGE_READ;
9956     case 6:
9957         return PAGE_READ;
9958     case 7:
9959         if (!arm_feature(env, ARM_FEATURE_V6K)) {
9960             return 0;
9961         }
9962         return PAGE_READ;
9963     default:
9964         g_assert_not_reached();
9965     }
9966 }
9967 
9968 /* Translate section/page access permissions to page
9969  * R/W protection flags.
9970  *
9971  * @ap:      The 2-bit simple AP (AP[2:1])
9972  * @is_user: TRUE if accessing from PL0
9973  */
9974 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
9975 {
9976     switch (ap) {
9977     case 0:
9978         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
9979     case 1:
9980         return PAGE_READ | PAGE_WRITE;
9981     case 2:
9982         return is_user ? 0 : PAGE_READ;
9983     case 3:
9984         return PAGE_READ;
9985     default:
9986         g_assert_not_reached();
9987     }
9988 }
9989 
9990 static inline int
9991 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
9992 {
9993     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
9994 }
9995 
9996 /* Translate S2 section/page access permissions to protection flags
9997  *
9998  * @env:     CPUARMState
9999  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10000  * @xn:      XN (execute-never) bit
10001  */
10002 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
10003 {
10004     int prot = 0;
10005 
10006     if (s2ap & 1) {
10007         prot |= PAGE_READ;
10008     }
10009     if (s2ap & 2) {
10010         prot |= PAGE_WRITE;
10011     }
10012     if (!xn) {
10013         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10014             prot |= PAGE_EXEC;
10015         }
10016     }
10017     return prot;
10018 }
10019 
10020 /* Translate section/page access permissions to protection flags
10021  *
10022  * @env:     CPUARMState
10023  * @mmu_idx: MMU index indicating required translation regime
10024  * @is_aa64: TRUE if AArch64
10025  * @ap:      The 2-bit simple AP (AP[2:1])
10026  * @ns:      NS (non-secure) bit
10027  * @xn:      XN (execute-never) bit
10028  * @pxn:     PXN (privileged execute-never) bit
10029  */
10030 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10031                       int ap, int ns, int xn, int pxn)
10032 {
10033     bool is_user = regime_is_user(env, mmu_idx);
10034     int prot_rw, user_rw;
10035     bool have_wxn;
10036     int wxn = 0;
10037 
10038     assert(mmu_idx != ARMMMUIdx_Stage2);
10039 
10040     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10041     if (is_user) {
10042         prot_rw = user_rw;
10043     } else {
10044         if (user_rw && regime_is_pan(env, mmu_idx)) {
10045             /* PAN forbids data accesses but doesn't affect insn fetch */
10046             prot_rw = 0;
10047         } else {
10048             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10049         }
10050     }
10051 
10052     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10053         return prot_rw;
10054     }
10055 
10056     /* TODO have_wxn should be replaced with
10057      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10058      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10059      * compatible processors have EL2, which is required for [U]WXN.
10060      */
10061     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10062 
10063     if (have_wxn) {
10064         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10065     }
10066 
10067     if (is_aa64) {
10068         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10069             xn = pxn || (user_rw & PAGE_WRITE);
10070         }
10071     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10072         switch (regime_el(env, mmu_idx)) {
10073         case 1:
10074         case 3:
10075             if (is_user) {
10076                 xn = xn || !(user_rw & PAGE_READ);
10077             } else {
10078                 int uwxn = 0;
10079                 if (have_wxn) {
10080                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10081                 }
10082                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10083                      (uwxn && (user_rw & PAGE_WRITE));
10084             }
10085             break;
10086         case 2:
10087             break;
10088         }
10089     } else {
10090         xn = wxn = 0;
10091     }
10092 
10093     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10094         return prot_rw;
10095     }
10096     return prot_rw | PAGE_EXEC;
10097 }
10098 
10099 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10100                                      uint32_t *table, uint32_t address)
10101 {
10102     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10103     TCR *tcr = regime_tcr(env, mmu_idx);
10104 
10105     if (address & tcr->mask) {
10106         if (tcr->raw_tcr & TTBCR_PD1) {
10107             /* Translation table walk disabled for TTBR1 */
10108             return false;
10109         }
10110         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10111     } else {
10112         if (tcr->raw_tcr & TTBCR_PD0) {
10113             /* Translation table walk disabled for TTBR0 */
10114             return false;
10115         }
10116         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10117     }
10118     *table |= (address >> 18) & 0x3ffc;
10119     return true;
10120 }
10121 
10122 /* Translate a S1 pagetable walk through S2 if needed.  */
10123 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10124                                hwaddr addr, MemTxAttrs txattrs,
10125                                ARMMMUFaultInfo *fi)
10126 {
10127     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10128         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10129         target_ulong s2size;
10130         hwaddr s2pa;
10131         int s2prot;
10132         int ret;
10133         ARMCacheAttrs cacheattrs = {};
10134         ARMCacheAttrs *pcacheattrs = NULL;
10135 
10136         if (env->cp15.hcr_el2 & HCR_PTW) {
10137             /*
10138              * PTW means we must fault if this S1 walk touches S2 Device
10139              * memory; otherwise we don't care about the attributes and can
10140              * save the S2 translation the effort of computing them.
10141              */
10142             pcacheattrs = &cacheattrs;
10143         }
10144 
10145         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_Stage2, &s2pa,
10146                                  &txattrs, &s2prot, &s2size, fi, pcacheattrs);
10147         if (ret) {
10148             assert(fi->type != ARMFault_None);
10149             fi->s2addr = addr;
10150             fi->stage2 = true;
10151             fi->s1ptw = true;
10152             return ~0;
10153         }
10154         if (pcacheattrs && (pcacheattrs->attrs & 0xf0) == 0) {
10155             /* Access was to Device memory: generate Permission fault */
10156             fi->type = ARMFault_Permission;
10157             fi->s2addr = addr;
10158             fi->stage2 = true;
10159             fi->s1ptw = true;
10160             return ~0;
10161         }
10162         addr = s2pa;
10163     }
10164     return addr;
10165 }
10166 
10167 /* All loads done in the course of a page table walk go through here. */
10168 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10169                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10170 {
10171     ARMCPU *cpu = ARM_CPU(cs);
10172     CPUARMState *env = &cpu->env;
10173     MemTxAttrs attrs = {};
10174     MemTxResult result = MEMTX_OK;
10175     AddressSpace *as;
10176     uint32_t data;
10177 
10178     attrs.secure = is_secure;
10179     as = arm_addressspace(cs, attrs);
10180     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10181     if (fi->s1ptw) {
10182         return 0;
10183     }
10184     if (regime_translation_big_endian(env, mmu_idx)) {
10185         data = address_space_ldl_be(as, addr, attrs, &result);
10186     } else {
10187         data = address_space_ldl_le(as, addr, attrs, &result);
10188     }
10189     if (result == MEMTX_OK) {
10190         return data;
10191     }
10192     fi->type = ARMFault_SyncExternalOnWalk;
10193     fi->ea = arm_extabort_type(result);
10194     return 0;
10195 }
10196 
10197 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10198                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10199 {
10200     ARMCPU *cpu = ARM_CPU(cs);
10201     CPUARMState *env = &cpu->env;
10202     MemTxAttrs attrs = {};
10203     MemTxResult result = MEMTX_OK;
10204     AddressSpace *as;
10205     uint64_t data;
10206 
10207     attrs.secure = is_secure;
10208     as = arm_addressspace(cs, attrs);
10209     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10210     if (fi->s1ptw) {
10211         return 0;
10212     }
10213     if (regime_translation_big_endian(env, mmu_idx)) {
10214         data = address_space_ldq_be(as, addr, attrs, &result);
10215     } else {
10216         data = address_space_ldq_le(as, addr, attrs, &result);
10217     }
10218     if (result == MEMTX_OK) {
10219         return data;
10220     }
10221     fi->type = ARMFault_SyncExternalOnWalk;
10222     fi->ea = arm_extabort_type(result);
10223     return 0;
10224 }
10225 
10226 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10227                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10228                              hwaddr *phys_ptr, int *prot,
10229                              target_ulong *page_size,
10230                              ARMMMUFaultInfo *fi)
10231 {
10232     CPUState *cs = env_cpu(env);
10233     int level = 1;
10234     uint32_t table;
10235     uint32_t desc;
10236     int type;
10237     int ap;
10238     int domain = 0;
10239     int domain_prot;
10240     hwaddr phys_addr;
10241     uint32_t dacr;
10242 
10243     /* Pagetable walk.  */
10244     /* Lookup l1 descriptor.  */
10245     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10246         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10247         fi->type = ARMFault_Translation;
10248         goto do_fault;
10249     }
10250     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10251                        mmu_idx, fi);
10252     if (fi->type != ARMFault_None) {
10253         goto do_fault;
10254     }
10255     type = (desc & 3);
10256     domain = (desc >> 5) & 0x0f;
10257     if (regime_el(env, mmu_idx) == 1) {
10258         dacr = env->cp15.dacr_ns;
10259     } else {
10260         dacr = env->cp15.dacr_s;
10261     }
10262     domain_prot = (dacr >> (domain * 2)) & 3;
10263     if (type == 0) {
10264         /* Section translation fault.  */
10265         fi->type = ARMFault_Translation;
10266         goto do_fault;
10267     }
10268     if (type != 2) {
10269         level = 2;
10270     }
10271     if (domain_prot == 0 || domain_prot == 2) {
10272         fi->type = ARMFault_Domain;
10273         goto do_fault;
10274     }
10275     if (type == 2) {
10276         /* 1Mb section.  */
10277         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10278         ap = (desc >> 10) & 3;
10279         *page_size = 1024 * 1024;
10280     } else {
10281         /* Lookup l2 entry.  */
10282         if (type == 1) {
10283             /* Coarse pagetable.  */
10284             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10285         } else {
10286             /* Fine pagetable.  */
10287             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10288         }
10289         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10290                            mmu_idx, fi);
10291         if (fi->type != ARMFault_None) {
10292             goto do_fault;
10293         }
10294         switch (desc & 3) {
10295         case 0: /* Page translation fault.  */
10296             fi->type = ARMFault_Translation;
10297             goto do_fault;
10298         case 1: /* 64k page.  */
10299             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10300             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10301             *page_size = 0x10000;
10302             break;
10303         case 2: /* 4k page.  */
10304             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10305             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10306             *page_size = 0x1000;
10307             break;
10308         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10309             if (type == 1) {
10310                 /* ARMv6/XScale extended small page format */
10311                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10312                     || arm_feature(env, ARM_FEATURE_V6)) {
10313                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10314                     *page_size = 0x1000;
10315                 } else {
10316                     /* UNPREDICTABLE in ARMv5; we choose to take a
10317                      * page translation fault.
10318                      */
10319                     fi->type = ARMFault_Translation;
10320                     goto do_fault;
10321                 }
10322             } else {
10323                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10324                 *page_size = 0x400;
10325             }
10326             ap = (desc >> 4) & 3;
10327             break;
10328         default:
10329             /* Never happens, but compiler isn't smart enough to tell.  */
10330             abort();
10331         }
10332     }
10333     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10334     *prot |= *prot ? PAGE_EXEC : 0;
10335     if (!(*prot & (1 << access_type))) {
10336         /* Access permission fault.  */
10337         fi->type = ARMFault_Permission;
10338         goto do_fault;
10339     }
10340     *phys_ptr = phys_addr;
10341     return false;
10342 do_fault:
10343     fi->domain = domain;
10344     fi->level = level;
10345     return true;
10346 }
10347 
10348 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10349                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10350                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10351                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10352 {
10353     CPUState *cs = env_cpu(env);
10354     int level = 1;
10355     uint32_t table;
10356     uint32_t desc;
10357     uint32_t xn;
10358     uint32_t pxn = 0;
10359     int type;
10360     int ap;
10361     int domain = 0;
10362     int domain_prot;
10363     hwaddr phys_addr;
10364     uint32_t dacr;
10365     bool ns;
10366 
10367     /* Pagetable walk.  */
10368     /* Lookup l1 descriptor.  */
10369     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10370         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10371         fi->type = ARMFault_Translation;
10372         goto do_fault;
10373     }
10374     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10375                        mmu_idx, fi);
10376     if (fi->type != ARMFault_None) {
10377         goto do_fault;
10378     }
10379     type = (desc & 3);
10380     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
10381         /* Section translation fault, or attempt to use the encoding
10382          * which is Reserved on implementations without PXN.
10383          */
10384         fi->type = ARMFault_Translation;
10385         goto do_fault;
10386     }
10387     if ((type == 1) || !(desc & (1 << 18))) {
10388         /* Page or Section.  */
10389         domain = (desc >> 5) & 0x0f;
10390     }
10391     if (regime_el(env, mmu_idx) == 1) {
10392         dacr = env->cp15.dacr_ns;
10393     } else {
10394         dacr = env->cp15.dacr_s;
10395     }
10396     if (type == 1) {
10397         level = 2;
10398     }
10399     domain_prot = (dacr >> (domain * 2)) & 3;
10400     if (domain_prot == 0 || domain_prot == 2) {
10401         /* Section or Page domain fault */
10402         fi->type = ARMFault_Domain;
10403         goto do_fault;
10404     }
10405     if (type != 1) {
10406         if (desc & (1 << 18)) {
10407             /* Supersection.  */
10408             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
10409             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
10410             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
10411             *page_size = 0x1000000;
10412         } else {
10413             /* Section.  */
10414             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10415             *page_size = 0x100000;
10416         }
10417         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
10418         xn = desc & (1 << 4);
10419         pxn = desc & 1;
10420         ns = extract32(desc, 19, 1);
10421     } else {
10422         if (arm_feature(env, ARM_FEATURE_PXN)) {
10423             pxn = (desc >> 2) & 1;
10424         }
10425         ns = extract32(desc, 3, 1);
10426         /* Lookup l2 entry.  */
10427         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10428         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10429                            mmu_idx, fi);
10430         if (fi->type != ARMFault_None) {
10431             goto do_fault;
10432         }
10433         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
10434         switch (desc & 3) {
10435         case 0: /* Page translation fault.  */
10436             fi->type = ARMFault_Translation;
10437             goto do_fault;
10438         case 1: /* 64k page.  */
10439             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10440             xn = desc & (1 << 15);
10441             *page_size = 0x10000;
10442             break;
10443         case 2: case 3: /* 4k page.  */
10444             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10445             xn = desc & 1;
10446             *page_size = 0x1000;
10447             break;
10448         default:
10449             /* Never happens, but compiler isn't smart enough to tell.  */
10450             abort();
10451         }
10452     }
10453     if (domain_prot == 3) {
10454         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10455     } else {
10456         if (pxn && !regime_is_user(env, mmu_idx)) {
10457             xn = 1;
10458         }
10459         if (xn && access_type == MMU_INST_FETCH) {
10460             fi->type = ARMFault_Permission;
10461             goto do_fault;
10462         }
10463 
10464         if (arm_feature(env, ARM_FEATURE_V6K) &&
10465                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
10466             /* The simplified model uses AP[0] as an access control bit.  */
10467             if ((ap & 1) == 0) {
10468                 /* Access flag fault.  */
10469                 fi->type = ARMFault_AccessFlag;
10470                 goto do_fault;
10471             }
10472             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
10473         } else {
10474             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10475         }
10476         if (*prot && !xn) {
10477             *prot |= PAGE_EXEC;
10478         }
10479         if (!(*prot & (1 << access_type))) {
10480             /* Access permission fault.  */
10481             fi->type = ARMFault_Permission;
10482             goto do_fault;
10483         }
10484     }
10485     if (ns) {
10486         /* The NS bit will (as required by the architecture) have no effect if
10487          * the CPU doesn't support TZ or this is a non-secure translation
10488          * regime, because the attribute will already be non-secure.
10489          */
10490         attrs->secure = false;
10491     }
10492     *phys_ptr = phys_addr;
10493     return false;
10494 do_fault:
10495     fi->domain = domain;
10496     fi->level = level;
10497     return true;
10498 }
10499 
10500 /*
10501  * check_s2_mmu_setup
10502  * @cpu:        ARMCPU
10503  * @is_aa64:    True if the translation regime is in AArch64 state
10504  * @startlevel: Suggested starting level
10505  * @inputsize:  Bitsize of IPAs
10506  * @stride:     Page-table stride (See the ARM ARM)
10507  *
10508  * Returns true if the suggested S2 translation parameters are OK and
10509  * false otherwise.
10510  */
10511 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
10512                                int inputsize, int stride)
10513 {
10514     const int grainsize = stride + 3;
10515     int startsizecheck;
10516 
10517     /* Negative levels are never allowed.  */
10518     if (level < 0) {
10519         return false;
10520     }
10521 
10522     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
10523     if (startsizecheck < 1 || startsizecheck > stride + 4) {
10524         return false;
10525     }
10526 
10527     if (is_aa64) {
10528         CPUARMState *env = &cpu->env;
10529         unsigned int pamax = arm_pamax(cpu);
10530 
10531         switch (stride) {
10532         case 13: /* 64KB Pages.  */
10533             if (level == 0 || (level == 1 && pamax <= 42)) {
10534                 return false;
10535             }
10536             break;
10537         case 11: /* 16KB Pages.  */
10538             if (level == 0 || (level == 1 && pamax <= 40)) {
10539                 return false;
10540             }
10541             break;
10542         case 9: /* 4KB Pages.  */
10543             if (level == 0 && pamax <= 42) {
10544                 return false;
10545             }
10546             break;
10547         default:
10548             g_assert_not_reached();
10549         }
10550 
10551         /* Inputsize checks.  */
10552         if (inputsize > pamax &&
10553             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
10554             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
10555             return false;
10556         }
10557     } else {
10558         /* AArch32 only supports 4KB pages. Assert on that.  */
10559         assert(stride == 9);
10560 
10561         if (level == 0) {
10562             return false;
10563         }
10564     }
10565     return true;
10566 }
10567 
10568 /* Translate from the 4-bit stage 2 representation of
10569  * memory attributes (without cache-allocation hints) to
10570  * the 8-bit representation of the stage 1 MAIR registers
10571  * (which includes allocation hints).
10572  *
10573  * ref: shared/translation/attrs/S2AttrDecode()
10574  *      .../S2ConvertAttrsHints()
10575  */
10576 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
10577 {
10578     uint8_t hiattr = extract32(s2attrs, 2, 2);
10579     uint8_t loattr = extract32(s2attrs, 0, 2);
10580     uint8_t hihint = 0, lohint = 0;
10581 
10582     if (hiattr != 0) { /* normal memory */
10583         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
10584             hiattr = loattr = 1; /* non-cacheable */
10585         } else {
10586             if (hiattr != 1) { /* Write-through or write-back */
10587                 hihint = 3; /* RW allocate */
10588             }
10589             if (loattr != 1) { /* Write-through or write-back */
10590                 lohint = 3; /* RW allocate */
10591             }
10592         }
10593     }
10594 
10595     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
10596 }
10597 #endif /* !CONFIG_USER_ONLY */
10598 
10599 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
10600 {
10601     if (regime_has_2_ranges(mmu_idx)) {
10602         return extract64(tcr, 37, 2);
10603     } else if (mmu_idx == ARMMMUIdx_Stage2) {
10604         return 0; /* VTCR_EL2 */
10605     } else {
10606         /* Replicate the single TBI bit so we always have 2 bits.  */
10607         return extract32(tcr, 20, 1) * 3;
10608     }
10609 }
10610 
10611 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
10612 {
10613     if (regime_has_2_ranges(mmu_idx)) {
10614         return extract64(tcr, 51, 2);
10615     } else if (mmu_idx == ARMMMUIdx_Stage2) {
10616         return 0; /* VTCR_EL2 */
10617     } else {
10618         /* Replicate the single TBID bit so we always have 2 bits.  */
10619         return extract32(tcr, 29, 1) * 3;
10620     }
10621 }
10622 
10623 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
10624                                    ARMMMUIdx mmu_idx, bool data)
10625 {
10626     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
10627     bool epd, hpd, using16k, using64k;
10628     int select, tsz, tbi;
10629 
10630     if (!regime_has_2_ranges(mmu_idx)) {
10631         select = 0;
10632         tsz = extract32(tcr, 0, 6);
10633         using64k = extract32(tcr, 14, 1);
10634         using16k = extract32(tcr, 15, 1);
10635         if (mmu_idx == ARMMMUIdx_Stage2) {
10636             /* VTCR_EL2 */
10637             hpd = false;
10638         } else {
10639             hpd = extract32(tcr, 24, 1);
10640         }
10641         epd = false;
10642     } else {
10643         /*
10644          * Bit 55 is always between the two regions, and is canonical for
10645          * determining if address tagging is enabled.
10646          */
10647         select = extract64(va, 55, 1);
10648         if (!select) {
10649             tsz = extract32(tcr, 0, 6);
10650             epd = extract32(tcr, 7, 1);
10651             using64k = extract32(tcr, 14, 1);
10652             using16k = extract32(tcr, 15, 1);
10653             hpd = extract64(tcr, 41, 1);
10654         } else {
10655             int tg = extract32(tcr, 30, 2);
10656             using16k = tg == 1;
10657             using64k = tg == 3;
10658             tsz = extract32(tcr, 16, 6);
10659             epd = extract32(tcr, 23, 1);
10660             hpd = extract64(tcr, 42, 1);
10661         }
10662     }
10663     tsz = MIN(tsz, 39);  /* TODO: ARMv8.4-TTST */
10664     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
10665 
10666     /* Present TBI as a composite with TBID.  */
10667     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
10668     if (!data) {
10669         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
10670     }
10671     tbi = (tbi >> select) & 1;
10672 
10673     return (ARMVAParameters) {
10674         .tsz = tsz,
10675         .select = select,
10676         .tbi = tbi,
10677         .epd = epd,
10678         .hpd = hpd,
10679         .using16k = using16k,
10680         .using64k = using64k,
10681     };
10682 }
10683 
10684 #ifndef CONFIG_USER_ONLY
10685 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
10686                                           ARMMMUIdx mmu_idx)
10687 {
10688     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
10689     uint32_t el = regime_el(env, mmu_idx);
10690     int select, tsz;
10691     bool epd, hpd;
10692 
10693     if (mmu_idx == ARMMMUIdx_Stage2) {
10694         /* VTCR */
10695         bool sext = extract32(tcr, 4, 1);
10696         bool sign = extract32(tcr, 3, 1);
10697 
10698         /*
10699          * If the sign-extend bit is not the same as t0sz[3], the result
10700          * is unpredictable. Flag this as a guest error.
10701          */
10702         if (sign != sext) {
10703             qemu_log_mask(LOG_GUEST_ERROR,
10704                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
10705         }
10706         tsz = sextract32(tcr, 0, 4) + 8;
10707         select = 0;
10708         hpd = false;
10709         epd = false;
10710     } else if (el == 2) {
10711         /* HTCR */
10712         tsz = extract32(tcr, 0, 3);
10713         select = 0;
10714         hpd = extract64(tcr, 24, 1);
10715         epd = false;
10716     } else {
10717         int t0sz = extract32(tcr, 0, 3);
10718         int t1sz = extract32(tcr, 16, 3);
10719 
10720         if (t1sz == 0) {
10721             select = va > (0xffffffffu >> t0sz);
10722         } else {
10723             /* Note that we will detect errors later.  */
10724             select = va >= ~(0xffffffffu >> t1sz);
10725         }
10726         if (!select) {
10727             tsz = t0sz;
10728             epd = extract32(tcr, 7, 1);
10729             hpd = extract64(tcr, 41, 1);
10730         } else {
10731             tsz = t1sz;
10732             epd = extract32(tcr, 23, 1);
10733             hpd = extract64(tcr, 42, 1);
10734         }
10735         /* For aarch32, hpd0 is not enabled without t2e as well.  */
10736         hpd &= extract32(tcr, 6, 1);
10737     }
10738 
10739     return (ARMVAParameters) {
10740         .tsz = tsz,
10741         .select = select,
10742         .epd = epd,
10743         .hpd = hpd,
10744     };
10745 }
10746 
10747 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
10748                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
10749                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
10750                                target_ulong *page_size_ptr,
10751                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10752 {
10753     ARMCPU *cpu = env_archcpu(env);
10754     CPUState *cs = CPU(cpu);
10755     /* Read an LPAE long-descriptor translation table. */
10756     ARMFaultType fault_type = ARMFault_Translation;
10757     uint32_t level;
10758     ARMVAParameters param;
10759     uint64_t ttbr;
10760     hwaddr descaddr, indexmask, indexmask_grainsize;
10761     uint32_t tableattrs;
10762     target_ulong page_size;
10763     uint32_t attrs;
10764     int32_t stride;
10765     int addrsize, inputsize;
10766     TCR *tcr = regime_tcr(env, mmu_idx);
10767     int ap, ns, xn, pxn;
10768     uint32_t el = regime_el(env, mmu_idx);
10769     uint64_t descaddrmask;
10770     bool aarch64 = arm_el_is_aa64(env, el);
10771     bool guarded = false;
10772 
10773     /* TODO: This code does not support shareability levels. */
10774     if (aarch64) {
10775         param = aa64_va_parameters(env, address, mmu_idx,
10776                                    access_type != MMU_INST_FETCH);
10777         level = 0;
10778         addrsize = 64 - 8 * param.tbi;
10779         inputsize = 64 - param.tsz;
10780     } else {
10781         param = aa32_va_parameters(env, address, mmu_idx);
10782         level = 1;
10783         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
10784         inputsize = addrsize - param.tsz;
10785     }
10786 
10787     /*
10788      * We determined the region when collecting the parameters, but we
10789      * have not yet validated that the address is valid for the region.
10790      * Extract the top bits and verify that they all match select.
10791      *
10792      * For aa32, if inputsize == addrsize, then we have selected the
10793      * region by exclusion in aa32_va_parameters and there is no more
10794      * validation to do here.
10795      */
10796     if (inputsize < addrsize) {
10797         target_ulong top_bits = sextract64(address, inputsize,
10798                                            addrsize - inputsize);
10799         if (-top_bits != param.select) {
10800             /* The gap between the two regions is a Translation fault */
10801             fault_type = ARMFault_Translation;
10802             goto do_fault;
10803         }
10804     }
10805 
10806     if (param.using64k) {
10807         stride = 13;
10808     } else if (param.using16k) {
10809         stride = 11;
10810     } else {
10811         stride = 9;
10812     }
10813 
10814     /* Note that QEMU ignores shareability and cacheability attributes,
10815      * so we don't need to do anything with the SH, ORGN, IRGN fields
10816      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
10817      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
10818      * implement any ASID-like capability so we can ignore it (instead
10819      * we will always flush the TLB any time the ASID is changed).
10820      */
10821     ttbr = regime_ttbr(env, mmu_idx, param.select);
10822 
10823     /* Here we should have set up all the parameters for the translation:
10824      * inputsize, ttbr, epd, stride, tbi
10825      */
10826 
10827     if (param.epd) {
10828         /* Translation table walk disabled => Translation fault on TLB miss
10829          * Note: This is always 0 on 64-bit EL2 and EL3.
10830          */
10831         goto do_fault;
10832     }
10833 
10834     if (mmu_idx != ARMMMUIdx_Stage2) {
10835         /* The starting level depends on the virtual address size (which can
10836          * be up to 48 bits) and the translation granule size. It indicates
10837          * the number of strides (stride bits at a time) needed to
10838          * consume the bits of the input address. In the pseudocode this is:
10839          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
10840          * where their 'inputsize' is our 'inputsize', 'grainsize' is
10841          * our 'stride + 3' and 'stride' is our 'stride'.
10842          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
10843          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
10844          * = 4 - (inputsize - 4) / stride;
10845          */
10846         level = 4 - (inputsize - 4) / stride;
10847     } else {
10848         /* For stage 2 translations the starting level is specified by the
10849          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
10850          */
10851         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
10852         uint32_t startlevel;
10853         bool ok;
10854 
10855         if (!aarch64 || stride == 9) {
10856             /* AArch32 or 4KB pages */
10857             startlevel = 2 - sl0;
10858         } else {
10859             /* 16KB or 64KB pages */
10860             startlevel = 3 - sl0;
10861         }
10862 
10863         /* Check that the starting level is valid. */
10864         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
10865                                 inputsize, stride);
10866         if (!ok) {
10867             fault_type = ARMFault_Translation;
10868             goto do_fault;
10869         }
10870         level = startlevel;
10871     }
10872 
10873     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
10874     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
10875 
10876     /* Now we can extract the actual base address from the TTBR */
10877     descaddr = extract64(ttbr, 0, 48);
10878     /*
10879      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
10880      * and also to mask out CnP (bit 0) which could validly be non-zero.
10881      */
10882     descaddr &= ~indexmask;
10883 
10884     /* The address field in the descriptor goes up to bit 39 for ARMv7
10885      * but up to bit 47 for ARMv8, but we use the descaddrmask
10886      * up to bit 39 for AArch32, because we don't need other bits in that case
10887      * to construct next descriptor address (anyway they should be all zeroes).
10888      */
10889     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
10890                    ~indexmask_grainsize;
10891 
10892     /* Secure accesses start with the page table in secure memory and
10893      * can be downgraded to non-secure at any step. Non-secure accesses
10894      * remain non-secure. We implement this by just ORing in the NSTable/NS
10895      * bits at each step.
10896      */
10897     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
10898     for (;;) {
10899         uint64_t descriptor;
10900         bool nstable;
10901 
10902         descaddr |= (address >> (stride * (4 - level))) & indexmask;
10903         descaddr &= ~7ULL;
10904         nstable = extract32(tableattrs, 4, 1);
10905         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
10906         if (fi->type != ARMFault_None) {
10907             goto do_fault;
10908         }
10909 
10910         if (!(descriptor & 1) ||
10911             (!(descriptor & 2) && (level == 3))) {
10912             /* Invalid, or the Reserved level 3 encoding */
10913             goto do_fault;
10914         }
10915         descaddr = descriptor & descaddrmask;
10916 
10917         if ((descriptor & 2) && (level < 3)) {
10918             /* Table entry. The top five bits are attributes which may
10919              * propagate down through lower levels of the table (and
10920              * which are all arranged so that 0 means "no effect", so
10921              * we can gather them up by ORing in the bits at each level).
10922              */
10923             tableattrs |= extract64(descriptor, 59, 5);
10924             level++;
10925             indexmask = indexmask_grainsize;
10926             continue;
10927         }
10928         /* Block entry at level 1 or 2, or page entry at level 3.
10929          * These are basically the same thing, although the number
10930          * of bits we pull in from the vaddr varies.
10931          */
10932         page_size = (1ULL << ((stride * (4 - level)) + 3));
10933         descaddr |= (address & (page_size - 1));
10934         /* Extract attributes from the descriptor */
10935         attrs = extract64(descriptor, 2, 10)
10936             | (extract64(descriptor, 52, 12) << 10);
10937 
10938         if (mmu_idx == ARMMMUIdx_Stage2) {
10939             /* Stage 2 table descriptors do not include any attribute fields */
10940             break;
10941         }
10942         /* Merge in attributes from table descriptors */
10943         attrs |= nstable << 3; /* NS */
10944         guarded = extract64(descriptor, 50, 1);  /* GP */
10945         if (param.hpd) {
10946             /* HPD disables all the table attributes except NSTable.  */
10947             break;
10948         }
10949         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
10950         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
10951          * means "force PL1 access only", which means forcing AP[1] to 0.
10952          */
10953         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
10954         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
10955         break;
10956     }
10957     /* Here descaddr is the final physical address, and attributes
10958      * are all in attrs.
10959      */
10960     fault_type = ARMFault_AccessFlag;
10961     if ((attrs & (1 << 8)) == 0) {
10962         /* Access flag */
10963         goto do_fault;
10964     }
10965 
10966     ap = extract32(attrs, 4, 2);
10967     xn = extract32(attrs, 12, 1);
10968 
10969     if (mmu_idx == ARMMMUIdx_Stage2) {
10970         ns = true;
10971         *prot = get_S2prot(env, ap, xn);
10972     } else {
10973         ns = extract32(attrs, 3, 1);
10974         pxn = extract32(attrs, 11, 1);
10975         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
10976     }
10977 
10978     fault_type = ARMFault_Permission;
10979     if (!(*prot & (1 << access_type))) {
10980         goto do_fault;
10981     }
10982 
10983     if (ns) {
10984         /* The NS bit will (as required by the architecture) have no effect if
10985          * the CPU doesn't support TZ or this is a non-secure translation
10986          * regime, because the attribute will already be non-secure.
10987          */
10988         txattrs->secure = false;
10989     }
10990     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
10991     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
10992         txattrs->target_tlb_bit0 = true;
10993     }
10994 
10995     if (cacheattrs != NULL) {
10996         if (mmu_idx == ARMMMUIdx_Stage2) {
10997             cacheattrs->attrs = convert_stage2_attrs(env,
10998                                                      extract32(attrs, 0, 4));
10999         } else {
11000             /* Index into MAIR registers for cache attributes */
11001             uint8_t attrindx = extract32(attrs, 0, 3);
11002             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11003             assert(attrindx <= 7);
11004             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11005         }
11006         cacheattrs->shareability = extract32(attrs, 6, 2);
11007     }
11008 
11009     *phys_ptr = descaddr;
11010     *page_size_ptr = page_size;
11011     return false;
11012 
11013 do_fault:
11014     fi->type = fault_type;
11015     fi->level = level;
11016     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11017     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2);
11018     return true;
11019 }
11020 
11021 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11022                                                 ARMMMUIdx mmu_idx,
11023                                                 int32_t address, int *prot)
11024 {
11025     if (!arm_feature(env, ARM_FEATURE_M)) {
11026         *prot = PAGE_READ | PAGE_WRITE;
11027         switch (address) {
11028         case 0xF0000000 ... 0xFFFFFFFF:
11029             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11030                 /* hivecs execing is ok */
11031                 *prot |= PAGE_EXEC;
11032             }
11033             break;
11034         case 0x00000000 ... 0x7FFFFFFF:
11035             *prot |= PAGE_EXEC;
11036             break;
11037         }
11038     } else {
11039         /* Default system address map for M profile cores.
11040          * The architecture specifies which regions are execute-never;
11041          * at the MPU level no other checks are defined.
11042          */
11043         switch (address) {
11044         case 0x00000000 ... 0x1fffffff: /* ROM */
11045         case 0x20000000 ... 0x3fffffff: /* SRAM */
11046         case 0x60000000 ... 0x7fffffff: /* RAM */
11047         case 0x80000000 ... 0x9fffffff: /* RAM */
11048             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11049             break;
11050         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11051         case 0xa0000000 ... 0xbfffffff: /* Device */
11052         case 0xc0000000 ... 0xdfffffff: /* Device */
11053         case 0xe0000000 ... 0xffffffff: /* System */
11054             *prot = PAGE_READ | PAGE_WRITE;
11055             break;
11056         default:
11057             g_assert_not_reached();
11058         }
11059     }
11060 }
11061 
11062 static bool pmsav7_use_background_region(ARMCPU *cpu,
11063                                          ARMMMUIdx mmu_idx, bool is_user)
11064 {
11065     /* Return true if we should use the default memory map as a
11066      * "background" region if there are no hits against any MPU regions.
11067      */
11068     CPUARMState *env = &cpu->env;
11069 
11070     if (is_user) {
11071         return false;
11072     }
11073 
11074     if (arm_feature(env, ARM_FEATURE_M)) {
11075         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11076             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11077     } else {
11078         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11079     }
11080 }
11081 
11082 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11083 {
11084     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11085     return arm_feature(env, ARM_FEATURE_M) &&
11086         extract32(address, 20, 12) == 0xe00;
11087 }
11088 
11089 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11090 {
11091     /* True if address is in the M profile system region
11092      * 0xe0000000 - 0xffffffff
11093      */
11094     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11095 }
11096 
11097 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11098                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11099                                  hwaddr *phys_ptr, int *prot,
11100                                  target_ulong *page_size,
11101                                  ARMMMUFaultInfo *fi)
11102 {
11103     ARMCPU *cpu = env_archcpu(env);
11104     int n;
11105     bool is_user = regime_is_user(env, mmu_idx);
11106 
11107     *phys_ptr = address;
11108     *page_size = TARGET_PAGE_SIZE;
11109     *prot = 0;
11110 
11111     if (regime_translation_disabled(env, mmu_idx) ||
11112         m_is_ppb_region(env, address)) {
11113         /* MPU disabled or M profile PPB access: use default memory map.
11114          * The other case which uses the default memory map in the
11115          * v7M ARM ARM pseudocode is exception vector reads from the vector
11116          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11117          * which always does a direct read using address_space_ldl(), rather
11118          * than going via this function, so we don't need to check that here.
11119          */
11120         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11121     } else { /* MPU enabled */
11122         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11123             /* region search */
11124             uint32_t base = env->pmsav7.drbar[n];
11125             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11126             uint32_t rmask;
11127             bool srdis = false;
11128 
11129             if (!(env->pmsav7.drsr[n] & 0x1)) {
11130                 continue;
11131             }
11132 
11133             if (!rsize) {
11134                 qemu_log_mask(LOG_GUEST_ERROR,
11135                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11136                 continue;
11137             }
11138             rsize++;
11139             rmask = (1ull << rsize) - 1;
11140 
11141             if (base & rmask) {
11142                 qemu_log_mask(LOG_GUEST_ERROR,
11143                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11144                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11145                               n, base, rmask);
11146                 continue;
11147             }
11148 
11149             if (address < base || address > base + rmask) {
11150                 /*
11151                  * Address not in this region. We must check whether the
11152                  * region covers addresses in the same page as our address.
11153                  * In that case we must not report a size that covers the
11154                  * whole page for a subsequent hit against a different MPU
11155                  * region or the background region, because it would result in
11156                  * incorrect TLB hits for subsequent accesses to addresses that
11157                  * are in this MPU region.
11158                  */
11159                 if (ranges_overlap(base, rmask,
11160                                    address & TARGET_PAGE_MASK,
11161                                    TARGET_PAGE_SIZE)) {
11162                     *page_size = 1;
11163                 }
11164                 continue;
11165             }
11166 
11167             /* Region matched */
11168 
11169             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11170                 int i, snd;
11171                 uint32_t srdis_mask;
11172 
11173                 rsize -= 3; /* sub region size (power of 2) */
11174                 snd = ((address - base) >> rsize) & 0x7;
11175                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11176 
11177                 srdis_mask = srdis ? 0x3 : 0x0;
11178                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11179                     /* This will check in groups of 2, 4 and then 8, whether
11180                      * the subregion bits are consistent. rsize is incremented
11181                      * back up to give the region size, considering consistent
11182                      * adjacent subregions as one region. Stop testing if rsize
11183                      * is already big enough for an entire QEMU page.
11184                      */
11185                     int snd_rounded = snd & ~(i - 1);
11186                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11187                                                      snd_rounded + 8, i);
11188                     if (srdis_mask ^ srdis_multi) {
11189                         break;
11190                     }
11191                     srdis_mask = (srdis_mask << i) | srdis_mask;
11192                     rsize++;
11193                 }
11194             }
11195             if (srdis) {
11196                 continue;
11197             }
11198             if (rsize < TARGET_PAGE_BITS) {
11199                 *page_size = 1 << rsize;
11200             }
11201             break;
11202         }
11203 
11204         if (n == -1) { /* no hits */
11205             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11206                 /* background fault */
11207                 fi->type = ARMFault_Background;
11208                 return true;
11209             }
11210             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11211         } else { /* a MPU hit! */
11212             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11213             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11214 
11215             if (m_is_system_region(env, address)) {
11216                 /* System space is always execute never */
11217                 xn = 1;
11218             }
11219 
11220             if (is_user) { /* User mode AP bit decoding */
11221                 switch (ap) {
11222                 case 0:
11223                 case 1:
11224                 case 5:
11225                     break; /* no access */
11226                 case 3:
11227                     *prot |= PAGE_WRITE;
11228                     /* fall through */
11229                 case 2:
11230                 case 6:
11231                     *prot |= PAGE_READ | PAGE_EXEC;
11232                     break;
11233                 case 7:
11234                     /* for v7M, same as 6; for R profile a reserved value */
11235                     if (arm_feature(env, ARM_FEATURE_M)) {
11236                         *prot |= PAGE_READ | PAGE_EXEC;
11237                         break;
11238                     }
11239                     /* fall through */
11240                 default:
11241                     qemu_log_mask(LOG_GUEST_ERROR,
11242                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11243                                   PRIx32 "\n", n, ap);
11244                 }
11245             } else { /* Priv. mode AP bits decoding */
11246                 switch (ap) {
11247                 case 0:
11248                     break; /* no access */
11249                 case 1:
11250                 case 2:
11251                 case 3:
11252                     *prot |= PAGE_WRITE;
11253                     /* fall through */
11254                 case 5:
11255                 case 6:
11256                     *prot |= PAGE_READ | PAGE_EXEC;
11257                     break;
11258                 case 7:
11259                     /* for v7M, same as 6; for R profile a reserved value */
11260                     if (arm_feature(env, ARM_FEATURE_M)) {
11261                         *prot |= PAGE_READ | PAGE_EXEC;
11262                         break;
11263                     }
11264                     /* fall through */
11265                 default:
11266                     qemu_log_mask(LOG_GUEST_ERROR,
11267                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11268                                   PRIx32 "\n", n, ap);
11269                 }
11270             }
11271 
11272             /* execute never */
11273             if (xn) {
11274                 *prot &= ~PAGE_EXEC;
11275             }
11276         }
11277     }
11278 
11279     fi->type = ARMFault_Permission;
11280     fi->level = 1;
11281     return !(*prot & (1 << access_type));
11282 }
11283 
11284 static bool v8m_is_sau_exempt(CPUARMState *env,
11285                               uint32_t address, MMUAccessType access_type)
11286 {
11287     /* The architecture specifies that certain address ranges are
11288      * exempt from v8M SAU/IDAU checks.
11289      */
11290     return
11291         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
11292         (address >= 0xe0000000 && address <= 0xe0002fff) ||
11293         (address >= 0xe000e000 && address <= 0xe000efff) ||
11294         (address >= 0xe002e000 && address <= 0xe002efff) ||
11295         (address >= 0xe0040000 && address <= 0xe0041fff) ||
11296         (address >= 0xe00ff000 && address <= 0xe00fffff);
11297 }
11298 
11299 void v8m_security_lookup(CPUARMState *env, uint32_t address,
11300                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
11301                                 V8M_SAttributes *sattrs)
11302 {
11303     /* Look up the security attributes for this address. Compare the
11304      * pseudocode SecurityCheck() function.
11305      * We assume the caller has zero-initialized *sattrs.
11306      */
11307     ARMCPU *cpu = env_archcpu(env);
11308     int r;
11309     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
11310     int idau_region = IREGION_NOTVALID;
11311     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11312     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11313 
11314     if (cpu->idau) {
11315         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
11316         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
11317 
11318         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
11319                    &idau_nsc);
11320     }
11321 
11322     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
11323         /* 0xf0000000..0xffffffff is always S for insn fetches */
11324         return;
11325     }
11326 
11327     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
11328         sattrs->ns = !regime_is_secure(env, mmu_idx);
11329         return;
11330     }
11331 
11332     if (idau_region != IREGION_NOTVALID) {
11333         sattrs->irvalid = true;
11334         sattrs->iregion = idau_region;
11335     }
11336 
11337     switch (env->sau.ctrl & 3) {
11338     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
11339         break;
11340     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
11341         sattrs->ns = true;
11342         break;
11343     default: /* SAU.ENABLE == 1 */
11344         for (r = 0; r < cpu->sau_sregion; r++) {
11345             if (env->sau.rlar[r] & 1) {
11346                 uint32_t base = env->sau.rbar[r] & ~0x1f;
11347                 uint32_t limit = env->sau.rlar[r] | 0x1f;
11348 
11349                 if (base <= address && limit >= address) {
11350                     if (base > addr_page_base || limit < addr_page_limit) {
11351                         sattrs->subpage = true;
11352                     }
11353                     if (sattrs->srvalid) {
11354                         /* If we hit in more than one region then we must report
11355                          * as Secure, not NS-Callable, with no valid region
11356                          * number info.
11357                          */
11358                         sattrs->ns = false;
11359                         sattrs->nsc = false;
11360                         sattrs->sregion = 0;
11361                         sattrs->srvalid = false;
11362                         break;
11363                     } else {
11364                         if (env->sau.rlar[r] & 2) {
11365                             sattrs->nsc = true;
11366                         } else {
11367                             sattrs->ns = true;
11368                         }
11369                         sattrs->srvalid = true;
11370                         sattrs->sregion = r;
11371                     }
11372                 } else {
11373                     /*
11374                      * Address not in this region. We must check whether the
11375                      * region covers addresses in the same page as our address.
11376                      * In that case we must not report a size that covers the
11377                      * whole page for a subsequent hit against a different MPU
11378                      * region or the background region, because it would result
11379                      * in incorrect TLB hits for subsequent accesses to
11380                      * addresses that are in this MPU region.
11381                      */
11382                     if (limit >= base &&
11383                         ranges_overlap(base, limit - base + 1,
11384                                        addr_page_base,
11385                                        TARGET_PAGE_SIZE)) {
11386                         sattrs->subpage = true;
11387                     }
11388                 }
11389             }
11390         }
11391         break;
11392     }
11393 
11394     /*
11395      * The IDAU will override the SAU lookup results if it specifies
11396      * higher security than the SAU does.
11397      */
11398     if (!idau_ns) {
11399         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
11400             sattrs->ns = false;
11401             sattrs->nsc = idau_nsc;
11402         }
11403     }
11404 }
11405 
11406 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
11407                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
11408                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
11409                               int *prot, bool *is_subpage,
11410                               ARMMMUFaultInfo *fi, uint32_t *mregion)
11411 {
11412     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
11413      * that a full phys-to-virt translation does).
11414      * mregion is (if not NULL) set to the region number which matched,
11415      * or -1 if no region number is returned (MPU off, address did not
11416      * hit a region, address hit in multiple regions).
11417      * We set is_subpage to true if the region hit doesn't cover the
11418      * entire TARGET_PAGE the address is within.
11419      */
11420     ARMCPU *cpu = env_archcpu(env);
11421     bool is_user = regime_is_user(env, mmu_idx);
11422     uint32_t secure = regime_is_secure(env, mmu_idx);
11423     int n;
11424     int matchregion = -1;
11425     bool hit = false;
11426     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11427     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11428 
11429     *is_subpage = false;
11430     *phys_ptr = address;
11431     *prot = 0;
11432     if (mregion) {
11433         *mregion = -1;
11434     }
11435 
11436     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
11437      * was an exception vector read from the vector table (which is always
11438      * done using the default system address map), because those accesses
11439      * are done in arm_v7m_load_vector(), which always does a direct
11440      * read using address_space_ldl(), rather than going via this function.
11441      */
11442     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
11443         hit = true;
11444     } else if (m_is_ppb_region(env, address)) {
11445         hit = true;
11446     } else {
11447         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11448             hit = true;
11449         }
11450 
11451         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11452             /* region search */
11453             /* Note that the base address is bits [31:5] from the register
11454              * with bits [4:0] all zeroes, but the limit address is bits
11455              * [31:5] from the register with bits [4:0] all ones.
11456              */
11457             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
11458             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
11459 
11460             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
11461                 /* Region disabled */
11462                 continue;
11463             }
11464 
11465             if (address < base || address > limit) {
11466                 /*
11467                  * Address not in this region. We must check whether the
11468                  * region covers addresses in the same page as our address.
11469                  * In that case we must not report a size that covers the
11470                  * whole page for a subsequent hit against a different MPU
11471                  * region or the background region, because it would result in
11472                  * incorrect TLB hits for subsequent accesses to addresses that
11473                  * are in this MPU region.
11474                  */
11475                 if (limit >= base &&
11476                     ranges_overlap(base, limit - base + 1,
11477                                    addr_page_base,
11478                                    TARGET_PAGE_SIZE)) {
11479                     *is_subpage = true;
11480                 }
11481                 continue;
11482             }
11483 
11484             if (base > addr_page_base || limit < addr_page_limit) {
11485                 *is_subpage = true;
11486             }
11487 
11488             if (matchregion != -1) {
11489                 /* Multiple regions match -- always a failure (unlike
11490                  * PMSAv7 where highest-numbered-region wins)
11491                  */
11492                 fi->type = ARMFault_Permission;
11493                 fi->level = 1;
11494                 return true;
11495             }
11496 
11497             matchregion = n;
11498             hit = true;
11499         }
11500     }
11501 
11502     if (!hit) {
11503         /* background fault */
11504         fi->type = ARMFault_Background;
11505         return true;
11506     }
11507 
11508     if (matchregion == -1) {
11509         /* hit using the background region */
11510         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11511     } else {
11512         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
11513         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
11514 
11515         if (m_is_system_region(env, address)) {
11516             /* System space is always execute never */
11517             xn = 1;
11518         }
11519 
11520         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
11521         if (*prot && !xn) {
11522             *prot |= PAGE_EXEC;
11523         }
11524         /* We don't need to look the attribute up in the MAIR0/MAIR1
11525          * registers because that only tells us about cacheability.
11526          */
11527         if (mregion) {
11528             *mregion = matchregion;
11529         }
11530     }
11531 
11532     fi->type = ARMFault_Permission;
11533     fi->level = 1;
11534     return !(*prot & (1 << access_type));
11535 }
11536 
11537 
11538 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
11539                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11540                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
11541                                  int *prot, target_ulong *page_size,
11542                                  ARMMMUFaultInfo *fi)
11543 {
11544     uint32_t secure = regime_is_secure(env, mmu_idx);
11545     V8M_SAttributes sattrs = {};
11546     bool ret;
11547     bool mpu_is_subpage;
11548 
11549     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
11550         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
11551         if (access_type == MMU_INST_FETCH) {
11552             /* Instruction fetches always use the MMU bank and the
11553              * transaction attribute determined by the fetch address,
11554              * regardless of CPU state. This is painful for QEMU
11555              * to handle, because it would mean we need to encode
11556              * into the mmu_idx not just the (user, negpri) information
11557              * for the current security state but also that for the
11558              * other security state, which would balloon the number
11559              * of mmu_idx values needed alarmingly.
11560              * Fortunately we can avoid this because it's not actually
11561              * possible to arbitrarily execute code from memory with
11562              * the wrong security attribute: it will always generate
11563              * an exception of some kind or another, apart from the
11564              * special case of an NS CPU executing an SG instruction
11565              * in S&NSC memory. So we always just fail the translation
11566              * here and sort things out in the exception handler
11567              * (including possibly emulating an SG instruction).
11568              */
11569             if (sattrs.ns != !secure) {
11570                 if (sattrs.nsc) {
11571                     fi->type = ARMFault_QEMU_NSCExec;
11572                 } else {
11573                     fi->type = ARMFault_QEMU_SFault;
11574                 }
11575                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
11576                 *phys_ptr = address;
11577                 *prot = 0;
11578                 return true;
11579             }
11580         } else {
11581             /* For data accesses we always use the MMU bank indicated
11582              * by the current CPU state, but the security attributes
11583              * might downgrade a secure access to nonsecure.
11584              */
11585             if (sattrs.ns) {
11586                 txattrs->secure = false;
11587             } else if (!secure) {
11588                 /* NS access to S memory must fault.
11589                  * Architecturally we should first check whether the
11590                  * MPU information for this address indicates that we
11591                  * are doing an unaligned access to Device memory, which
11592                  * should generate a UsageFault instead. QEMU does not
11593                  * currently check for that kind of unaligned access though.
11594                  * If we added it we would need to do so as a special case
11595                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
11596                  */
11597                 fi->type = ARMFault_QEMU_SFault;
11598                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
11599                 *phys_ptr = address;
11600                 *prot = 0;
11601                 return true;
11602             }
11603         }
11604     }
11605 
11606     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
11607                             txattrs, prot, &mpu_is_subpage, fi, NULL);
11608     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
11609     return ret;
11610 }
11611 
11612 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
11613                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11614                                  hwaddr *phys_ptr, int *prot,
11615                                  ARMMMUFaultInfo *fi)
11616 {
11617     int n;
11618     uint32_t mask;
11619     uint32_t base;
11620     bool is_user = regime_is_user(env, mmu_idx);
11621 
11622     if (regime_translation_disabled(env, mmu_idx)) {
11623         /* MPU disabled.  */
11624         *phys_ptr = address;
11625         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11626         return false;
11627     }
11628 
11629     *phys_ptr = address;
11630     for (n = 7; n >= 0; n--) {
11631         base = env->cp15.c6_region[n];
11632         if ((base & 1) == 0) {
11633             continue;
11634         }
11635         mask = 1 << ((base >> 1) & 0x1f);
11636         /* Keep this shift separate from the above to avoid an
11637            (undefined) << 32.  */
11638         mask = (mask << 1) - 1;
11639         if (((base ^ address) & ~mask) == 0) {
11640             break;
11641         }
11642     }
11643     if (n < 0) {
11644         fi->type = ARMFault_Background;
11645         return true;
11646     }
11647 
11648     if (access_type == MMU_INST_FETCH) {
11649         mask = env->cp15.pmsav5_insn_ap;
11650     } else {
11651         mask = env->cp15.pmsav5_data_ap;
11652     }
11653     mask = (mask >> (n * 4)) & 0xf;
11654     switch (mask) {
11655     case 0:
11656         fi->type = ARMFault_Permission;
11657         fi->level = 1;
11658         return true;
11659     case 1:
11660         if (is_user) {
11661             fi->type = ARMFault_Permission;
11662             fi->level = 1;
11663             return true;
11664         }
11665         *prot = PAGE_READ | PAGE_WRITE;
11666         break;
11667     case 2:
11668         *prot = PAGE_READ;
11669         if (!is_user) {
11670             *prot |= PAGE_WRITE;
11671         }
11672         break;
11673     case 3:
11674         *prot = PAGE_READ | PAGE_WRITE;
11675         break;
11676     case 5:
11677         if (is_user) {
11678             fi->type = ARMFault_Permission;
11679             fi->level = 1;
11680             return true;
11681         }
11682         *prot = PAGE_READ;
11683         break;
11684     case 6:
11685         *prot = PAGE_READ;
11686         break;
11687     default:
11688         /* Bad permission.  */
11689         fi->type = ARMFault_Permission;
11690         fi->level = 1;
11691         return true;
11692     }
11693     *prot |= PAGE_EXEC;
11694     return false;
11695 }
11696 
11697 /* Combine either inner or outer cacheability attributes for normal
11698  * memory, according to table D4-42 and pseudocode procedure
11699  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
11700  *
11701  * NB: only stage 1 includes allocation hints (RW bits), leading to
11702  * some asymmetry.
11703  */
11704 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
11705 {
11706     if (s1 == 4 || s2 == 4) {
11707         /* non-cacheable has precedence */
11708         return 4;
11709     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
11710         /* stage 1 write-through takes precedence */
11711         return s1;
11712     } else if (extract32(s2, 2, 2) == 2) {
11713         /* stage 2 write-through takes precedence, but the allocation hint
11714          * is still taken from stage 1
11715          */
11716         return (2 << 2) | extract32(s1, 0, 2);
11717     } else { /* write-back */
11718         return s1;
11719     }
11720 }
11721 
11722 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
11723  * and CombineS1S2Desc()
11724  *
11725  * @s1:      Attributes from stage 1 walk
11726  * @s2:      Attributes from stage 2 walk
11727  */
11728 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
11729 {
11730     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
11731     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
11732     ARMCacheAttrs ret;
11733 
11734     /* Combine shareability attributes (table D4-43) */
11735     if (s1.shareability == 2 || s2.shareability == 2) {
11736         /* if either are outer-shareable, the result is outer-shareable */
11737         ret.shareability = 2;
11738     } else if (s1.shareability == 3 || s2.shareability == 3) {
11739         /* if either are inner-shareable, the result is inner-shareable */
11740         ret.shareability = 3;
11741     } else {
11742         /* both non-shareable */
11743         ret.shareability = 0;
11744     }
11745 
11746     /* Combine memory type and cacheability attributes */
11747     if (s1hi == 0 || s2hi == 0) {
11748         /* Device has precedence over normal */
11749         if (s1lo == 0 || s2lo == 0) {
11750             /* nGnRnE has precedence over anything */
11751             ret.attrs = 0;
11752         } else if (s1lo == 4 || s2lo == 4) {
11753             /* non-Reordering has precedence over Reordering */
11754             ret.attrs = 4;  /* nGnRE */
11755         } else if (s1lo == 8 || s2lo == 8) {
11756             /* non-Gathering has precedence over Gathering */
11757             ret.attrs = 8;  /* nGRE */
11758         } else {
11759             ret.attrs = 0xc; /* GRE */
11760         }
11761 
11762         /* Any location for which the resultant memory type is any
11763          * type of Device memory is always treated as Outer Shareable.
11764          */
11765         ret.shareability = 2;
11766     } else { /* Normal memory */
11767         /* Outer/inner cacheability combine independently */
11768         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
11769                   | combine_cacheattr_nibble(s1lo, s2lo);
11770 
11771         if (ret.attrs == 0x44) {
11772             /* Any location for which the resultant memory type is Normal
11773              * Inner Non-cacheable, Outer Non-cacheable is always treated
11774              * as Outer Shareable.
11775              */
11776             ret.shareability = 2;
11777         }
11778     }
11779 
11780     return ret;
11781 }
11782 
11783 
11784 /* get_phys_addr - get the physical address for this virtual address
11785  *
11786  * Find the physical address corresponding to the given virtual address,
11787  * by doing a translation table walk on MMU based systems or using the
11788  * MPU state on MPU based systems.
11789  *
11790  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11791  * prot and page_size may not be filled in, and the populated fsr value provides
11792  * information on why the translation aborted, in the format of a
11793  * DFSR/IFSR fault register, with the following caveats:
11794  *  * we honour the short vs long DFSR format differences.
11795  *  * the WnR bit is never set (the caller must do this).
11796  *  * for PSMAv5 based systems we don't bother to return a full FSR format
11797  *    value.
11798  *
11799  * @env: CPUARMState
11800  * @address: virtual address to get physical address for
11801  * @access_type: 0 for read, 1 for write, 2 for execute
11802  * @mmu_idx: MMU index indicating required translation regime
11803  * @phys_ptr: set to the physical address corresponding to the virtual address
11804  * @attrs: set to the memory transaction attributes to use
11805  * @prot: set to the permissions for the page containing phys_ptr
11806  * @page_size: set to the size of the page containing phys_ptr
11807  * @fi: set to fault info if the translation fails
11808  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11809  */
11810 bool get_phys_addr(CPUARMState *env, target_ulong address,
11811                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
11812                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
11813                    target_ulong *page_size,
11814                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11815 {
11816     if (mmu_idx == ARMMMUIdx_E10_0 ||
11817         mmu_idx == ARMMMUIdx_E10_1 ||
11818         mmu_idx == ARMMMUIdx_E10_1_PAN) {
11819         /* Call ourselves recursively to do the stage 1 and then stage 2
11820          * translations.
11821          */
11822         if (arm_feature(env, ARM_FEATURE_EL2)) {
11823             hwaddr ipa;
11824             int s2_prot;
11825             int ret;
11826             ARMCacheAttrs cacheattrs2 = {};
11827 
11828             ret = get_phys_addr(env, address, access_type,
11829                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
11830                                 prot, page_size, fi, cacheattrs);
11831 
11832             /* If S1 fails or S2 is disabled, return early.  */
11833             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
11834                 *phys_ptr = ipa;
11835                 return ret;
11836             }
11837 
11838             /* S1 is done. Now do S2 translation.  */
11839             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_Stage2,
11840                                      phys_ptr, attrs, &s2_prot,
11841                                      page_size, fi,
11842                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
11843             fi->s2addr = ipa;
11844             /* Combine the S1 and S2 perms.  */
11845             *prot &= s2_prot;
11846 
11847             /* Combine the S1 and S2 cache attributes, if needed */
11848             if (!ret && cacheattrs != NULL) {
11849                 if (env->cp15.hcr_el2 & HCR_DC) {
11850                     /*
11851                      * HCR.DC forces the first stage attributes to
11852                      *  Normal Non-Shareable,
11853                      *  Inner Write-Back Read-Allocate Write-Allocate,
11854                      *  Outer Write-Back Read-Allocate Write-Allocate.
11855                      */
11856                     cacheattrs->attrs = 0xff;
11857                     cacheattrs->shareability = 0;
11858                 }
11859                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
11860             }
11861 
11862             return ret;
11863         } else {
11864             /*
11865              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
11866              */
11867             mmu_idx = stage_1_mmu_idx(mmu_idx);
11868         }
11869     }
11870 
11871     /* The page table entries may downgrade secure to non-secure, but
11872      * cannot upgrade an non-secure translation regime's attributes
11873      * to secure.
11874      */
11875     attrs->secure = regime_is_secure(env, mmu_idx);
11876     attrs->user = regime_is_user(env, mmu_idx);
11877 
11878     /* Fast Context Switch Extension. This doesn't exist at all in v8.
11879      * In v7 and earlier it affects all stage 1 translations.
11880      */
11881     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
11882         && !arm_feature(env, ARM_FEATURE_V8)) {
11883         if (regime_el(env, mmu_idx) == 3) {
11884             address += env->cp15.fcseidr_s;
11885         } else {
11886             address += env->cp15.fcseidr_ns;
11887         }
11888     }
11889 
11890     if (arm_feature(env, ARM_FEATURE_PMSA)) {
11891         bool ret;
11892         *page_size = TARGET_PAGE_SIZE;
11893 
11894         if (arm_feature(env, ARM_FEATURE_V8)) {
11895             /* PMSAv8 */
11896             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
11897                                        phys_ptr, attrs, prot, page_size, fi);
11898         } else if (arm_feature(env, ARM_FEATURE_V7)) {
11899             /* PMSAv7 */
11900             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
11901                                        phys_ptr, prot, page_size, fi);
11902         } else {
11903             /* Pre-v7 MPU */
11904             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
11905                                        phys_ptr, prot, fi);
11906         }
11907         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
11908                       " mmu_idx %u -> %s (prot %c%c%c)\n",
11909                       access_type == MMU_DATA_LOAD ? "reading" :
11910                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
11911                       (uint32_t)address, mmu_idx,
11912                       ret ? "Miss" : "Hit",
11913                       *prot & PAGE_READ ? 'r' : '-',
11914                       *prot & PAGE_WRITE ? 'w' : '-',
11915                       *prot & PAGE_EXEC ? 'x' : '-');
11916 
11917         return ret;
11918     }
11919 
11920     /* Definitely a real MMU, not an MPU */
11921 
11922     if (regime_translation_disabled(env, mmu_idx)) {
11923         /*
11924          * MMU disabled.  S1 addresses within aa64 translation regimes are
11925          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
11926          */
11927         if (mmu_idx != ARMMMUIdx_Stage2) {
11928             int r_el = regime_el(env, mmu_idx);
11929             if (arm_el_is_aa64(env, r_el)) {
11930                 int pamax = arm_pamax(env_archcpu(env));
11931                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
11932                 int addrtop, tbi;
11933 
11934                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11935                 if (access_type == MMU_INST_FETCH) {
11936                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11937                 }
11938                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
11939                 addrtop = (tbi ? 55 : 63);
11940 
11941                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
11942                     fi->type = ARMFault_AddressSize;
11943                     fi->level = 0;
11944                     fi->stage2 = false;
11945                     return 1;
11946                 }
11947 
11948                 /*
11949                  * When TBI is disabled, we've just validated that all of the
11950                  * bits above PAMax are zero, so logically we only need to
11951                  * clear the top byte for TBI.  But it's clearer to follow
11952                  * the pseudocode set of addrdesc.paddress.
11953                  */
11954                 address = extract64(address, 0, 52);
11955             }
11956         }
11957         *phys_ptr = address;
11958         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11959         *page_size = TARGET_PAGE_SIZE;
11960         return 0;
11961     }
11962 
11963     if (regime_using_lpae_format(env, mmu_idx)) {
11964         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
11965                                   phys_ptr, attrs, prot, page_size,
11966                                   fi, cacheattrs);
11967     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
11968         return get_phys_addr_v6(env, address, access_type, mmu_idx,
11969                                 phys_ptr, attrs, prot, page_size, fi);
11970     } else {
11971         return get_phys_addr_v5(env, address, access_type, mmu_idx,
11972                                     phys_ptr, prot, page_size, fi);
11973     }
11974 }
11975 
11976 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
11977                                          MemTxAttrs *attrs)
11978 {
11979     ARMCPU *cpu = ARM_CPU(cs);
11980     CPUARMState *env = &cpu->env;
11981     hwaddr phys_addr;
11982     target_ulong page_size;
11983     int prot;
11984     bool ret;
11985     ARMMMUFaultInfo fi = {};
11986     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
11987 
11988     *attrs = (MemTxAttrs) {};
11989 
11990     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
11991                         attrs, &prot, &page_size, &fi, NULL);
11992 
11993     if (ret) {
11994         return -1;
11995     }
11996     return phys_addr;
11997 }
11998 
11999 #endif
12000 
12001 /* Note that signed overflow is undefined in C.  The following routines are
12002    careful to use unsigned types where modulo arithmetic is required.
12003    Failure to do so _will_ break on newer gcc.  */
12004 
12005 /* Signed saturating arithmetic.  */
12006 
12007 /* Perform 16-bit signed saturating addition.  */
12008 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
12009 {
12010     uint16_t res;
12011 
12012     res = a + b;
12013     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
12014         if (a & 0x8000)
12015             res = 0x8000;
12016         else
12017             res = 0x7fff;
12018     }
12019     return res;
12020 }
12021 
12022 /* Perform 8-bit signed saturating addition.  */
12023 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
12024 {
12025     uint8_t res;
12026 
12027     res = a + b;
12028     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
12029         if (a & 0x80)
12030             res = 0x80;
12031         else
12032             res = 0x7f;
12033     }
12034     return res;
12035 }
12036 
12037 /* Perform 16-bit signed saturating subtraction.  */
12038 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
12039 {
12040     uint16_t res;
12041 
12042     res = a - b;
12043     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
12044         if (a & 0x8000)
12045             res = 0x8000;
12046         else
12047             res = 0x7fff;
12048     }
12049     return res;
12050 }
12051 
12052 /* Perform 8-bit signed saturating subtraction.  */
12053 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12054 {
12055     uint8_t res;
12056 
12057     res = a - b;
12058     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12059         if (a & 0x80)
12060             res = 0x80;
12061         else
12062             res = 0x7f;
12063     }
12064     return res;
12065 }
12066 
12067 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12068 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12069 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12070 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12071 #define PFX q
12072 
12073 #include "op_addsub.h"
12074 
12075 /* Unsigned saturating arithmetic.  */
12076 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12077 {
12078     uint16_t res;
12079     res = a + b;
12080     if (res < a)
12081         res = 0xffff;
12082     return res;
12083 }
12084 
12085 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12086 {
12087     if (a > b)
12088         return a - b;
12089     else
12090         return 0;
12091 }
12092 
12093 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12094 {
12095     uint8_t res;
12096     res = a + b;
12097     if (res < a)
12098         res = 0xff;
12099     return res;
12100 }
12101 
12102 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12103 {
12104     if (a > b)
12105         return a - b;
12106     else
12107         return 0;
12108 }
12109 
12110 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12111 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12112 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12113 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12114 #define PFX uq
12115 
12116 #include "op_addsub.h"
12117 
12118 /* Signed modulo arithmetic.  */
12119 #define SARITH16(a, b, n, op) do { \
12120     int32_t sum; \
12121     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12122     RESULT(sum, n, 16); \
12123     if (sum >= 0) \
12124         ge |= 3 << (n * 2); \
12125     } while(0)
12126 
12127 #define SARITH8(a, b, n, op) do { \
12128     int32_t sum; \
12129     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
12130     RESULT(sum, n, 8); \
12131     if (sum >= 0) \
12132         ge |= 1 << n; \
12133     } while(0)
12134 
12135 
12136 #define ADD16(a, b, n) SARITH16(a, b, n, +)
12137 #define SUB16(a, b, n) SARITH16(a, b, n, -)
12138 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
12139 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
12140 #define PFX s
12141 #define ARITH_GE
12142 
12143 #include "op_addsub.h"
12144 
12145 /* Unsigned modulo arithmetic.  */
12146 #define ADD16(a, b, n) do { \
12147     uint32_t sum; \
12148     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
12149     RESULT(sum, n, 16); \
12150     if ((sum >> 16) == 1) \
12151         ge |= 3 << (n * 2); \
12152     } while(0)
12153 
12154 #define ADD8(a, b, n) do { \
12155     uint32_t sum; \
12156     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
12157     RESULT(sum, n, 8); \
12158     if ((sum >> 8) == 1) \
12159         ge |= 1 << n; \
12160     } while(0)
12161 
12162 #define SUB16(a, b, n) do { \
12163     uint32_t sum; \
12164     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
12165     RESULT(sum, n, 16); \
12166     if ((sum >> 16) == 0) \
12167         ge |= 3 << (n * 2); \
12168     } while(0)
12169 
12170 #define SUB8(a, b, n) do { \
12171     uint32_t sum; \
12172     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
12173     RESULT(sum, n, 8); \
12174     if ((sum >> 8) == 0) \
12175         ge |= 1 << n; \
12176     } while(0)
12177 
12178 #define PFX u
12179 #define ARITH_GE
12180 
12181 #include "op_addsub.h"
12182 
12183 /* Halved signed arithmetic.  */
12184 #define ADD16(a, b, n) \
12185   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
12186 #define SUB16(a, b, n) \
12187   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
12188 #define ADD8(a, b, n) \
12189   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
12190 #define SUB8(a, b, n) \
12191   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
12192 #define PFX sh
12193 
12194 #include "op_addsub.h"
12195 
12196 /* Halved unsigned arithmetic.  */
12197 #define ADD16(a, b, n) \
12198   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12199 #define SUB16(a, b, n) \
12200   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12201 #define ADD8(a, b, n) \
12202   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12203 #define SUB8(a, b, n) \
12204   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12205 #define PFX uh
12206 
12207 #include "op_addsub.h"
12208 
12209 static inline uint8_t do_usad(uint8_t a, uint8_t b)
12210 {
12211     if (a > b)
12212         return a - b;
12213     else
12214         return b - a;
12215 }
12216 
12217 /* Unsigned sum of absolute byte differences.  */
12218 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
12219 {
12220     uint32_t sum;
12221     sum = do_usad(a, b);
12222     sum += do_usad(a >> 8, b >> 8);
12223     sum += do_usad(a >> 16, b >>16);
12224     sum += do_usad(a >> 24, b >> 24);
12225     return sum;
12226 }
12227 
12228 /* For ARMv6 SEL instruction.  */
12229 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
12230 {
12231     uint32_t mask;
12232 
12233     mask = 0;
12234     if (flags & 1)
12235         mask |= 0xff;
12236     if (flags & 2)
12237         mask |= 0xff00;
12238     if (flags & 4)
12239         mask |= 0xff0000;
12240     if (flags & 8)
12241         mask |= 0xff000000;
12242     return (a & mask) | (b & ~mask);
12243 }
12244 
12245 /* CRC helpers.
12246  * The upper bytes of val (above the number specified by 'bytes') must have
12247  * been zeroed out by the caller.
12248  */
12249 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12250 {
12251     uint8_t buf[4];
12252 
12253     stl_le_p(buf, val);
12254 
12255     /* zlib crc32 converts the accumulator and output to one's complement.  */
12256     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12257 }
12258 
12259 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12260 {
12261     uint8_t buf[4];
12262 
12263     stl_le_p(buf, val);
12264 
12265     /* Linux crc32c converts the output to one's complement.  */
12266     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12267 }
12268 
12269 /* Return the exception level to which FP-disabled exceptions should
12270  * be taken, or 0 if FP is enabled.
12271  */
12272 int fp_exception_el(CPUARMState *env, int cur_el)
12273 {
12274 #ifndef CONFIG_USER_ONLY
12275     /* CPACR and the CPTR registers don't exist before v6, so FP is
12276      * always accessible
12277      */
12278     if (!arm_feature(env, ARM_FEATURE_V6)) {
12279         return 0;
12280     }
12281 
12282     if (arm_feature(env, ARM_FEATURE_M)) {
12283         /* CPACR can cause a NOCP UsageFault taken to current security state */
12284         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
12285             return 1;
12286         }
12287 
12288         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
12289             if (!extract32(env->v7m.nsacr, 10, 1)) {
12290                 /* FP insns cause a NOCP UsageFault taken to Secure */
12291                 return 3;
12292             }
12293         }
12294 
12295         return 0;
12296     }
12297 
12298     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12299      * 0, 2 : trap EL0 and EL1/PL1 accesses
12300      * 1    : trap only EL0 accesses
12301      * 3    : trap no accesses
12302      * This register is ignored if E2H+TGE are both set.
12303      */
12304     if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12305         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12306 
12307         switch (fpen) {
12308         case 0:
12309         case 2:
12310             if (cur_el == 0 || cur_el == 1) {
12311                 /* Trap to PL1, which might be EL1 or EL3 */
12312                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12313                     return 3;
12314                 }
12315                 return 1;
12316             }
12317             if (cur_el == 3 && !is_a64(env)) {
12318                 /* Secure PL1 running at EL3 */
12319                 return 3;
12320             }
12321             break;
12322         case 1:
12323             if (cur_el == 0) {
12324                 return 1;
12325             }
12326             break;
12327         case 3:
12328             break;
12329         }
12330     }
12331 
12332     /*
12333      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
12334      * to control non-secure access to the FPU. It doesn't have any
12335      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
12336      */
12337     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
12338          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
12339         if (!extract32(env->cp15.nsacr, 10, 1)) {
12340             /* FP insns act as UNDEF */
12341             return cur_el == 2 ? 2 : 1;
12342         }
12343     }
12344 
12345     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12346      * check because zero bits in the registers mean "don't trap".
12347      */
12348 
12349     /* CPTR_EL2 : present in v7VE or v8 */
12350     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12351         && !arm_is_secure_below_el3(env)) {
12352         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12353         return 2;
12354     }
12355 
12356     /* CPTR_EL3 : present in v8 */
12357     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12358         /* Trap all FP ops to EL3 */
12359         return 3;
12360     }
12361 #endif
12362     return 0;
12363 }
12364 
12365 /* Return the exception level we're running at if this is our mmu_idx */
12366 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
12367 {
12368     if (mmu_idx & ARM_MMU_IDX_M) {
12369         return mmu_idx & ARM_MMU_IDX_M_PRIV;
12370     }
12371 
12372     switch (mmu_idx) {
12373     case ARMMMUIdx_E10_0:
12374     case ARMMMUIdx_E20_0:
12375     case ARMMMUIdx_SE10_0:
12376         return 0;
12377     case ARMMMUIdx_E10_1:
12378     case ARMMMUIdx_E10_1_PAN:
12379     case ARMMMUIdx_SE10_1:
12380     case ARMMMUIdx_SE10_1_PAN:
12381         return 1;
12382     case ARMMMUIdx_E2:
12383     case ARMMMUIdx_E20_2:
12384     case ARMMMUIdx_E20_2_PAN:
12385         return 2;
12386     case ARMMMUIdx_SE3:
12387         return 3;
12388     default:
12389         g_assert_not_reached();
12390     }
12391 }
12392 
12393 #ifndef CONFIG_TCG
12394 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
12395 {
12396     g_assert_not_reached();
12397 }
12398 #endif
12399 
12400 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
12401 {
12402     if (arm_feature(env, ARM_FEATURE_M)) {
12403         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
12404     }
12405 
12406     /* See ARM pseudo-function ELIsInHost.  */
12407     switch (el) {
12408     case 0:
12409         if (arm_is_secure_below_el3(env)) {
12410             return ARMMMUIdx_SE10_0;
12411         }
12412         if ((env->cp15.hcr_el2 & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)
12413             && arm_el_is_aa64(env, 2)) {
12414             return ARMMMUIdx_E20_0;
12415         }
12416         return ARMMMUIdx_E10_0;
12417     case 1:
12418         if (arm_is_secure_below_el3(env)) {
12419             if (env->pstate & PSTATE_PAN) {
12420                 return ARMMMUIdx_SE10_1_PAN;
12421             }
12422             return ARMMMUIdx_SE10_1;
12423         }
12424         if (env->pstate & PSTATE_PAN) {
12425             return ARMMMUIdx_E10_1_PAN;
12426         }
12427         return ARMMMUIdx_E10_1;
12428     case 2:
12429         /* TODO: ARMv8.4-SecEL2 */
12430         /* Note that TGE does not apply at EL2.  */
12431         if ((env->cp15.hcr_el2 & HCR_E2H) && arm_el_is_aa64(env, 2)) {
12432             if (env->pstate & PSTATE_PAN) {
12433                 return ARMMMUIdx_E20_2_PAN;
12434             }
12435             return ARMMMUIdx_E20_2;
12436         }
12437         return ARMMMUIdx_E2;
12438     case 3:
12439         return ARMMMUIdx_SE3;
12440     default:
12441         g_assert_not_reached();
12442     }
12443 }
12444 
12445 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
12446 {
12447     return arm_mmu_idx_el(env, arm_current_el(env));
12448 }
12449 
12450 #ifndef CONFIG_USER_ONLY
12451 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
12452 {
12453     return stage_1_mmu_idx(arm_mmu_idx(env));
12454 }
12455 #endif
12456 
12457 static uint32_t rebuild_hflags_common(CPUARMState *env, int fp_el,
12458                                       ARMMMUIdx mmu_idx, uint32_t flags)
12459 {
12460     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
12461     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX,
12462                        arm_to_core_mmu_idx(mmu_idx));
12463 
12464     if (arm_singlestep_active(env)) {
12465         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
12466     }
12467     return flags;
12468 }
12469 
12470 static uint32_t rebuild_hflags_common_32(CPUARMState *env, int fp_el,
12471                                          ARMMMUIdx mmu_idx, uint32_t flags)
12472 {
12473     bool sctlr_b = arm_sctlr_b(env);
12474 
12475     if (sctlr_b) {
12476         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, 1);
12477     }
12478     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
12479         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
12480     }
12481     flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
12482 
12483     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
12484 }
12485 
12486 static uint32_t rebuild_hflags_m32(CPUARMState *env, int fp_el,
12487                                    ARMMMUIdx mmu_idx)
12488 {
12489     uint32_t flags = 0;
12490 
12491     if (arm_v7m_is_handler_mode(env)) {
12492         flags = FIELD_DP32(flags, TBFLAG_M32, HANDLER, 1);
12493     }
12494 
12495     /*
12496      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
12497      * is suppressing them because the requested execution priority
12498      * is less than 0.
12499      */
12500     if (arm_feature(env, ARM_FEATURE_V8) &&
12501         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
12502           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
12503         flags = FIELD_DP32(flags, TBFLAG_M32, STACKCHECK, 1);
12504     }
12505 
12506     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
12507 }
12508 
12509 static uint32_t rebuild_hflags_aprofile(CPUARMState *env)
12510 {
12511     int flags = 0;
12512 
12513     flags = FIELD_DP32(flags, TBFLAG_ANY, DEBUG_TARGET_EL,
12514                        arm_debug_target_el(env));
12515     return flags;
12516 }
12517 
12518 static uint32_t rebuild_hflags_a32(CPUARMState *env, int fp_el,
12519                                    ARMMMUIdx mmu_idx)
12520 {
12521     uint32_t flags = rebuild_hflags_aprofile(env);
12522 
12523     if (arm_el_is_aa64(env, 1)) {
12524         flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
12525     }
12526 
12527     if (arm_current_el(env) < 2 && env->cp15.hstr_el2 &&
12528         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12529         flags = FIELD_DP32(flags, TBFLAG_A32, HSTR_ACTIVE, 1);
12530     }
12531 
12532     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
12533 }
12534 
12535 static uint32_t rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
12536                                    ARMMMUIdx mmu_idx)
12537 {
12538     uint32_t flags = rebuild_hflags_aprofile(env);
12539     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
12540     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
12541     uint64_t sctlr;
12542     int tbii, tbid;
12543 
12544     flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
12545 
12546     /* Get control bits for tagged addresses.  */
12547     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
12548     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
12549 
12550     flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
12551     flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
12552 
12553     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
12554         int sve_el = sve_exception_el(env, el);
12555         uint32_t zcr_len;
12556 
12557         /*
12558          * If SVE is disabled, but FP is enabled,
12559          * then the effective len is 0.
12560          */
12561         if (sve_el != 0 && fp_el == 0) {
12562             zcr_len = 0;
12563         } else {
12564             zcr_len = sve_zcr_len_for_el(env, el);
12565         }
12566         flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
12567         flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
12568     }
12569 
12570     sctlr = regime_sctlr(env, stage1);
12571 
12572     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
12573         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
12574     }
12575 
12576     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
12577         /*
12578          * In order to save space in flags, we record only whether
12579          * pauth is "inactive", meaning all insns are implemented as
12580          * a nop, or "active" when some action must be performed.
12581          * The decision of which action to take is left to a helper.
12582          */
12583         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
12584             flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
12585         }
12586     }
12587 
12588     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
12589         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
12590         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
12591             flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
12592         }
12593     }
12594 
12595     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
12596     if (!(env->pstate & PSTATE_UAO)) {
12597         switch (mmu_idx) {
12598         case ARMMMUIdx_E10_1:
12599         case ARMMMUIdx_E10_1_PAN:
12600         case ARMMMUIdx_SE10_1:
12601         case ARMMMUIdx_SE10_1_PAN:
12602             /* TODO: ARMv8.3-NV */
12603             flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
12604             break;
12605         case ARMMMUIdx_E20_2:
12606         case ARMMMUIdx_E20_2_PAN:
12607             /* TODO: ARMv8.4-SecEL2 */
12608             /*
12609              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
12610              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
12611              */
12612             if (env->cp15.hcr_el2 & HCR_TGE) {
12613                 flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
12614             }
12615             break;
12616         default:
12617             break;
12618         }
12619     }
12620 
12621     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
12622 }
12623 
12624 static uint32_t rebuild_hflags_internal(CPUARMState *env)
12625 {
12626     int el = arm_current_el(env);
12627     int fp_el = fp_exception_el(env, el);
12628     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12629 
12630     if (is_a64(env)) {
12631         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
12632     } else if (arm_feature(env, ARM_FEATURE_M)) {
12633         return rebuild_hflags_m32(env, fp_el, mmu_idx);
12634     } else {
12635         return rebuild_hflags_a32(env, fp_el, mmu_idx);
12636     }
12637 }
12638 
12639 void arm_rebuild_hflags(CPUARMState *env)
12640 {
12641     env->hflags = rebuild_hflags_internal(env);
12642 }
12643 
12644 /*
12645  * If we have triggered a EL state change we can't rely on the
12646  * translator having passed it to us, we need to recompute.
12647  */
12648 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
12649 {
12650     int el = arm_current_el(env);
12651     int fp_el = fp_exception_el(env, el);
12652     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12653     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
12654 }
12655 
12656 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
12657 {
12658     int fp_el = fp_exception_el(env, el);
12659     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12660 
12661     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
12662 }
12663 
12664 /*
12665  * If we have triggered a EL state change we can't rely on the
12666  * translator having passed it to us, we need to recompute.
12667  */
12668 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
12669 {
12670     int el = arm_current_el(env);
12671     int fp_el = fp_exception_el(env, el);
12672     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12673     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
12674 }
12675 
12676 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
12677 {
12678     int fp_el = fp_exception_el(env, el);
12679     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12680 
12681     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
12682 }
12683 
12684 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
12685 {
12686     int fp_el = fp_exception_el(env, el);
12687     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12688 
12689     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
12690 }
12691 
12692 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
12693 {
12694 #ifdef CONFIG_DEBUG_TCG
12695     uint32_t env_flags_current = env->hflags;
12696     uint32_t env_flags_rebuilt = rebuild_hflags_internal(env);
12697 
12698     if (unlikely(env_flags_current != env_flags_rebuilt)) {
12699         fprintf(stderr, "TCG hflags mismatch (current:0x%08x rebuilt:0x%08x)\n",
12700                 env_flags_current, env_flags_rebuilt);
12701         abort();
12702     }
12703 #endif
12704 }
12705 
12706 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
12707                           target_ulong *cs_base, uint32_t *pflags)
12708 {
12709     uint32_t flags = env->hflags;
12710     uint32_t pstate_for_ss;
12711 
12712     *cs_base = 0;
12713     assert_hflags_rebuild_correctly(env);
12714 
12715     if (FIELD_EX32(flags, TBFLAG_ANY, AARCH64_STATE)) {
12716         *pc = env->pc;
12717         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
12718             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
12719         }
12720         pstate_for_ss = env->pstate;
12721     } else {
12722         *pc = env->regs[15];
12723 
12724         if (arm_feature(env, ARM_FEATURE_M)) {
12725             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
12726                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
12727                 != env->v7m.secure) {
12728                 flags = FIELD_DP32(flags, TBFLAG_M32, FPCCR_S_WRONG, 1);
12729             }
12730 
12731             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
12732                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
12733                  (env->v7m.secure &&
12734                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
12735                 /*
12736                  * ASPEN is set, but FPCA/SFPA indicate that there is no
12737                  * active FP context; we must create a new FP context before
12738                  * executing any FP insn.
12739                  */
12740                 flags = FIELD_DP32(flags, TBFLAG_M32, NEW_FP_CTXT_NEEDED, 1);
12741             }
12742 
12743             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
12744             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
12745                 flags = FIELD_DP32(flags, TBFLAG_M32, LSPACT, 1);
12746             }
12747         } else {
12748             /*
12749              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
12750              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
12751              */
12752             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
12753                 flags = FIELD_DP32(flags, TBFLAG_A32,
12754                                    XSCALE_CPAR, env->cp15.c15_cpar);
12755             } else {
12756                 flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN,
12757                                    env->vfp.vec_len);
12758                 flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE,
12759                                    env->vfp.vec_stride);
12760             }
12761             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
12762                 flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
12763             }
12764         }
12765 
12766         flags = FIELD_DP32(flags, TBFLAG_AM32, THUMB, env->thumb);
12767         flags = FIELD_DP32(flags, TBFLAG_AM32, CONDEXEC, env->condexec_bits);
12768         pstate_for_ss = env->uncached_cpsr;
12769     }
12770 
12771     /*
12772      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
12773      * states defined in the ARM ARM for software singlestep:
12774      *  SS_ACTIVE   PSTATE.SS   State
12775      *     0            x       Inactive (the TB flag for SS is always 0)
12776      *     1            0       Active-pending
12777      *     1            1       Active-not-pending
12778      * SS_ACTIVE is set in hflags; PSTATE_SS is computed every TB.
12779      */
12780     if (FIELD_EX32(flags, TBFLAG_ANY, SS_ACTIVE) &&
12781         (pstate_for_ss & PSTATE_SS)) {
12782         flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
12783     }
12784 
12785     *pflags = flags;
12786 }
12787 
12788 #ifdef TARGET_AARCH64
12789 /*
12790  * The manual says that when SVE is enabled and VQ is widened the
12791  * implementation is allowed to zero the previously inaccessible
12792  * portion of the registers.  The corollary to that is that when
12793  * SVE is enabled and VQ is narrowed we are also allowed to zero
12794  * the now inaccessible portion of the registers.
12795  *
12796  * The intent of this is that no predicate bit beyond VQ is ever set.
12797  * Which means that some operations on predicate registers themselves
12798  * may operate on full uint64_t or even unrolled across the maximum
12799  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
12800  * may well be cheaper than conditionals to restrict the operation
12801  * to the relevant portion of a uint16_t[16].
12802  */
12803 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
12804 {
12805     int i, j;
12806     uint64_t pmask;
12807 
12808     assert(vq >= 1 && vq <= ARM_MAX_VQ);
12809     assert(vq <= env_archcpu(env)->sve_max_vq);
12810 
12811     /* Zap the high bits of the zregs.  */
12812     for (i = 0; i < 32; i++) {
12813         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
12814     }
12815 
12816     /* Zap the high bits of the pregs and ffr.  */
12817     pmask = 0;
12818     if (vq & 3) {
12819         pmask = ~(-1ULL << (16 * (vq & 3)));
12820     }
12821     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
12822         for (i = 0; i < 17; ++i) {
12823             env->vfp.pregs[i].p[j] &= pmask;
12824         }
12825         pmask = 0;
12826     }
12827 }
12828 
12829 /*
12830  * Notice a change in SVE vector size when changing EL.
12831  */
12832 void aarch64_sve_change_el(CPUARMState *env, int old_el,
12833                            int new_el, bool el0_a64)
12834 {
12835     ARMCPU *cpu = env_archcpu(env);
12836     int old_len, new_len;
12837     bool old_a64, new_a64;
12838 
12839     /* Nothing to do if no SVE.  */
12840     if (!cpu_isar_feature(aa64_sve, cpu)) {
12841         return;
12842     }
12843 
12844     /* Nothing to do if FP is disabled in either EL.  */
12845     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
12846         return;
12847     }
12848 
12849     /*
12850      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
12851      * at ELx, or not available because the EL is in AArch32 state, then
12852      * for all purposes other than a direct read, the ZCR_ELx.LEN field
12853      * has an effective value of 0".
12854      *
12855      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
12856      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
12857      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
12858      * we already have the correct register contents when encountering the
12859      * vq0->vq0 transition between EL0->EL1.
12860      */
12861     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
12862     old_len = (old_a64 && !sve_exception_el(env, old_el)
12863                ? sve_zcr_len_for_el(env, old_el) : 0);
12864     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
12865     new_len = (new_a64 && !sve_exception_el(env, new_el)
12866                ? sve_zcr_len_for_el(env, new_el) : 0);
12867 
12868     /* When changing vector length, clear inaccessible state.  */
12869     if (new_len < old_len) {
12870         aarch64_sve_narrow_vq(env, new_len + 1);
12871     }
12872 }
12873 #endif
12874