xref: /openbmc/qemu/target/arm/helper.c (revision 40bd0502)
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 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3446                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3447 {
3448     hwaddr phys_addr;
3449     target_ulong page_size;
3450     int prot;
3451     bool ret;
3452     uint64_t par64;
3453     bool format64 = false;
3454     MemTxAttrs attrs = {};
3455     ARMMMUFaultInfo fi = {};
3456     ARMCacheAttrs cacheattrs = {};
3457 
3458     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3459                         &prot, &page_size, &fi, &cacheattrs);
3460 
3461     if (ret) {
3462         /*
3463          * Some kinds of translation fault must cause exceptions rather
3464          * than being reported in the PAR.
3465          */
3466         int current_el = arm_current_el(env);
3467         int target_el;
3468         uint32_t syn, fsr, fsc;
3469         bool take_exc = false;
3470 
3471         if (fi.s1ptw && current_el == 1 && !arm_is_secure(env)
3472             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3473             /*
3474              * Synchronous stage 2 fault on an access made as part of the
3475              * translation table walk for AT S1E0* or AT S1E1* insn
3476              * executed from NS EL1. If this is a synchronous external abort
3477              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3478              * to EL3. Otherwise the fault is taken as an exception to EL2,
3479              * and HPFAR_EL2 holds the faulting IPA.
3480              */
3481             if (fi.type == ARMFault_SyncExternalOnWalk &&
3482                 (env->cp15.scr_el3 & SCR_EA)) {
3483                 target_el = 3;
3484             } else {
3485                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3486                 target_el = 2;
3487             }
3488             take_exc = true;
3489         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3490             /*
3491              * Synchronous external aborts during a translation table walk
3492              * are taken as Data Abort exceptions.
3493              */
3494             if (fi.stage2) {
3495                 if (current_el == 3) {
3496                     target_el = 3;
3497                 } else {
3498                     target_el = 2;
3499                 }
3500             } else {
3501                 target_el = exception_target_el(env);
3502             }
3503             take_exc = true;
3504         }
3505 
3506         if (take_exc) {
3507             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3508             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3509                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3510                 fsr = arm_fi_to_lfsc(&fi);
3511                 fsc = extract32(fsr, 0, 6);
3512             } else {
3513                 fsr = arm_fi_to_sfsc(&fi);
3514                 fsc = 0x3f;
3515             }
3516             /*
3517              * Report exception with ESR indicating a fault due to a
3518              * translation table walk for a cache maintenance instruction.
3519              */
3520             syn = syn_data_abort_no_iss(current_el == target_el,
3521                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3522             env->exception.vaddress = value;
3523             env->exception.fsr = fsr;
3524             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3525         }
3526     }
3527 
3528     if (is_a64(env)) {
3529         format64 = true;
3530     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3531         /*
3532          * ATS1Cxx:
3533          * * TTBCR.EAE determines whether the result is returned using the
3534          *   32-bit or the 64-bit PAR format
3535          * * Instructions executed in Hyp mode always use the 64bit format
3536          *
3537          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3538          * * The Non-secure TTBCR.EAE bit is set to 1
3539          * * The implementation includes EL2, and the value of HCR.VM is 1
3540          *
3541          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3542          *
3543          * ATS1Hx always uses the 64bit format.
3544          */
3545         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3546 
3547         if (arm_feature(env, ARM_FEATURE_EL2)) {
3548             if (mmu_idx == ARMMMUIdx_E10_0 ||
3549                 mmu_idx == ARMMMUIdx_E10_1 ||
3550                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3551                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3552             } else {
3553                 format64 |= arm_current_el(env) == 2;
3554             }
3555         }
3556     }
3557 
3558     if (format64) {
3559         /* Create a 64-bit PAR */
3560         par64 = (1 << 11); /* LPAE bit always set */
3561         if (!ret) {
3562             par64 |= phys_addr & ~0xfffULL;
3563             if (!attrs.secure) {
3564                 par64 |= (1 << 9); /* NS */
3565             }
3566             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3567             par64 |= cacheattrs.shareability << 7; /* SH */
3568         } else {
3569             uint32_t fsr = arm_fi_to_lfsc(&fi);
3570 
3571             par64 |= 1; /* F */
3572             par64 |= (fsr & 0x3f) << 1; /* FS */
3573             if (fi.stage2) {
3574                 par64 |= (1 << 9); /* S */
3575             }
3576             if (fi.s1ptw) {
3577                 par64 |= (1 << 8); /* PTW */
3578             }
3579         }
3580     } else {
3581         /* fsr is a DFSR/IFSR value for the short descriptor
3582          * translation table format (with WnR always clear).
3583          * Convert it to a 32-bit PAR.
3584          */
3585         if (!ret) {
3586             /* We do not set any attribute bits in the PAR */
3587             if (page_size == (1 << 24)
3588                 && arm_feature(env, ARM_FEATURE_V7)) {
3589                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3590             } else {
3591                 par64 = phys_addr & 0xfffff000;
3592             }
3593             if (!attrs.secure) {
3594                 par64 |= (1 << 9); /* NS */
3595             }
3596         } else {
3597             uint32_t fsr = arm_fi_to_sfsc(&fi);
3598 
3599             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3600                     ((fsr & 0xf) << 1) | 1;
3601         }
3602     }
3603     return par64;
3604 }
3605 
3606 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3607 {
3608     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3609     uint64_t par64;
3610     ARMMMUIdx mmu_idx;
3611     int el = arm_current_el(env);
3612     bool secure = arm_is_secure_below_el3(env);
3613 
3614     switch (ri->opc2 & 6) {
3615     case 0:
3616         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3617         switch (el) {
3618         case 3:
3619             mmu_idx = ARMMMUIdx_SE3;
3620             break;
3621         case 2:
3622             g_assert(!secure);  /* TODO: ARMv8.4-SecEL2 */
3623             /* fall through */
3624         case 1:
3625             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3626                 mmu_idx = (secure ? ARMMMUIdx_SE10_1_PAN
3627                            : ARMMMUIdx_Stage1_E1_PAN);
3628             } else {
3629                 mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_Stage1_E1;
3630             }
3631             break;
3632         default:
3633             g_assert_not_reached();
3634         }
3635         break;
3636     case 2:
3637         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3638         switch (el) {
3639         case 3:
3640             mmu_idx = ARMMMUIdx_SE10_0;
3641             break;
3642         case 2:
3643             mmu_idx = ARMMMUIdx_Stage1_E0;
3644             break;
3645         case 1:
3646             mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_Stage1_E0;
3647             break;
3648         default:
3649             g_assert_not_reached();
3650         }
3651         break;
3652     case 4:
3653         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3654         mmu_idx = ARMMMUIdx_E10_1;
3655         break;
3656     case 6:
3657         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3658         mmu_idx = ARMMMUIdx_E10_0;
3659         break;
3660     default:
3661         g_assert_not_reached();
3662     }
3663 
3664     par64 = do_ats_write(env, value, access_type, mmu_idx);
3665 
3666     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3667 }
3668 
3669 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3670                         uint64_t value)
3671 {
3672     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3673     uint64_t par64;
3674 
3675     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3676 
3677     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3678 }
3679 
3680 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3681                                      bool isread)
3682 {
3683     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
3684         return CP_ACCESS_TRAP;
3685     }
3686     return CP_ACCESS_OK;
3687 }
3688 
3689 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3690                         uint64_t value)
3691 {
3692     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3693     ARMMMUIdx mmu_idx;
3694     int secure = arm_is_secure_below_el3(env);
3695 
3696     switch (ri->opc2 & 6) {
3697     case 0:
3698         switch (ri->opc1) {
3699         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3700             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3701                 mmu_idx = (secure ? ARMMMUIdx_SE10_1_PAN
3702                            : ARMMMUIdx_Stage1_E1_PAN);
3703             } else {
3704                 mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_Stage1_E1;
3705             }
3706             break;
3707         case 4: /* AT S1E2R, AT S1E2W */
3708             mmu_idx = ARMMMUIdx_E2;
3709             break;
3710         case 6: /* AT S1E3R, AT S1E3W */
3711             mmu_idx = ARMMMUIdx_SE3;
3712             break;
3713         default:
3714             g_assert_not_reached();
3715         }
3716         break;
3717     case 2: /* AT S1E0R, AT S1E0W */
3718         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_Stage1_E0;
3719         break;
3720     case 4: /* AT S12E1R, AT S12E1W */
3721         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3722         break;
3723     case 6: /* AT S12E0R, AT S12E0W */
3724         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3725         break;
3726     default:
3727         g_assert_not_reached();
3728     }
3729 
3730     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3731 }
3732 #endif
3733 
3734 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3735     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3736       .access = PL1_RW, .resetvalue = 0,
3737       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3738                              offsetoflow32(CPUARMState, cp15.par_ns) },
3739       .writefn = par_write },
3740 #ifndef CONFIG_USER_ONLY
3741     /* This underdecoding is safe because the reginfo is NO_RAW. */
3742     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3743       .access = PL1_W, .accessfn = ats_access,
3744       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3745 #endif
3746     REGINFO_SENTINEL
3747 };
3748 
3749 /* Return basic MPU access permission bits.  */
3750 static uint32_t simple_mpu_ap_bits(uint32_t val)
3751 {
3752     uint32_t ret;
3753     uint32_t mask;
3754     int i;
3755     ret = 0;
3756     mask = 3;
3757     for (i = 0; i < 16; i += 2) {
3758         ret |= (val >> i) & mask;
3759         mask <<= 2;
3760     }
3761     return ret;
3762 }
3763 
3764 /* Pad basic MPU access permission bits to extended format.  */
3765 static uint32_t extended_mpu_ap_bits(uint32_t val)
3766 {
3767     uint32_t ret;
3768     uint32_t mask;
3769     int i;
3770     ret = 0;
3771     mask = 3;
3772     for (i = 0; i < 16; i += 2) {
3773         ret |= (val & mask) << i;
3774         mask <<= 2;
3775     }
3776     return ret;
3777 }
3778 
3779 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3780                                  uint64_t value)
3781 {
3782     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3783 }
3784 
3785 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3786 {
3787     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3788 }
3789 
3790 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3791                                  uint64_t value)
3792 {
3793     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3794 }
3795 
3796 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3797 {
3798     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3799 }
3800 
3801 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3802 {
3803     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3804 
3805     if (!u32p) {
3806         return 0;
3807     }
3808 
3809     u32p += env->pmsav7.rnr[M_REG_NS];
3810     return *u32p;
3811 }
3812 
3813 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3814                          uint64_t value)
3815 {
3816     ARMCPU *cpu = env_archcpu(env);
3817     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3818 
3819     if (!u32p) {
3820         return;
3821     }
3822 
3823     u32p += env->pmsav7.rnr[M_REG_NS];
3824     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3825     *u32p = value;
3826 }
3827 
3828 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3829                               uint64_t value)
3830 {
3831     ARMCPU *cpu = env_archcpu(env);
3832     uint32_t nrgs = cpu->pmsav7_dregion;
3833 
3834     if (value >= nrgs) {
3835         qemu_log_mask(LOG_GUEST_ERROR,
3836                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3837                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3838         return;
3839     }
3840 
3841     raw_write(env, ri, value);
3842 }
3843 
3844 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3845     /* Reset for all these registers is handled in arm_cpu_reset(),
3846      * because the PMSAv7 is also used by M-profile CPUs, which do
3847      * not register cpregs but still need the state to be reset.
3848      */
3849     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3850       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3851       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3852       .readfn = pmsav7_read, .writefn = pmsav7_write,
3853       .resetfn = arm_cp_reset_ignore },
3854     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3855       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3856       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3857       .readfn = pmsav7_read, .writefn = pmsav7_write,
3858       .resetfn = arm_cp_reset_ignore },
3859     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3860       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3861       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3862       .readfn = pmsav7_read, .writefn = pmsav7_write,
3863       .resetfn = arm_cp_reset_ignore },
3864     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3865       .access = PL1_RW,
3866       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3867       .writefn = pmsav7_rgnr_write,
3868       .resetfn = arm_cp_reset_ignore },
3869     REGINFO_SENTINEL
3870 };
3871 
3872 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3873     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3874       .access = PL1_RW, .type = ARM_CP_ALIAS,
3875       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3876       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3877     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3878       .access = PL1_RW, .type = ARM_CP_ALIAS,
3879       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3880       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3881     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3882       .access = PL1_RW,
3883       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3884       .resetvalue = 0, },
3885     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3886       .access = PL1_RW,
3887       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3888       .resetvalue = 0, },
3889     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3890       .access = PL1_RW,
3891       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3892     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3893       .access = PL1_RW,
3894       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3895     /* Protection region base and size registers */
3896     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3897       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3898       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3899     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3900       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3901       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3902     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3903       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3904       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3905     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3906       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3907       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3908     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3909       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3910       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3911     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3912       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3913       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3914     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3915       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3916       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3917     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3918       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3919       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3920     REGINFO_SENTINEL
3921 };
3922 
3923 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3924                                  uint64_t value)
3925 {
3926     TCR *tcr = raw_ptr(env, ri);
3927     int maskshift = extract32(value, 0, 3);
3928 
3929     if (!arm_feature(env, ARM_FEATURE_V8)) {
3930         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3931             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3932              * using Long-desciptor translation table format */
3933             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3934         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3935             /* In an implementation that includes the Security Extensions
3936              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3937              * Short-descriptor translation table format.
3938              */
3939             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3940         } else {
3941             value &= TTBCR_N;
3942         }
3943     }
3944 
3945     /* Update the masks corresponding to the TCR bank being written
3946      * Note that we always calculate mask and base_mask, but
3947      * they are only used for short-descriptor tables (ie if EAE is 0);
3948      * for long-descriptor tables the TCR fields are used differently
3949      * and the mask and base_mask values are meaningless.
3950      */
3951     tcr->raw_tcr = value;
3952     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3953     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3954 }
3955 
3956 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3957                              uint64_t value)
3958 {
3959     ARMCPU *cpu = env_archcpu(env);
3960     TCR *tcr = raw_ptr(env, ri);
3961 
3962     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3963         /* With LPAE the TTBCR could result in a change of ASID
3964          * via the TTBCR.A1 bit, so do a TLB flush.
3965          */
3966         tlb_flush(CPU(cpu));
3967     }
3968     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3969     value = deposit64(tcr->raw_tcr, 0, 32, value);
3970     vmsa_ttbcr_raw_write(env, ri, value);
3971 }
3972 
3973 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3974 {
3975     TCR *tcr = raw_ptr(env, ri);
3976 
3977     /* Reset both the TCR as well as the masks corresponding to the bank of
3978      * the TCR being reset.
3979      */
3980     tcr->raw_tcr = 0;
3981     tcr->mask = 0;
3982     tcr->base_mask = 0xffffc000u;
3983 }
3984 
3985 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3986                                uint64_t value)
3987 {
3988     ARMCPU *cpu = env_archcpu(env);
3989     TCR *tcr = raw_ptr(env, ri);
3990 
3991     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3992     tlb_flush(CPU(cpu));
3993     tcr->raw_tcr = value;
3994 }
3995 
3996 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3997                             uint64_t value)
3998 {
3999     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
4000     if (cpreg_field_is_64bit(ri) &&
4001         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
4002         ARMCPU *cpu = env_archcpu(env);
4003         tlb_flush(CPU(cpu));
4004     }
4005     raw_write(env, ri, value);
4006 }
4007 
4008 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4009                                     uint64_t value)
4010 {
4011     /*
4012      * If we are running with E2&0 regime, then an ASID is active.
4013      * Flush if that might be changing.  Note we're not checking
4014      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
4015      * holds the active ASID, only checking the field that might.
4016      */
4017     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
4018         (arm_hcr_el2_eff(env) & HCR_E2H)) {
4019         tlb_flush_by_mmuidx(env_cpu(env),
4020                             ARMMMUIdxBit_E20_2 |
4021                             ARMMMUIdxBit_E20_2_PAN |
4022                             ARMMMUIdxBit_E20_0);
4023     }
4024     raw_write(env, ri, value);
4025 }
4026 
4027 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4028                         uint64_t value)
4029 {
4030     ARMCPU *cpu = env_archcpu(env);
4031     CPUState *cs = CPU(cpu);
4032 
4033     /*
4034      * A change in VMID to the stage2 page table (Stage2) invalidates
4035      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
4036      */
4037     if (raw_read(env, ri) != value) {
4038         tlb_flush_by_mmuidx(cs,
4039                             ARMMMUIdxBit_E10_1 |
4040                             ARMMMUIdxBit_E10_1_PAN |
4041                             ARMMMUIdxBit_E10_0 |
4042                             ARMMMUIdxBit_Stage2);
4043         raw_write(env, ri, value);
4044     }
4045 }
4046 
4047 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
4048     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
4049       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
4050       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
4051                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
4052     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
4053       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4054       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
4055                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
4056     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
4057       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4058       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
4059                              offsetof(CPUARMState, cp15.dfar_ns) } },
4060     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
4061       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
4062       .access = PL1_RW, .accessfn = access_tvm_trvm,
4063       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
4064       .resetvalue = 0, },
4065     REGINFO_SENTINEL
4066 };
4067 
4068 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
4069     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
4070       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
4071       .access = PL1_RW, .accessfn = access_tvm_trvm,
4072       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
4073     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
4074       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
4075       .access = PL1_RW, .accessfn = access_tvm_trvm,
4076       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4077       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4078                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
4079     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
4080       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
4081       .access = PL1_RW, .accessfn = access_tvm_trvm,
4082       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4083       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4084                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
4085     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
4086       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4087       .access = PL1_RW, .accessfn = access_tvm_trvm,
4088       .writefn = vmsa_tcr_el12_write,
4089       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
4090       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
4091     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4092       .access = PL1_RW, .accessfn = access_tvm_trvm,
4093       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
4094       .raw_writefn = vmsa_ttbcr_raw_write,
4095       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
4096                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
4097     REGINFO_SENTINEL
4098 };
4099 
4100 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
4101  * qemu tlbs nor adjusting cached masks.
4102  */
4103 static const ARMCPRegInfo ttbcr2_reginfo = {
4104     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
4105     .access = PL1_RW, .accessfn = access_tvm_trvm,
4106     .type = ARM_CP_ALIAS,
4107     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
4108                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
4109 };
4110 
4111 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
4112                                 uint64_t value)
4113 {
4114     env->cp15.c15_ticonfig = value & 0xe7;
4115     /* The OS_TYPE bit in this register changes the reported CPUID! */
4116     env->cp15.c0_cpuid = (value & (1 << 5)) ?
4117         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
4118 }
4119 
4120 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
4121                                 uint64_t value)
4122 {
4123     env->cp15.c15_threadid = value & 0xffff;
4124 }
4125 
4126 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
4127                            uint64_t value)
4128 {
4129     /* Wait-for-interrupt (deprecated) */
4130     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
4131 }
4132 
4133 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
4134                                   uint64_t value)
4135 {
4136     /* On OMAP there are registers indicating the max/min index of dcache lines
4137      * containing a dirty line; cache flush operations have to reset these.
4138      */
4139     env->cp15.c15_i_max = 0x000;
4140     env->cp15.c15_i_min = 0xff0;
4141 }
4142 
4143 static const ARMCPRegInfo omap_cp_reginfo[] = {
4144     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
4145       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
4146       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
4147       .resetvalue = 0, },
4148     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
4149       .access = PL1_RW, .type = ARM_CP_NOP },
4150     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
4151       .access = PL1_RW,
4152       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
4153       .writefn = omap_ticonfig_write },
4154     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
4155       .access = PL1_RW,
4156       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
4157     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
4158       .access = PL1_RW, .resetvalue = 0xff0,
4159       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
4160     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
4161       .access = PL1_RW,
4162       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
4163       .writefn = omap_threadid_write },
4164     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
4165       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4166       .type = ARM_CP_NO_RAW,
4167       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
4168     /* TODO: Peripheral port remap register:
4169      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
4170      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
4171      * when MMU is off.
4172      */
4173     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
4174       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
4175       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
4176       .writefn = omap_cachemaint_write },
4177     { .name = "C9", .cp = 15, .crn = 9,
4178       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
4179       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
4180     REGINFO_SENTINEL
4181 };
4182 
4183 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4184                               uint64_t value)
4185 {
4186     env->cp15.c15_cpar = value & 0x3fff;
4187 }
4188 
4189 static const ARMCPRegInfo xscale_cp_reginfo[] = {
4190     { .name = "XSCALE_CPAR",
4191       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4192       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
4193       .writefn = xscale_cpar_write, },
4194     { .name = "XSCALE_AUXCR",
4195       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
4196       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
4197       .resetvalue = 0, },
4198     /* XScale specific cache-lockdown: since we have no cache we NOP these
4199      * and hope the guest does not really rely on cache behaviour.
4200      */
4201     { .name = "XSCALE_LOCK_ICACHE_LINE",
4202       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
4203       .access = PL1_W, .type = ARM_CP_NOP },
4204     { .name = "XSCALE_UNLOCK_ICACHE",
4205       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
4206       .access = PL1_W, .type = ARM_CP_NOP },
4207     { .name = "XSCALE_DCACHE_LOCK",
4208       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
4209       .access = PL1_RW, .type = ARM_CP_NOP },
4210     { .name = "XSCALE_UNLOCK_DCACHE",
4211       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
4212       .access = PL1_W, .type = ARM_CP_NOP },
4213     REGINFO_SENTINEL
4214 };
4215 
4216 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
4217     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
4218      * implementation of this implementation-defined space.
4219      * Ideally this should eventually disappear in favour of actually
4220      * implementing the correct behaviour for all cores.
4221      */
4222     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
4223       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4224       .access = PL1_RW,
4225       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
4226       .resetvalue = 0 },
4227     REGINFO_SENTINEL
4228 };
4229 
4230 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
4231     /* Cache status: RAZ because we have no cache so it's always clean */
4232     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
4233       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4234       .resetvalue = 0 },
4235     REGINFO_SENTINEL
4236 };
4237 
4238 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
4239     /* We never have a a block transfer operation in progress */
4240     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4241       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4242       .resetvalue = 0 },
4243     /* The cache ops themselves: these all NOP for QEMU */
4244     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4245       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4246     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4247       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4248     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4249       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4250     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4251       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4252     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4253       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4254     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4255       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4256     REGINFO_SENTINEL
4257 };
4258 
4259 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4260     /* The cache test-and-clean instructions always return (1 << 30)
4261      * to indicate that there are no dirty cache lines.
4262      */
4263     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4264       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4265       .resetvalue = (1 << 30) },
4266     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4267       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4268       .resetvalue = (1 << 30) },
4269     REGINFO_SENTINEL
4270 };
4271 
4272 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4273     /* Ignore ReadBuffer accesses */
4274     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4275       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4276       .access = PL1_RW, .resetvalue = 0,
4277       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4278     REGINFO_SENTINEL
4279 };
4280 
4281 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4282 {
4283     ARMCPU *cpu = env_archcpu(env);
4284     unsigned int cur_el = arm_current_el(env);
4285     bool secure = arm_is_secure(env);
4286 
4287     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
4288         return env->cp15.vpidr_el2;
4289     }
4290     return raw_read(env, ri);
4291 }
4292 
4293 static uint64_t mpidr_read_val(CPUARMState *env)
4294 {
4295     ARMCPU *cpu = env_archcpu(env);
4296     uint64_t mpidr = cpu->mp_affinity;
4297 
4298     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4299         mpidr |= (1U << 31);
4300         /* Cores which are uniprocessor (non-coherent)
4301          * but still implement the MP extensions set
4302          * bit 30. (For instance, Cortex-R5).
4303          */
4304         if (cpu->mp_is_up) {
4305             mpidr |= (1u << 30);
4306         }
4307     }
4308     return mpidr;
4309 }
4310 
4311 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4312 {
4313     unsigned int cur_el = arm_current_el(env);
4314     bool secure = arm_is_secure(env);
4315 
4316     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
4317         return env->cp15.vmpidr_el2;
4318     }
4319     return mpidr_read_val(env);
4320 }
4321 
4322 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4323     /* NOP AMAIR0/1 */
4324     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4325       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4326       .access = PL1_RW, .accessfn = access_tvm_trvm,
4327       .type = ARM_CP_CONST, .resetvalue = 0 },
4328     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4329     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4330       .access = PL1_RW, .accessfn = access_tvm_trvm,
4331       .type = ARM_CP_CONST, .resetvalue = 0 },
4332     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4333       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4334       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4335                              offsetof(CPUARMState, cp15.par_ns)} },
4336     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4337       .access = PL1_RW, .accessfn = access_tvm_trvm,
4338       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4339       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4340                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4341       .writefn = vmsa_ttbr_write, },
4342     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4343       .access = PL1_RW, .accessfn = access_tvm_trvm,
4344       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4345       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4346                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4347       .writefn = vmsa_ttbr_write, },
4348     REGINFO_SENTINEL
4349 };
4350 
4351 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4352 {
4353     return vfp_get_fpcr(env);
4354 }
4355 
4356 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4357                             uint64_t value)
4358 {
4359     vfp_set_fpcr(env, value);
4360 }
4361 
4362 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4363 {
4364     return vfp_get_fpsr(env);
4365 }
4366 
4367 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4368                             uint64_t value)
4369 {
4370     vfp_set_fpsr(env, value);
4371 }
4372 
4373 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4374                                        bool isread)
4375 {
4376     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4377         return CP_ACCESS_TRAP;
4378     }
4379     return CP_ACCESS_OK;
4380 }
4381 
4382 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4383                             uint64_t value)
4384 {
4385     env->daif = value & PSTATE_DAIF;
4386 }
4387 
4388 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4389 {
4390     return env->pstate & PSTATE_PAN;
4391 }
4392 
4393 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4394                            uint64_t value)
4395 {
4396     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4397 }
4398 
4399 static const ARMCPRegInfo pan_reginfo = {
4400     .name = "PAN", .state = ARM_CP_STATE_AA64,
4401     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4402     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4403     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4404 };
4405 
4406 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4407 {
4408     return env->pstate & PSTATE_UAO;
4409 }
4410 
4411 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4412                            uint64_t value)
4413 {
4414     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4415 }
4416 
4417 static const ARMCPRegInfo uao_reginfo = {
4418     .name = "UAO", .state = ARM_CP_STATE_AA64,
4419     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4420     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4421     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4422 };
4423 
4424 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4425                                               const ARMCPRegInfo *ri,
4426                                               bool isread)
4427 {
4428     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4429     switch (arm_current_el(env)) {
4430     case 0:
4431         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4432         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4433             return CP_ACCESS_TRAP;
4434         }
4435         /* fall through */
4436     case 1:
4437         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4438         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4439             return CP_ACCESS_TRAP_EL2;
4440         }
4441         break;
4442     }
4443     return CP_ACCESS_OK;
4444 }
4445 
4446 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4447                                               const ARMCPRegInfo *ri,
4448                                               bool isread)
4449 {
4450     /* Cache invalidate/clean to Point of Unification... */
4451     switch (arm_current_el(env)) {
4452     case 0:
4453         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4454         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4455             return CP_ACCESS_TRAP;
4456         }
4457         /* fall through */
4458     case 1:
4459         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4460         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4461             return CP_ACCESS_TRAP_EL2;
4462         }
4463         break;
4464     }
4465     return CP_ACCESS_OK;
4466 }
4467 
4468 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4469  * Page D4-1736 (DDI0487A.b)
4470  */
4471 
4472 static int vae1_tlbmask(CPUARMState *env)
4473 {
4474     /* Since we exclude secure first, we may read HCR_EL2 directly. */
4475     if (arm_is_secure_below_el3(env)) {
4476         return ARMMMUIdxBit_SE10_1 |
4477                ARMMMUIdxBit_SE10_1_PAN |
4478                ARMMMUIdxBit_SE10_0;
4479     } else if ((env->cp15.hcr_el2 & (HCR_E2H | HCR_TGE))
4480                == (HCR_E2H | HCR_TGE)) {
4481         return ARMMMUIdxBit_E20_2 |
4482                ARMMMUIdxBit_E20_2_PAN |
4483                ARMMMUIdxBit_E20_0;
4484     } else {
4485         return ARMMMUIdxBit_E10_1 |
4486                ARMMMUIdxBit_E10_1_PAN |
4487                ARMMMUIdxBit_E10_0;
4488     }
4489 }
4490 
4491 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4492                                       uint64_t value)
4493 {
4494     CPUState *cs = env_cpu(env);
4495     int mask = vae1_tlbmask(env);
4496 
4497     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4498 }
4499 
4500 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4501                                     uint64_t value)
4502 {
4503     CPUState *cs = env_cpu(env);
4504     int mask = vae1_tlbmask(env);
4505 
4506     if (tlb_force_broadcast(env)) {
4507         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4508     } else {
4509         tlb_flush_by_mmuidx(cs, mask);
4510     }
4511 }
4512 
4513 static int alle1_tlbmask(CPUARMState *env)
4514 {
4515     /*
4516      * Note that the 'ALL' scope must invalidate both stage 1 and
4517      * stage 2 translations, whereas most other scopes only invalidate
4518      * stage 1 translations.
4519      */
4520     if (arm_is_secure_below_el3(env)) {
4521         return ARMMMUIdxBit_SE10_1 |
4522                ARMMMUIdxBit_SE10_1_PAN |
4523                ARMMMUIdxBit_SE10_0;
4524     } else if (arm_feature(env, ARM_FEATURE_EL2)) {
4525         return ARMMMUIdxBit_E10_1 |
4526                ARMMMUIdxBit_E10_1_PAN |
4527                ARMMMUIdxBit_E10_0 |
4528                ARMMMUIdxBit_Stage2;
4529     } else {
4530         return ARMMMUIdxBit_E10_1 |
4531                ARMMMUIdxBit_E10_1_PAN |
4532                ARMMMUIdxBit_E10_0;
4533     }
4534 }
4535 
4536 static int e2_tlbmask(CPUARMState *env)
4537 {
4538     /* TODO: ARMv8.4-SecEL2 */
4539     return ARMMMUIdxBit_E20_0 |
4540            ARMMMUIdxBit_E20_2 |
4541            ARMMMUIdxBit_E20_2_PAN |
4542            ARMMMUIdxBit_E2;
4543 }
4544 
4545 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4546                                   uint64_t value)
4547 {
4548     CPUState *cs = env_cpu(env);
4549     int mask = alle1_tlbmask(env);
4550 
4551     tlb_flush_by_mmuidx(cs, mask);
4552 }
4553 
4554 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4555                                   uint64_t value)
4556 {
4557     CPUState *cs = env_cpu(env);
4558     int mask = e2_tlbmask(env);
4559 
4560     tlb_flush_by_mmuidx(cs, mask);
4561 }
4562 
4563 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4564                                   uint64_t value)
4565 {
4566     ARMCPU *cpu = env_archcpu(env);
4567     CPUState *cs = CPU(cpu);
4568 
4569     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4570 }
4571 
4572 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4573                                     uint64_t value)
4574 {
4575     CPUState *cs = env_cpu(env);
4576     int mask = alle1_tlbmask(env);
4577 
4578     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4579 }
4580 
4581 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4582                                     uint64_t value)
4583 {
4584     CPUState *cs = env_cpu(env);
4585     int mask = e2_tlbmask(env);
4586 
4587     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4588 }
4589 
4590 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4591                                     uint64_t value)
4592 {
4593     CPUState *cs = env_cpu(env);
4594 
4595     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4596 }
4597 
4598 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4599                                  uint64_t value)
4600 {
4601     /* Invalidate by VA, EL2
4602      * Currently handles both VAE2 and VALE2, since we don't support
4603      * flush-last-level-only.
4604      */
4605     CPUState *cs = env_cpu(env);
4606     int mask = e2_tlbmask(env);
4607     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4608 
4609     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4610 }
4611 
4612 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4613                                  uint64_t value)
4614 {
4615     /* Invalidate by VA, EL3
4616      * Currently handles both VAE3 and VALE3, since we don't support
4617      * flush-last-level-only.
4618      */
4619     ARMCPU *cpu = env_archcpu(env);
4620     CPUState *cs = CPU(cpu);
4621     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4622 
4623     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4624 }
4625 
4626 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4627                                    uint64_t value)
4628 {
4629     CPUState *cs = env_cpu(env);
4630     int mask = vae1_tlbmask(env);
4631     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4632 
4633     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr, mask);
4634 }
4635 
4636 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4637                                  uint64_t value)
4638 {
4639     /* Invalidate by VA, EL1&0 (AArch64 version).
4640      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4641      * since we don't support flush-for-specific-ASID-only or
4642      * flush-last-level-only.
4643      */
4644     CPUState *cs = env_cpu(env);
4645     int mask = vae1_tlbmask(env);
4646     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4647 
4648     if (tlb_force_broadcast(env)) {
4649         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr, mask);
4650     } else {
4651         tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4652     }
4653 }
4654 
4655 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4656                                    uint64_t value)
4657 {
4658     CPUState *cs = env_cpu(env);
4659     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4660 
4661     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4662                                              ARMMMUIdxBit_E2);
4663 }
4664 
4665 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4666                                    uint64_t value)
4667 {
4668     CPUState *cs = env_cpu(env);
4669     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4670 
4671     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4672                                              ARMMMUIdxBit_SE3);
4673 }
4674 
4675 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4676                                     uint64_t value)
4677 {
4678     /* Invalidate by IPA. This has to invalidate any structures that
4679      * contain only stage 2 translation information, but does not need
4680      * to apply to structures that contain combined stage 1 and stage 2
4681      * translation information.
4682      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
4683      */
4684     ARMCPU *cpu = env_archcpu(env);
4685     CPUState *cs = CPU(cpu);
4686     uint64_t pageaddr;
4687 
4688     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4689         return;
4690     }
4691 
4692     pageaddr = sextract64(value << 12, 0, 48);
4693 
4694     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_Stage2);
4695 }
4696 
4697 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4698                                       uint64_t value)
4699 {
4700     CPUState *cs = env_cpu(env);
4701     uint64_t pageaddr;
4702 
4703     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4704         return;
4705     }
4706 
4707     pageaddr = sextract64(value << 12, 0, 48);
4708 
4709     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4710                                              ARMMMUIdxBit_Stage2);
4711 }
4712 
4713 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4714                                       bool isread)
4715 {
4716     int cur_el = arm_current_el(env);
4717 
4718     if (cur_el < 2) {
4719         uint64_t hcr = arm_hcr_el2_eff(env);
4720 
4721         if (cur_el == 0) {
4722             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4723                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4724                     return CP_ACCESS_TRAP_EL2;
4725                 }
4726             } else {
4727                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4728                     return CP_ACCESS_TRAP;
4729                 }
4730                 if (hcr & HCR_TDZ) {
4731                     return CP_ACCESS_TRAP_EL2;
4732                 }
4733             }
4734         } else if (hcr & HCR_TDZ) {
4735             return CP_ACCESS_TRAP_EL2;
4736         }
4737     }
4738     return CP_ACCESS_OK;
4739 }
4740 
4741 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4742 {
4743     ARMCPU *cpu = env_archcpu(env);
4744     int dzp_bit = 1 << 4;
4745 
4746     /* DZP indicates whether DC ZVA access is allowed */
4747     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4748         dzp_bit = 0;
4749     }
4750     return cpu->dcz_blocksize | dzp_bit;
4751 }
4752 
4753 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4754                                     bool isread)
4755 {
4756     if (!(env->pstate & PSTATE_SP)) {
4757         /* Access to SP_EL0 is undefined if it's being used as
4758          * the stack pointer.
4759          */
4760         return CP_ACCESS_TRAP_UNCATEGORIZED;
4761     }
4762     return CP_ACCESS_OK;
4763 }
4764 
4765 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4766 {
4767     return env->pstate & PSTATE_SP;
4768 }
4769 
4770 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4771 {
4772     update_spsel(env, val);
4773 }
4774 
4775 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4776                         uint64_t value)
4777 {
4778     ARMCPU *cpu = env_archcpu(env);
4779 
4780     if (raw_read(env, ri) == value) {
4781         /* Skip the TLB flush if nothing actually changed; Linux likes
4782          * to do a lot of pointless SCTLR writes.
4783          */
4784         return;
4785     }
4786 
4787     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4788         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4789         value &= ~SCTLR_M;
4790     }
4791 
4792     raw_write(env, ri, value);
4793     /* ??? Lots of these bits are not implemented.  */
4794     /* This may enable/disable the MMU, so do a TLB flush.  */
4795     tlb_flush(CPU(cpu));
4796 
4797     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4798         /*
4799          * Normally we would always end the TB on an SCTLR write; see the
4800          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4801          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4802          * of hflags from the translator, so do it here.
4803          */
4804         arm_rebuild_hflags(env);
4805     }
4806 }
4807 
4808 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4809                                      bool isread)
4810 {
4811     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4812         return CP_ACCESS_TRAP_FP_EL2;
4813     }
4814     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4815         return CP_ACCESS_TRAP_FP_EL3;
4816     }
4817     return CP_ACCESS_OK;
4818 }
4819 
4820 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4821                        uint64_t value)
4822 {
4823     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4824 }
4825 
4826 static const ARMCPRegInfo v8_cp_reginfo[] = {
4827     /* Minimal set of EL0-visible registers. This will need to be expanded
4828      * significantly for system emulation of AArch64 CPUs.
4829      */
4830     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4831       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4832       .access = PL0_RW, .type = ARM_CP_NZCV },
4833     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4834       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4835       .type = ARM_CP_NO_RAW,
4836       .access = PL0_RW, .accessfn = aa64_daif_access,
4837       .fieldoffset = offsetof(CPUARMState, daif),
4838       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4839     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4840       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4841       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4842       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4843     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4844       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4845       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4846       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4847     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4848       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4849       .access = PL0_R, .type = ARM_CP_NO_RAW,
4850       .readfn = aa64_dczid_read },
4851     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4852       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4853       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4854 #ifndef CONFIG_USER_ONLY
4855       /* Avoid overhead of an access check that always passes in user-mode */
4856       .accessfn = aa64_zva_access,
4857 #endif
4858     },
4859     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4860       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4861       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4862     /* Cache ops: all NOPs since we don't emulate caches */
4863     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4864       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4865       .access = PL1_W, .type = ARM_CP_NOP,
4866       .accessfn = aa64_cacheop_pou_access },
4867     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4868       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4869       .access = PL1_W, .type = ARM_CP_NOP,
4870       .accessfn = aa64_cacheop_pou_access },
4871     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4872       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4873       .access = PL0_W, .type = ARM_CP_NOP,
4874       .accessfn = aa64_cacheop_pou_access },
4875     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4876       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4877       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4878       .type = ARM_CP_NOP },
4879     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4880       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4881       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4882     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4883       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4884       .access = PL0_W, .type = ARM_CP_NOP,
4885       .accessfn = aa64_cacheop_poc_access },
4886     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4887       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4888       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4889     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4890       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4891       .access = PL0_W, .type = ARM_CP_NOP,
4892       .accessfn = aa64_cacheop_pou_access },
4893     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4894       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4895       .access = PL0_W, .type = ARM_CP_NOP,
4896       .accessfn = aa64_cacheop_poc_access },
4897     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4898       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4899       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4900     /* TLBI operations */
4901     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4902       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4903       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4904       .writefn = tlbi_aa64_vmalle1is_write },
4905     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4906       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4907       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4908       .writefn = tlbi_aa64_vae1is_write },
4909     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4910       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4911       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4912       .writefn = tlbi_aa64_vmalle1is_write },
4913     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4914       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4915       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4916       .writefn = tlbi_aa64_vae1is_write },
4917     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4918       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4919       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4920       .writefn = tlbi_aa64_vae1is_write },
4921     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4922       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4923       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4924       .writefn = tlbi_aa64_vae1is_write },
4925     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4926       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4927       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4928       .writefn = tlbi_aa64_vmalle1_write },
4929     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4930       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4931       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4932       .writefn = tlbi_aa64_vae1_write },
4933     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4934       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4935       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4936       .writefn = tlbi_aa64_vmalle1_write },
4937     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4938       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4939       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4940       .writefn = tlbi_aa64_vae1_write },
4941     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4942       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4943       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4944       .writefn = tlbi_aa64_vae1_write },
4945     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4946       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4947       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4948       .writefn = tlbi_aa64_vae1_write },
4949     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4950       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4951       .access = PL2_W, .type = ARM_CP_NO_RAW,
4952       .writefn = tlbi_aa64_ipas2e1is_write },
4953     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4954       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4955       .access = PL2_W, .type = ARM_CP_NO_RAW,
4956       .writefn = tlbi_aa64_ipas2e1is_write },
4957     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4958       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4959       .access = PL2_W, .type = ARM_CP_NO_RAW,
4960       .writefn = tlbi_aa64_alle1is_write },
4961     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4962       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4963       .access = PL2_W, .type = ARM_CP_NO_RAW,
4964       .writefn = tlbi_aa64_alle1is_write },
4965     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4966       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4967       .access = PL2_W, .type = ARM_CP_NO_RAW,
4968       .writefn = tlbi_aa64_ipas2e1_write },
4969     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4970       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4971       .access = PL2_W, .type = ARM_CP_NO_RAW,
4972       .writefn = tlbi_aa64_ipas2e1_write },
4973     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4974       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4975       .access = PL2_W, .type = ARM_CP_NO_RAW,
4976       .writefn = tlbi_aa64_alle1_write },
4977     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4978       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4979       .access = PL2_W, .type = ARM_CP_NO_RAW,
4980       .writefn = tlbi_aa64_alle1is_write },
4981 #ifndef CONFIG_USER_ONLY
4982     /* 64 bit address translation operations */
4983     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4984       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4985       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4986       .writefn = ats_write64 },
4987     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4988       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4989       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4990       .writefn = ats_write64 },
4991     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4992       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4993       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4994       .writefn = ats_write64 },
4995     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4996       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4997       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4998       .writefn = ats_write64 },
4999     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
5000       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
5001       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5002       .writefn = ats_write64 },
5003     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
5004       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
5005       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5006       .writefn = ats_write64 },
5007     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
5008       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
5009       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5010       .writefn = ats_write64 },
5011     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
5012       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
5013       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5014       .writefn = ats_write64 },
5015     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
5016     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
5017       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
5018       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5019       .writefn = ats_write64 },
5020     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
5021       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
5022       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5023       .writefn = ats_write64 },
5024     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
5025       .type = ARM_CP_ALIAS,
5026       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
5027       .access = PL1_RW, .resetvalue = 0,
5028       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
5029       .writefn = par_write },
5030 #endif
5031     /* TLB invalidate last level of translation table walk */
5032     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
5033       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5034       .writefn = tlbimva_is_write },
5035     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
5036       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5037       .writefn = tlbimvaa_is_write },
5038     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
5039       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5040       .writefn = tlbimva_write },
5041     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
5042       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5043       .writefn = tlbimvaa_write },
5044     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5045       .type = ARM_CP_NO_RAW, .access = PL2_W,
5046       .writefn = tlbimva_hyp_write },
5047     { .name = "TLBIMVALHIS",
5048       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5049       .type = ARM_CP_NO_RAW, .access = PL2_W,
5050       .writefn = tlbimva_hyp_is_write },
5051     { .name = "TLBIIPAS2",
5052       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5053       .type = ARM_CP_NO_RAW, .access = PL2_W,
5054       .writefn = tlbiipas2_write },
5055     { .name = "TLBIIPAS2IS",
5056       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5057       .type = ARM_CP_NO_RAW, .access = PL2_W,
5058       .writefn = tlbiipas2_is_write },
5059     { .name = "TLBIIPAS2L",
5060       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5061       .type = ARM_CP_NO_RAW, .access = PL2_W,
5062       .writefn = tlbiipas2_write },
5063     { .name = "TLBIIPAS2LIS",
5064       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5065       .type = ARM_CP_NO_RAW, .access = PL2_W,
5066       .writefn = tlbiipas2_is_write },
5067     /* 32 bit cache operations */
5068     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5069       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5070     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5071       .type = ARM_CP_NOP, .access = PL1_W },
5072     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5073       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5074     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5075       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5076     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5077       .type = ARM_CP_NOP, .access = PL1_W },
5078     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5079       .type = ARM_CP_NOP, .access = PL1_W },
5080     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5081       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5082     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5083       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5084     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5085       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5086     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5087       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5088     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5089       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5090     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5091       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5092     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5093       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5094     /* MMU Domain access control / MPU write buffer control */
5095     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5096       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5097       .writefn = dacr_write, .raw_writefn = raw_write,
5098       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5099                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5100     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5101       .type = ARM_CP_ALIAS,
5102       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5103       .access = PL1_RW,
5104       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5105     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5106       .type = ARM_CP_ALIAS,
5107       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5108       .access = PL1_RW,
5109       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5110     /* We rely on the access checks not allowing the guest to write to the
5111      * state field when SPSel indicates that it's being used as the stack
5112      * pointer.
5113      */
5114     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5115       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5116       .access = PL1_RW, .accessfn = sp_el0_access,
5117       .type = ARM_CP_ALIAS,
5118       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5119     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5120       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5121       .access = PL2_RW, .type = ARM_CP_ALIAS,
5122       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5123     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5124       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5125       .type = ARM_CP_NO_RAW,
5126       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5127     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5128       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5129       .type = ARM_CP_ALIAS,
5130       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
5131       .access = PL2_RW, .accessfn = fpexc32_access },
5132     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5133       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5134       .access = PL2_RW, .resetvalue = 0,
5135       .writefn = dacr_write, .raw_writefn = raw_write,
5136       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5137     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5138       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5139       .access = PL2_RW, .resetvalue = 0,
5140       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5141     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5142       .type = ARM_CP_ALIAS,
5143       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5144       .access = PL2_RW,
5145       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5146     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5147       .type = ARM_CP_ALIAS,
5148       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5149       .access = PL2_RW,
5150       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5151     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5152       .type = ARM_CP_ALIAS,
5153       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5154       .access = PL2_RW,
5155       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5156     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5157       .type = ARM_CP_ALIAS,
5158       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5159       .access = PL2_RW,
5160       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5161     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5162       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5163       .resetvalue = 0,
5164       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5165     { .name = "SDCR", .type = ARM_CP_ALIAS,
5166       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5167       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5168       .writefn = sdcr_write,
5169       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5170     REGINFO_SENTINEL
5171 };
5172 
5173 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
5174 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
5175     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5176       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5177       .access = PL2_RW,
5178       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
5179     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
5180       .type = ARM_CP_NO_RAW,
5181       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5182       .access = PL2_RW,
5183       .type = ARM_CP_CONST, .resetvalue = 0 },
5184     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5185       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5186       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5187     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5188       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5189       .access = PL2_RW,
5190       .type = ARM_CP_CONST, .resetvalue = 0 },
5191     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5192       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5193       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5194     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5195       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5196       .access = PL2_RW, .type = ARM_CP_CONST,
5197       .resetvalue = 0 },
5198     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5199       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5200       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5201     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5202       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5203       .access = PL2_RW, .type = ARM_CP_CONST,
5204       .resetvalue = 0 },
5205     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5206       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5207       .access = PL2_RW, .type = ARM_CP_CONST,
5208       .resetvalue = 0 },
5209     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5210       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5211       .access = PL2_RW, .type = ARM_CP_CONST,
5212       .resetvalue = 0 },
5213     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5214       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5215       .access = PL2_RW, .type = ARM_CP_CONST,
5216       .resetvalue = 0 },
5217     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5218       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5219       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5220     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
5221       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5222       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5223       .type = ARM_CP_CONST, .resetvalue = 0 },
5224     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5225       .cp = 15, .opc1 = 6, .crm = 2,
5226       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5227       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
5228     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5229       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5230       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5231     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5232       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5233       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5234     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5235       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5236       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5237     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5238       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5239       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5240     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5241       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5242       .resetvalue = 0 },
5243     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5244       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5245       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5246     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5247       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5248       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5249     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5250       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5251       .resetvalue = 0 },
5252     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5253       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5254       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5255     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5256       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5257       .resetvalue = 0 },
5258     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5259       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5260       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5261     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5262       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5263       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5264     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5265       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5266       .access = PL2_RW, .accessfn = access_tda,
5267       .type = ARM_CP_CONST, .resetvalue = 0 },
5268     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
5269       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5270       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5271       .type = ARM_CP_CONST, .resetvalue = 0 },
5272     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5273       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5274       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5275     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5276       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5277       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5278     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5279       .type = ARM_CP_CONST,
5280       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5281       .access = PL2_RW, .resetvalue = 0 },
5282     REGINFO_SENTINEL
5283 };
5284 
5285 /* Ditto, but for registers which exist in ARMv8 but not v7 */
5286 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
5287     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5288       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5289       .access = PL2_RW,
5290       .type = ARM_CP_CONST, .resetvalue = 0 },
5291     REGINFO_SENTINEL
5292 };
5293 
5294 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5295 {
5296     ARMCPU *cpu = env_archcpu(env);
5297 
5298     if (arm_feature(env, ARM_FEATURE_V8)) {
5299         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5300     } else {
5301         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5302     }
5303 
5304     if (arm_feature(env, ARM_FEATURE_EL3)) {
5305         valid_mask &= ~HCR_HCD;
5306     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5307         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5308          * However, if we're using the SMC PSCI conduit then QEMU is
5309          * effectively acting like EL3 firmware and so the guest at
5310          * EL2 should retain the ability to prevent EL1 from being
5311          * able to make SMC calls into the ersatz firmware, so in
5312          * that case HCR.TSC should be read/write.
5313          */
5314         valid_mask &= ~HCR_TSC;
5315     }
5316 
5317     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5318         if (cpu_isar_feature(aa64_vh, cpu)) {
5319             valid_mask |= HCR_E2H;
5320         }
5321         if (cpu_isar_feature(aa64_lor, cpu)) {
5322             valid_mask |= HCR_TLOR;
5323         }
5324         if (cpu_isar_feature(aa64_pauth, cpu)) {
5325             valid_mask |= HCR_API | HCR_APK;
5326         }
5327     }
5328 
5329     /* Clear RES0 bits.  */
5330     value &= valid_mask;
5331 
5332     /* These bits change the MMU setup:
5333      * HCR_VM enables stage 2 translation
5334      * HCR_PTW forbids certain page-table setups
5335      * HCR_DC Disables stage1 and enables stage2 translation
5336      */
5337     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
5338         tlb_flush(CPU(cpu));
5339     }
5340     env->cp15.hcr_el2 = value;
5341 
5342     /*
5343      * Updates to VI and VF require us to update the status of
5344      * virtual interrupts, which are the logical OR of these bits
5345      * and the state of the input lines from the GIC. (This requires
5346      * that we have the iothread lock, which is done by marking the
5347      * reginfo structs as ARM_CP_IO.)
5348      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5349      * possible for it to be taken immediately, because VIRQ and
5350      * VFIQ are masked unless running at EL0 or EL1, and HCR
5351      * can only be written at EL2.
5352      */
5353     g_assert(qemu_mutex_iothread_locked());
5354     arm_cpu_update_virq(cpu);
5355     arm_cpu_update_vfiq(cpu);
5356 }
5357 
5358 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5359 {
5360     do_hcr_write(env, value, 0);
5361 }
5362 
5363 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5364                           uint64_t value)
5365 {
5366     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5367     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5368     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5369 }
5370 
5371 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5372                          uint64_t value)
5373 {
5374     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5375     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5376     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5377 }
5378 
5379 /*
5380  * Return the effective value of HCR_EL2.
5381  * Bits that are not included here:
5382  * RW       (read from SCR_EL3.RW as needed)
5383  */
5384 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5385 {
5386     uint64_t ret = env->cp15.hcr_el2;
5387 
5388     if (arm_is_secure_below_el3(env)) {
5389         /*
5390          * "This register has no effect if EL2 is not enabled in the
5391          * current Security state".  This is ARMv8.4-SecEL2 speak for
5392          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5393          *
5394          * Prior to that, the language was "In an implementation that
5395          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5396          * as if this field is 0 for all purposes other than a direct
5397          * read or write access of HCR_EL2".  With lots of enumeration
5398          * on a per-field basis.  In current QEMU, this is condition
5399          * is arm_is_secure_below_el3.
5400          *
5401          * Since the v8.4 language applies to the entire register, and
5402          * appears to be backward compatible, use that.
5403          */
5404         return 0;
5405     }
5406 
5407     /*
5408      * For a cpu that supports both aarch64 and aarch32, we can set bits
5409      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5410      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5411      */
5412     if (!arm_el_is_aa64(env, 2)) {
5413         uint64_t aa32_valid;
5414 
5415         /*
5416          * These bits are up-to-date as of ARMv8.6.
5417          * For HCR, it's easiest to list just the 2 bits that are invalid.
5418          * For HCR2, list those that are valid.
5419          */
5420         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5421         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5422                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5423         ret &= aa32_valid;
5424     }
5425 
5426     if (ret & HCR_TGE) {
5427         /* These bits are up-to-date as of ARMv8.6.  */
5428         if (ret & HCR_E2H) {
5429             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5430                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5431                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5432                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5433                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5434                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5435         } else {
5436             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5437         }
5438         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5439                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5440                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5441                  HCR_TLOR);
5442     }
5443 
5444     return ret;
5445 }
5446 
5447 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5448                            uint64_t value)
5449 {
5450     /*
5451      * For A-profile AArch32 EL3, if NSACR.CP10
5452      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5453      */
5454     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5455         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5456         value &= ~(0x3 << 10);
5457         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5458     }
5459     env->cp15.cptr_el[2] = value;
5460 }
5461 
5462 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5463 {
5464     /*
5465      * For A-profile AArch32 EL3, if NSACR.CP10
5466      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5467      */
5468     uint64_t value = env->cp15.cptr_el[2];
5469 
5470     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5471         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5472         value |= 0x3 << 10;
5473     }
5474     return value;
5475 }
5476 
5477 static const ARMCPRegInfo el2_cp_reginfo[] = {
5478     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5479       .type = ARM_CP_IO,
5480       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5481       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5482       .writefn = hcr_write },
5483     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5484       .type = ARM_CP_ALIAS | ARM_CP_IO,
5485       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5486       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5487       .writefn = hcr_writelow },
5488     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5489       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5490       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5491     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5492       .type = ARM_CP_ALIAS,
5493       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5494       .access = PL2_RW,
5495       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5496     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5497       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5498       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5499     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5500       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5501       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5502     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5503       .type = ARM_CP_ALIAS,
5504       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5505       .access = PL2_RW,
5506       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5507     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5508       .type = ARM_CP_ALIAS,
5509       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5510       .access = PL2_RW,
5511       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5512     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5513       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5514       .access = PL2_RW, .writefn = vbar_write,
5515       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5516       .resetvalue = 0 },
5517     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5518       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5519       .access = PL3_RW, .type = ARM_CP_ALIAS,
5520       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5521     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5522       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5523       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5524       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5525       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5526     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5527       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5528       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5529       .resetvalue = 0 },
5530     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5531       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5532       .access = PL2_RW, .type = ARM_CP_ALIAS,
5533       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5534     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5535       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5536       .access = PL2_RW, .type = ARM_CP_CONST,
5537       .resetvalue = 0 },
5538     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5539     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5540       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5541       .access = PL2_RW, .type = ARM_CP_CONST,
5542       .resetvalue = 0 },
5543     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5544       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5545       .access = PL2_RW, .type = ARM_CP_CONST,
5546       .resetvalue = 0 },
5547     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5548       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5549       .access = PL2_RW, .type = ARM_CP_CONST,
5550       .resetvalue = 0 },
5551     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5552       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5553       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5554       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5555       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5556     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5557       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5558       .type = ARM_CP_ALIAS,
5559       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5560       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5561     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5562       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5563       .access = PL2_RW,
5564       /* no .writefn needed as this can't cause an ASID change;
5565        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5566        */
5567       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5568     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5569       .cp = 15, .opc1 = 6, .crm = 2,
5570       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5571       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5572       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5573       .writefn = vttbr_write },
5574     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5575       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5576       .access = PL2_RW, .writefn = vttbr_write,
5577       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5578     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5579       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5580       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5581       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5582     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5583       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5584       .access = PL2_RW, .resetvalue = 0,
5585       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5586     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5587       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5588       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5589       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5590     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5591       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5592       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5593     { .name = "TLBIALLNSNH",
5594       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5595       .type = ARM_CP_NO_RAW, .access = PL2_W,
5596       .writefn = tlbiall_nsnh_write },
5597     { .name = "TLBIALLNSNHIS",
5598       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5599       .type = ARM_CP_NO_RAW, .access = PL2_W,
5600       .writefn = tlbiall_nsnh_is_write },
5601     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5602       .type = ARM_CP_NO_RAW, .access = PL2_W,
5603       .writefn = tlbiall_hyp_write },
5604     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5605       .type = ARM_CP_NO_RAW, .access = PL2_W,
5606       .writefn = tlbiall_hyp_is_write },
5607     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5608       .type = ARM_CP_NO_RAW, .access = PL2_W,
5609       .writefn = tlbimva_hyp_write },
5610     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5611       .type = ARM_CP_NO_RAW, .access = PL2_W,
5612       .writefn = tlbimva_hyp_is_write },
5613     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5614       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5615       .type = ARM_CP_NO_RAW, .access = PL2_W,
5616       .writefn = tlbi_aa64_alle2_write },
5617     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5618       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5619       .type = ARM_CP_NO_RAW, .access = PL2_W,
5620       .writefn = tlbi_aa64_vae2_write },
5621     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5622       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5623       .access = PL2_W, .type = ARM_CP_NO_RAW,
5624       .writefn = tlbi_aa64_vae2_write },
5625     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5626       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5627       .access = PL2_W, .type = ARM_CP_NO_RAW,
5628       .writefn = tlbi_aa64_alle2is_write },
5629     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5630       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5631       .type = ARM_CP_NO_RAW, .access = PL2_W,
5632       .writefn = tlbi_aa64_vae2is_write },
5633     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5634       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5635       .access = PL2_W, .type = ARM_CP_NO_RAW,
5636       .writefn = tlbi_aa64_vae2is_write },
5637 #ifndef CONFIG_USER_ONLY
5638     /* Unlike the other EL2-related AT operations, these must
5639      * UNDEF from EL3 if EL2 is not implemented, which is why we
5640      * define them here rather than with the rest of the AT ops.
5641      */
5642     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5643       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5644       .access = PL2_W, .accessfn = at_s1e2_access,
5645       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5646     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5647       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5648       .access = PL2_W, .accessfn = at_s1e2_access,
5649       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5650     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5651      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5652      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5653      * to behave as if SCR.NS was 1.
5654      */
5655     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5656       .access = PL2_W,
5657       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5658     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5659       .access = PL2_W,
5660       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5661     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5662       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5663       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5664        * reset values as IMPDEF. We choose to reset to 3 to comply with
5665        * both ARMv7 and ARMv8.
5666        */
5667       .access = PL2_RW, .resetvalue = 3,
5668       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5669     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5670       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5671       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5672       .writefn = gt_cntvoff_write,
5673       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5674     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5675       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5676       .writefn = gt_cntvoff_write,
5677       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5678     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5679       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5680       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5681       .type = ARM_CP_IO, .access = PL2_RW,
5682       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5683     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5684       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5685       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5686       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5687     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5688       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5689       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5690       .resetfn = gt_hyp_timer_reset,
5691       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5692     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5693       .type = ARM_CP_IO,
5694       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5695       .access = PL2_RW,
5696       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5697       .resetvalue = 0,
5698       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5699 #endif
5700     /* The only field of MDCR_EL2 that has a defined architectural reset value
5701      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
5702      * don't implement any PMU event counters, so using zero as a reset
5703      * value for MDCR_EL2 is okay
5704      */
5705     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5706       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5707       .access = PL2_RW, .resetvalue = 0,
5708       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5709     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5710       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5711       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5712       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5713     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5714       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5715       .access = PL2_RW,
5716       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5717     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5718       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5719       .access = PL2_RW,
5720       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5721     REGINFO_SENTINEL
5722 };
5723 
5724 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5725     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5726       .type = ARM_CP_ALIAS | ARM_CP_IO,
5727       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5728       .access = PL2_RW,
5729       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5730       .writefn = hcr_writehigh },
5731     REGINFO_SENTINEL
5732 };
5733 
5734 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5735                                    bool isread)
5736 {
5737     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5738      * At Secure EL1 it traps to EL3.
5739      */
5740     if (arm_current_el(env) == 3) {
5741         return CP_ACCESS_OK;
5742     }
5743     if (arm_is_secure_below_el3(env)) {
5744         return CP_ACCESS_TRAP_EL3;
5745     }
5746     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5747     if (isread) {
5748         return CP_ACCESS_OK;
5749     }
5750     return CP_ACCESS_TRAP_UNCATEGORIZED;
5751 }
5752 
5753 static const ARMCPRegInfo el3_cp_reginfo[] = {
5754     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5755       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5756       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5757       .resetvalue = 0, .writefn = scr_write },
5758     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5759       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5760       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5761       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5762       .writefn = scr_write },
5763     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5764       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5765       .access = PL3_RW, .resetvalue = 0,
5766       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5767     { .name = "SDER",
5768       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5769       .access = PL3_RW, .resetvalue = 0,
5770       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5771     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5772       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5773       .writefn = vbar_write, .resetvalue = 0,
5774       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5775     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5776       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5777       .access = PL3_RW, .resetvalue = 0,
5778       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5779     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5780       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5781       .access = PL3_RW,
5782       /* no .writefn needed as this can't cause an ASID change;
5783        * we must provide a .raw_writefn and .resetfn because we handle
5784        * reset and migration for the AArch32 TTBCR(S), which might be
5785        * using mask and base_mask.
5786        */
5787       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5788       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5789     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5790       .type = ARM_CP_ALIAS,
5791       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5792       .access = PL3_RW,
5793       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5794     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5795       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5796       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5797     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5798       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5799       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5800     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5801       .type = ARM_CP_ALIAS,
5802       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5803       .access = PL3_RW,
5804       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5805     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5806       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5807       .access = PL3_RW, .writefn = vbar_write,
5808       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5809       .resetvalue = 0 },
5810     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5811       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5812       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5813       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5814     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5815       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5816       .access = PL3_RW, .resetvalue = 0,
5817       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5818     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5819       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5820       .access = PL3_RW, .type = ARM_CP_CONST,
5821       .resetvalue = 0 },
5822     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5823       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5824       .access = PL3_RW, .type = ARM_CP_CONST,
5825       .resetvalue = 0 },
5826     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5827       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5828       .access = PL3_RW, .type = ARM_CP_CONST,
5829       .resetvalue = 0 },
5830     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5831       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5832       .access = PL3_W, .type = ARM_CP_NO_RAW,
5833       .writefn = tlbi_aa64_alle3is_write },
5834     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5835       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5836       .access = PL3_W, .type = ARM_CP_NO_RAW,
5837       .writefn = tlbi_aa64_vae3is_write },
5838     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5839       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5840       .access = PL3_W, .type = ARM_CP_NO_RAW,
5841       .writefn = tlbi_aa64_vae3is_write },
5842     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5843       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5844       .access = PL3_W, .type = ARM_CP_NO_RAW,
5845       .writefn = tlbi_aa64_alle3_write },
5846     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5847       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5848       .access = PL3_W, .type = ARM_CP_NO_RAW,
5849       .writefn = tlbi_aa64_vae3_write },
5850     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5851       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5852       .access = PL3_W, .type = ARM_CP_NO_RAW,
5853       .writefn = tlbi_aa64_vae3_write },
5854     REGINFO_SENTINEL
5855 };
5856 
5857 #ifndef CONFIG_USER_ONLY
5858 /* Test if system register redirection is to occur in the current state.  */
5859 static bool redirect_for_e2h(CPUARMState *env)
5860 {
5861     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5862 }
5863 
5864 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5865 {
5866     CPReadFn *readfn;
5867 
5868     if (redirect_for_e2h(env)) {
5869         /* Switch to the saved EL2 version of the register.  */
5870         ri = ri->opaque;
5871         readfn = ri->readfn;
5872     } else {
5873         readfn = ri->orig_readfn;
5874     }
5875     if (readfn == NULL) {
5876         readfn = raw_read;
5877     }
5878     return readfn(env, ri);
5879 }
5880 
5881 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5882                           uint64_t value)
5883 {
5884     CPWriteFn *writefn;
5885 
5886     if (redirect_for_e2h(env)) {
5887         /* Switch to the saved EL2 version of the register.  */
5888         ri = ri->opaque;
5889         writefn = ri->writefn;
5890     } else {
5891         writefn = ri->orig_writefn;
5892     }
5893     if (writefn == NULL) {
5894         writefn = raw_write;
5895     }
5896     writefn(env, ri, value);
5897 }
5898 
5899 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5900 {
5901     struct E2HAlias {
5902         uint32_t src_key, dst_key, new_key;
5903         const char *src_name, *dst_name, *new_name;
5904         bool (*feature)(const ARMISARegisters *id);
5905     };
5906 
5907 #define K(op0, op1, crn, crm, op2) \
5908     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5909 
5910     static const struct E2HAlias aliases[] = {
5911         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5912           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5913         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5914           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5915         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5916           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5917         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5918           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5919         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5920           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5921         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5922           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5923         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5924           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5925         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5926           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5927         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5928           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5929         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5930           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5931         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5932           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5933         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5934           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5935         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5936           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5937         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5938           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5939         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5940           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5941         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5942           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5943 
5944         /*
5945          * Note that redirection of ZCR is mentioned in the description
5946          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5947          * not in the summary table.
5948          */
5949         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5950           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5951 
5952         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5953         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5954     };
5955 #undef K
5956 
5957     size_t i;
5958 
5959     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5960         const struct E2HAlias *a = &aliases[i];
5961         ARMCPRegInfo *src_reg, *dst_reg;
5962 
5963         if (a->feature && !a->feature(&cpu->isar)) {
5964             continue;
5965         }
5966 
5967         src_reg = g_hash_table_lookup(cpu->cp_regs, &a->src_key);
5968         dst_reg = g_hash_table_lookup(cpu->cp_regs, &a->dst_key);
5969         g_assert(src_reg != NULL);
5970         g_assert(dst_reg != NULL);
5971 
5972         /* Cross-compare names to detect typos in the keys.  */
5973         g_assert(strcmp(src_reg->name, a->src_name) == 0);
5974         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
5975 
5976         /* None of the core system registers use opaque; we will.  */
5977         g_assert(src_reg->opaque == NULL);
5978 
5979         /* Create alias before redirection so we dup the right data. */
5980         if (a->new_key) {
5981             ARMCPRegInfo *new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
5982             uint32_t *new_key = g_memdup(&a->new_key, sizeof(uint32_t));
5983             bool ok;
5984 
5985             new_reg->name = a->new_name;
5986             new_reg->type |= ARM_CP_ALIAS;
5987             /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
5988             new_reg->access &= PL2_RW | PL3_RW;
5989 
5990             ok = g_hash_table_insert(cpu->cp_regs, new_key, new_reg);
5991             g_assert(ok);
5992         }
5993 
5994         src_reg->opaque = dst_reg;
5995         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
5996         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
5997         if (!src_reg->raw_readfn) {
5998             src_reg->raw_readfn = raw_read;
5999         }
6000         if (!src_reg->raw_writefn) {
6001             src_reg->raw_writefn = raw_write;
6002         }
6003         src_reg->readfn = el2_e2h_read;
6004         src_reg->writefn = el2_e2h_write;
6005     }
6006 }
6007 #endif
6008 
6009 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
6010                                      bool isread)
6011 {
6012     int cur_el = arm_current_el(env);
6013 
6014     if (cur_el < 2) {
6015         uint64_t hcr = arm_hcr_el2_eff(env);
6016 
6017         if (cur_el == 0) {
6018             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
6019                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
6020                     return CP_ACCESS_TRAP_EL2;
6021                 }
6022             } else {
6023                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
6024                     return CP_ACCESS_TRAP;
6025                 }
6026                 if (hcr & HCR_TID2) {
6027                     return CP_ACCESS_TRAP_EL2;
6028                 }
6029             }
6030         } else if (hcr & HCR_TID2) {
6031             return CP_ACCESS_TRAP_EL2;
6032         }
6033     }
6034 
6035     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
6036         return CP_ACCESS_TRAP_EL2;
6037     }
6038 
6039     return CP_ACCESS_OK;
6040 }
6041 
6042 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
6043                         uint64_t value)
6044 {
6045     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
6046      * read via a bit in OSLSR_EL1.
6047      */
6048     int oslock;
6049 
6050     if (ri->state == ARM_CP_STATE_AA32) {
6051         oslock = (value == 0xC5ACCE55);
6052     } else {
6053         oslock = value & 1;
6054     }
6055 
6056     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
6057 }
6058 
6059 static const ARMCPRegInfo debug_cp_reginfo[] = {
6060     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
6061      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
6062      * unlike DBGDRAR it is never accessible from EL0.
6063      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
6064      * accessor.
6065      */
6066     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
6067       .access = PL0_R, .accessfn = access_tdra,
6068       .type = ARM_CP_CONST, .resetvalue = 0 },
6069     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
6070       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6071       .access = PL1_R, .accessfn = access_tdra,
6072       .type = ARM_CP_CONST, .resetvalue = 0 },
6073     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
6074       .access = PL0_R, .accessfn = access_tdra,
6075       .type = ARM_CP_CONST, .resetvalue = 0 },
6076     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
6077     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
6078       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6079       .access = PL1_RW, .accessfn = access_tda,
6080       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
6081       .resetvalue = 0 },
6082     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
6083      * We don't implement the configurable EL0 access.
6084      */
6085     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
6086       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6087       .type = ARM_CP_ALIAS,
6088       .access = PL1_R, .accessfn = access_tda,
6089       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
6090     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
6091       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
6092       .access = PL1_W, .type = ARM_CP_NO_RAW,
6093       .accessfn = access_tdosa,
6094       .writefn = oslar_write },
6095     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
6096       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
6097       .access = PL1_R, .resetvalue = 10,
6098       .accessfn = access_tdosa,
6099       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6100     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6101     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6102       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6103       .access = PL1_RW, .accessfn = access_tdosa,
6104       .type = ARM_CP_NOP },
6105     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6106      * implement vector catch debug events yet.
6107      */
6108     { .name = "DBGVCR",
6109       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6110       .access = PL1_RW, .accessfn = access_tda,
6111       .type = ARM_CP_NOP },
6112     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6113      * to save and restore a 32-bit guest's DBGVCR)
6114      */
6115     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6116       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6117       .access = PL2_RW, .accessfn = access_tda,
6118       .type = ARM_CP_NOP },
6119     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6120      * Channel but Linux may try to access this register. The 32-bit
6121      * alias is DBGDCCINT.
6122      */
6123     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6124       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6125       .access = PL1_RW, .accessfn = access_tda,
6126       .type = ARM_CP_NOP },
6127     REGINFO_SENTINEL
6128 };
6129 
6130 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6131     /* 64 bit access versions of the (dummy) debug registers */
6132     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6133       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6134     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6135       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6136     REGINFO_SENTINEL
6137 };
6138 
6139 /* Return the exception level to which exceptions should be taken
6140  * via SVEAccessTrap.  If an exception should be routed through
6141  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6142  * take care of raising that exception.
6143  * C.f. the ARM pseudocode function CheckSVEEnabled.
6144  */
6145 int sve_exception_el(CPUARMState *env, int el)
6146 {
6147 #ifndef CONFIG_USER_ONLY
6148     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6149 
6150     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6151         bool disabled = false;
6152 
6153         /* The CPACR.ZEN controls traps to EL1:
6154          * 0, 2 : trap EL0 and EL1 accesses
6155          * 1    : trap only EL0 accesses
6156          * 3    : trap no accesses
6157          */
6158         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
6159             disabled = true;
6160         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
6161             disabled = el == 0;
6162         }
6163         if (disabled) {
6164             /* route_to_el2 */
6165             return hcr_el2 & HCR_TGE ? 2 : 1;
6166         }
6167 
6168         /* Check CPACR.FPEN.  */
6169         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
6170             disabled = true;
6171         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
6172             disabled = el == 0;
6173         }
6174         if (disabled) {
6175             return 0;
6176         }
6177     }
6178 
6179     /* CPTR_EL2.  Since TZ and TFP are positive,
6180      * they will be zero when EL2 is not present.
6181      */
6182     if (el <= 2 && !arm_is_secure_below_el3(env)) {
6183         if (env->cp15.cptr_el[2] & CPTR_TZ) {
6184             return 2;
6185         }
6186         if (env->cp15.cptr_el[2] & CPTR_TFP) {
6187             return 0;
6188         }
6189     }
6190 
6191     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6192     if (arm_feature(env, ARM_FEATURE_EL3)
6193         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6194         return 3;
6195     }
6196 #endif
6197     return 0;
6198 }
6199 
6200 static uint32_t sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6201 {
6202     uint32_t end_len;
6203 
6204     end_len = start_len &= 0xf;
6205     if (!test_bit(start_len, cpu->sve_vq_map)) {
6206         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6207         assert(end_len < start_len);
6208     }
6209     return end_len;
6210 }
6211 
6212 /*
6213  * Given that SVE is enabled, return the vector length for EL.
6214  */
6215 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6216 {
6217     ARMCPU *cpu = env_archcpu(env);
6218     uint32_t zcr_len = cpu->sve_max_vq - 1;
6219 
6220     if (el <= 1) {
6221         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6222     }
6223     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6224         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6225     }
6226     if (arm_feature(env, ARM_FEATURE_EL3)) {
6227         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6228     }
6229 
6230     return sve_zcr_get_valid_len(cpu, zcr_len);
6231 }
6232 
6233 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6234                       uint64_t value)
6235 {
6236     int cur_el = arm_current_el(env);
6237     int old_len = sve_zcr_len_for_el(env, cur_el);
6238     int new_len;
6239 
6240     /* Bits other than [3:0] are RAZ/WI.  */
6241     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6242     raw_write(env, ri, value & 0xf);
6243 
6244     /*
6245      * Because we arrived here, we know both FP and SVE are enabled;
6246      * otherwise we would have trapped access to the ZCR_ELn register.
6247      */
6248     new_len = sve_zcr_len_for_el(env, cur_el);
6249     if (new_len < old_len) {
6250         aarch64_sve_narrow_vq(env, new_len + 1);
6251     }
6252 }
6253 
6254 static const ARMCPRegInfo zcr_el1_reginfo = {
6255     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6256     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6257     .access = PL1_RW, .type = ARM_CP_SVE,
6258     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6259     .writefn = zcr_write, .raw_writefn = raw_write
6260 };
6261 
6262 static const ARMCPRegInfo zcr_el2_reginfo = {
6263     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6264     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6265     .access = PL2_RW, .type = ARM_CP_SVE,
6266     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6267     .writefn = zcr_write, .raw_writefn = raw_write
6268 };
6269 
6270 static const ARMCPRegInfo zcr_no_el2_reginfo = {
6271     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6272     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6273     .access = PL2_RW, .type = ARM_CP_SVE,
6274     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
6275 };
6276 
6277 static const ARMCPRegInfo zcr_el3_reginfo = {
6278     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6279     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6280     .access = PL3_RW, .type = ARM_CP_SVE,
6281     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6282     .writefn = zcr_write, .raw_writefn = raw_write
6283 };
6284 
6285 void hw_watchpoint_update(ARMCPU *cpu, int n)
6286 {
6287     CPUARMState *env = &cpu->env;
6288     vaddr len = 0;
6289     vaddr wvr = env->cp15.dbgwvr[n];
6290     uint64_t wcr = env->cp15.dbgwcr[n];
6291     int mask;
6292     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6293 
6294     if (env->cpu_watchpoint[n]) {
6295         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6296         env->cpu_watchpoint[n] = NULL;
6297     }
6298 
6299     if (!extract64(wcr, 0, 1)) {
6300         /* E bit clear : watchpoint disabled */
6301         return;
6302     }
6303 
6304     switch (extract64(wcr, 3, 2)) {
6305     case 0:
6306         /* LSC 00 is reserved and must behave as if the wp is disabled */
6307         return;
6308     case 1:
6309         flags |= BP_MEM_READ;
6310         break;
6311     case 2:
6312         flags |= BP_MEM_WRITE;
6313         break;
6314     case 3:
6315         flags |= BP_MEM_ACCESS;
6316         break;
6317     }
6318 
6319     /* Attempts to use both MASK and BAS fields simultaneously are
6320      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6321      * thus generating a watchpoint for every byte in the masked region.
6322      */
6323     mask = extract64(wcr, 24, 4);
6324     if (mask == 1 || mask == 2) {
6325         /* Reserved values of MASK; we must act as if the mask value was
6326          * some non-reserved value, or as if the watchpoint were disabled.
6327          * We choose the latter.
6328          */
6329         return;
6330     } else if (mask) {
6331         /* Watchpoint covers an aligned area up to 2GB in size */
6332         len = 1ULL << mask;
6333         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6334          * whether the watchpoint fires when the unmasked bits match; we opt
6335          * to generate the exceptions.
6336          */
6337         wvr &= ~(len - 1);
6338     } else {
6339         /* Watchpoint covers bytes defined by the byte address select bits */
6340         int bas = extract64(wcr, 5, 8);
6341         int basstart;
6342 
6343         if (extract64(wvr, 2, 1)) {
6344             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6345              * ignored, and BAS[3:0] define which bytes to watch.
6346              */
6347             bas &= 0xf;
6348         }
6349 
6350         if (bas == 0) {
6351             /* This must act as if the watchpoint is disabled */
6352             return;
6353         }
6354 
6355         /* The BAS bits are supposed to be programmed to indicate a contiguous
6356          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6357          * we fire for each byte in the word/doubleword addressed by the WVR.
6358          * We choose to ignore any non-zero bits after the first range of 1s.
6359          */
6360         basstart = ctz32(bas);
6361         len = cto32(bas >> basstart);
6362         wvr += basstart;
6363     }
6364 
6365     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6366                           &env->cpu_watchpoint[n]);
6367 }
6368 
6369 void hw_watchpoint_update_all(ARMCPU *cpu)
6370 {
6371     int i;
6372     CPUARMState *env = &cpu->env;
6373 
6374     /* Completely clear out existing QEMU watchpoints and our array, to
6375      * avoid possible stale entries following migration load.
6376      */
6377     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6378     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6379 
6380     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6381         hw_watchpoint_update(cpu, i);
6382     }
6383 }
6384 
6385 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6386                          uint64_t value)
6387 {
6388     ARMCPU *cpu = env_archcpu(env);
6389     int i = ri->crm;
6390 
6391     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
6392      * register reads and behaves as if values written are sign extended.
6393      * Bits [1:0] are RES0.
6394      */
6395     value = sextract64(value, 0, 49) & ~3ULL;
6396 
6397     raw_write(env, ri, value);
6398     hw_watchpoint_update(cpu, i);
6399 }
6400 
6401 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6402                          uint64_t value)
6403 {
6404     ARMCPU *cpu = env_archcpu(env);
6405     int i = ri->crm;
6406 
6407     raw_write(env, ri, value);
6408     hw_watchpoint_update(cpu, i);
6409 }
6410 
6411 void hw_breakpoint_update(ARMCPU *cpu, int n)
6412 {
6413     CPUARMState *env = &cpu->env;
6414     uint64_t bvr = env->cp15.dbgbvr[n];
6415     uint64_t bcr = env->cp15.dbgbcr[n];
6416     vaddr addr;
6417     int bt;
6418     int flags = BP_CPU;
6419 
6420     if (env->cpu_breakpoint[n]) {
6421         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6422         env->cpu_breakpoint[n] = NULL;
6423     }
6424 
6425     if (!extract64(bcr, 0, 1)) {
6426         /* E bit clear : watchpoint disabled */
6427         return;
6428     }
6429 
6430     bt = extract64(bcr, 20, 4);
6431 
6432     switch (bt) {
6433     case 4: /* unlinked address mismatch (reserved if AArch64) */
6434     case 5: /* linked address mismatch (reserved if AArch64) */
6435         qemu_log_mask(LOG_UNIMP,
6436                       "arm: address mismatch breakpoint types not implemented\n");
6437         return;
6438     case 0: /* unlinked address match */
6439     case 1: /* linked address match */
6440     {
6441         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
6442          * we behave as if the register was sign extended. Bits [1:0] are
6443          * RES0. The BAS field is used to allow setting breakpoints on 16
6444          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6445          * a bp will fire if the addresses covered by the bp and the addresses
6446          * covered by the insn overlap but the insn doesn't start at the
6447          * start of the bp address range. We choose to require the insn and
6448          * the bp to have the same address. The constraints on writing to
6449          * BAS enforced in dbgbcr_write mean we have only four cases:
6450          *  0b0000  => no breakpoint
6451          *  0b0011  => breakpoint on addr
6452          *  0b1100  => breakpoint on addr + 2
6453          *  0b1111  => breakpoint on addr
6454          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6455          */
6456         int bas = extract64(bcr, 5, 4);
6457         addr = sextract64(bvr, 0, 49) & ~3ULL;
6458         if (bas == 0) {
6459             return;
6460         }
6461         if (bas == 0xc) {
6462             addr += 2;
6463         }
6464         break;
6465     }
6466     case 2: /* unlinked context ID match */
6467     case 8: /* unlinked VMID match (reserved if no EL2) */
6468     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6469         qemu_log_mask(LOG_UNIMP,
6470                       "arm: unlinked context breakpoint types not implemented\n");
6471         return;
6472     case 9: /* linked VMID match (reserved if no EL2) */
6473     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6474     case 3: /* linked context ID match */
6475     default:
6476         /* We must generate no events for Linked context matches (unless
6477          * they are linked to by some other bp/wp, which is handled in
6478          * updates for the linking bp/wp). We choose to also generate no events
6479          * for reserved values.
6480          */
6481         return;
6482     }
6483 
6484     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6485 }
6486 
6487 void hw_breakpoint_update_all(ARMCPU *cpu)
6488 {
6489     int i;
6490     CPUARMState *env = &cpu->env;
6491 
6492     /* Completely clear out existing QEMU breakpoints and our array, to
6493      * avoid possible stale entries following migration load.
6494      */
6495     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6496     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6497 
6498     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6499         hw_breakpoint_update(cpu, i);
6500     }
6501 }
6502 
6503 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6504                          uint64_t value)
6505 {
6506     ARMCPU *cpu = env_archcpu(env);
6507     int i = ri->crm;
6508 
6509     raw_write(env, ri, value);
6510     hw_breakpoint_update(cpu, i);
6511 }
6512 
6513 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6514                          uint64_t value)
6515 {
6516     ARMCPU *cpu = env_archcpu(env);
6517     int i = ri->crm;
6518 
6519     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6520      * copy of BAS[0].
6521      */
6522     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6523     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6524 
6525     raw_write(env, ri, value);
6526     hw_breakpoint_update(cpu, i);
6527 }
6528 
6529 static void define_debug_regs(ARMCPU *cpu)
6530 {
6531     /* Define v7 and v8 architectural debug registers.
6532      * These are just dummy implementations for now.
6533      */
6534     int i;
6535     int wrps, brps, ctx_cmps;
6536     ARMCPRegInfo dbgdidr = {
6537         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
6538         .access = PL0_R, .accessfn = access_tda,
6539         .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6540     };
6541 
6542     /* Note that all these register fields hold "number of Xs minus 1". */
6543     brps = arm_num_brps(cpu);
6544     wrps = arm_num_wrps(cpu);
6545     ctx_cmps = arm_num_ctx_cmps(cpu);
6546 
6547     assert(ctx_cmps <= brps);
6548 
6549     define_one_arm_cp_reg(cpu, &dbgdidr);
6550     define_arm_cp_regs(cpu, debug_cp_reginfo);
6551 
6552     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6553         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6554     }
6555 
6556     for (i = 0; i < brps; i++) {
6557         ARMCPRegInfo dbgregs[] = {
6558             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6559               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6560               .access = PL1_RW, .accessfn = access_tda,
6561               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6562               .writefn = dbgbvr_write, .raw_writefn = raw_write
6563             },
6564             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6565               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6566               .access = PL1_RW, .accessfn = access_tda,
6567               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6568               .writefn = dbgbcr_write, .raw_writefn = raw_write
6569             },
6570             REGINFO_SENTINEL
6571         };
6572         define_arm_cp_regs(cpu, dbgregs);
6573     }
6574 
6575     for (i = 0; i < wrps; i++) {
6576         ARMCPRegInfo dbgregs[] = {
6577             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6578               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6579               .access = PL1_RW, .accessfn = access_tda,
6580               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6581               .writefn = dbgwvr_write, .raw_writefn = raw_write
6582             },
6583             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6584               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6585               .access = PL1_RW, .accessfn = access_tda,
6586               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6587               .writefn = dbgwcr_write, .raw_writefn = raw_write
6588             },
6589             REGINFO_SENTINEL
6590         };
6591         define_arm_cp_regs(cpu, dbgregs);
6592     }
6593 }
6594 
6595 static void define_pmu_regs(ARMCPU *cpu)
6596 {
6597     /*
6598      * v7 performance monitor control register: same implementor
6599      * field as main ID register, and we implement four counters in
6600      * addition to the cycle count register.
6601      */
6602     unsigned int i, pmcrn = 4;
6603     ARMCPRegInfo pmcr = {
6604         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6605         .access = PL0_RW,
6606         .type = ARM_CP_IO | ARM_CP_ALIAS,
6607         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6608         .accessfn = pmreg_access, .writefn = pmcr_write,
6609         .raw_writefn = raw_write,
6610     };
6611     ARMCPRegInfo pmcr64 = {
6612         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6613         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6614         .access = PL0_RW, .accessfn = pmreg_access,
6615         .type = ARM_CP_IO,
6616         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6617         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6618                       PMCRLC,
6619         .writefn = pmcr_write, .raw_writefn = raw_write,
6620     };
6621     define_one_arm_cp_reg(cpu, &pmcr);
6622     define_one_arm_cp_reg(cpu, &pmcr64);
6623     for (i = 0; i < pmcrn; i++) {
6624         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6625         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6626         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6627         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6628         ARMCPRegInfo pmev_regs[] = {
6629             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6630               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6631               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6632               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6633               .accessfn = pmreg_access },
6634             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6635               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6636               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6637               .type = ARM_CP_IO,
6638               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6639               .raw_readfn = pmevcntr_rawread,
6640               .raw_writefn = pmevcntr_rawwrite },
6641             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6642               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6643               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6644               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6645               .accessfn = pmreg_access },
6646             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6647               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6648               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6649               .type = ARM_CP_IO,
6650               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6651               .raw_writefn = pmevtyper_rawwrite },
6652             REGINFO_SENTINEL
6653         };
6654         define_arm_cp_regs(cpu, pmev_regs);
6655         g_free(pmevcntr_name);
6656         g_free(pmevcntr_el0_name);
6657         g_free(pmevtyper_name);
6658         g_free(pmevtyper_el0_name);
6659     }
6660     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6661         ARMCPRegInfo v81_pmu_regs[] = {
6662             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6663               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6664               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6665               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6666             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6667               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6668               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6669               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6670             REGINFO_SENTINEL
6671         };
6672         define_arm_cp_regs(cpu, v81_pmu_regs);
6673     }
6674     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6675         static const ARMCPRegInfo v84_pmmir = {
6676             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6677             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6678             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6679             .resetvalue = 0
6680         };
6681         define_one_arm_cp_reg(cpu, &v84_pmmir);
6682     }
6683 }
6684 
6685 /* We don't know until after realize whether there's a GICv3
6686  * attached, and that is what registers the gicv3 sysregs.
6687  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6688  * at runtime.
6689  */
6690 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6691 {
6692     ARMCPU *cpu = env_archcpu(env);
6693     uint64_t pfr1 = cpu->id_pfr1;
6694 
6695     if (env->gicv3state) {
6696         pfr1 |= 1 << 28;
6697     }
6698     return pfr1;
6699 }
6700 
6701 #ifndef CONFIG_USER_ONLY
6702 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6703 {
6704     ARMCPU *cpu = env_archcpu(env);
6705     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6706 
6707     if (env->gicv3state) {
6708         pfr0 |= 1 << 24;
6709     }
6710     return pfr0;
6711 }
6712 #endif
6713 
6714 /* Shared logic between LORID and the rest of the LOR* registers.
6715  * Secure state has already been delt with.
6716  */
6717 static CPAccessResult access_lor_ns(CPUARMState *env)
6718 {
6719     int el = arm_current_el(env);
6720 
6721     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6722         return CP_ACCESS_TRAP_EL2;
6723     }
6724     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6725         return CP_ACCESS_TRAP_EL3;
6726     }
6727     return CP_ACCESS_OK;
6728 }
6729 
6730 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
6731                                    bool isread)
6732 {
6733     if (arm_is_secure_below_el3(env)) {
6734         /* Access ok in secure mode.  */
6735         return CP_ACCESS_OK;
6736     }
6737     return access_lor_ns(env);
6738 }
6739 
6740 static CPAccessResult access_lor_other(CPUARMState *env,
6741                                        const ARMCPRegInfo *ri, bool isread)
6742 {
6743     if (arm_is_secure_below_el3(env)) {
6744         /* Access denied in secure mode.  */
6745         return CP_ACCESS_TRAP;
6746     }
6747     return access_lor_ns(env);
6748 }
6749 
6750 /*
6751  * A trivial implementation of ARMv8.1-LOR leaves all of these
6752  * registers fixed at 0, which indicates that there are zero
6753  * supported Limited Ordering regions.
6754  */
6755 static const ARMCPRegInfo lor_reginfo[] = {
6756     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6757       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6758       .access = PL1_RW, .accessfn = access_lor_other,
6759       .type = ARM_CP_CONST, .resetvalue = 0 },
6760     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6761       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6762       .access = PL1_RW, .accessfn = access_lor_other,
6763       .type = ARM_CP_CONST, .resetvalue = 0 },
6764     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6765       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6766       .access = PL1_RW, .accessfn = access_lor_other,
6767       .type = ARM_CP_CONST, .resetvalue = 0 },
6768     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6769       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6770       .access = PL1_RW, .accessfn = access_lor_other,
6771       .type = ARM_CP_CONST, .resetvalue = 0 },
6772     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6773       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6774       .access = PL1_R, .accessfn = access_lorid,
6775       .type = ARM_CP_CONST, .resetvalue = 0 },
6776     REGINFO_SENTINEL
6777 };
6778 
6779 #ifdef TARGET_AARCH64
6780 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6781                                    bool isread)
6782 {
6783     int el = arm_current_el(env);
6784 
6785     if (el < 2 &&
6786         arm_feature(env, ARM_FEATURE_EL2) &&
6787         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6788         return CP_ACCESS_TRAP_EL2;
6789     }
6790     if (el < 3 &&
6791         arm_feature(env, ARM_FEATURE_EL3) &&
6792         !(env->cp15.scr_el3 & SCR_APK)) {
6793         return CP_ACCESS_TRAP_EL3;
6794     }
6795     return CP_ACCESS_OK;
6796 }
6797 
6798 static const ARMCPRegInfo pauth_reginfo[] = {
6799     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6800       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6801       .access = PL1_RW, .accessfn = access_pauth,
6802       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6803     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6804       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6805       .access = PL1_RW, .accessfn = access_pauth,
6806       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6807     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6808       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6809       .access = PL1_RW, .accessfn = access_pauth,
6810       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6811     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6812       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6813       .access = PL1_RW, .accessfn = access_pauth,
6814       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6815     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6816       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6817       .access = PL1_RW, .accessfn = access_pauth,
6818       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6819     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6820       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6821       .access = PL1_RW, .accessfn = access_pauth,
6822       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6823     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6824       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6825       .access = PL1_RW, .accessfn = access_pauth,
6826       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6827     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6828       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6829       .access = PL1_RW, .accessfn = access_pauth,
6830       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6831     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6832       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6833       .access = PL1_RW, .accessfn = access_pauth,
6834       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6835     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6836       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6837       .access = PL1_RW, .accessfn = access_pauth,
6838       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6839     REGINFO_SENTINEL
6840 };
6841 
6842 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
6843 {
6844     Error *err = NULL;
6845     uint64_t ret;
6846 
6847     /* Success sets NZCV = 0000.  */
6848     env->NF = env->CF = env->VF = 0, env->ZF = 1;
6849 
6850     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
6851         /*
6852          * ??? Failed, for unknown reasons in the crypto subsystem.
6853          * The best we can do is log the reason and return the
6854          * timed-out indication to the guest.  There is no reason
6855          * we know to expect this failure to be transitory, so the
6856          * guest may well hang retrying the operation.
6857          */
6858         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
6859                       ri->name, error_get_pretty(err));
6860         error_free(err);
6861 
6862         env->ZF = 0; /* NZCF = 0100 */
6863         return 0;
6864     }
6865     return ret;
6866 }
6867 
6868 /* We do not support re-seeding, so the two registers operate the same.  */
6869 static const ARMCPRegInfo rndr_reginfo[] = {
6870     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
6871       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6872       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
6873       .access = PL0_R, .readfn = rndr_readfn },
6874     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
6875       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6876       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
6877       .access = PL0_R, .readfn = rndr_readfn },
6878     REGINFO_SENTINEL
6879 };
6880 
6881 #ifndef CONFIG_USER_ONLY
6882 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
6883                           uint64_t value)
6884 {
6885     ARMCPU *cpu = env_archcpu(env);
6886     /* CTR_EL0 System register -> DminLine, bits [19:16] */
6887     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
6888     uint64_t vaddr_in = (uint64_t) value;
6889     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
6890     void *haddr;
6891     int mem_idx = cpu_mmu_index(env, false);
6892 
6893     /* This won't be crossing page boundaries */
6894     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
6895     if (haddr) {
6896 
6897         ram_addr_t offset;
6898         MemoryRegion *mr;
6899 
6900         /* RCU lock is already being held */
6901         mr = memory_region_from_host(haddr, &offset);
6902 
6903         if (mr) {
6904             memory_region_do_writeback(mr, offset, dline_size);
6905         }
6906     }
6907 }
6908 
6909 static const ARMCPRegInfo dcpop_reg[] = {
6910     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
6911       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
6912       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6913       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6914     REGINFO_SENTINEL
6915 };
6916 
6917 static const ARMCPRegInfo dcpodp_reg[] = {
6918     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
6919       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
6920       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6921       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6922     REGINFO_SENTINEL
6923 };
6924 #endif /*CONFIG_USER_ONLY*/
6925 
6926 #endif
6927 
6928 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
6929                                      bool isread)
6930 {
6931     int el = arm_current_el(env);
6932 
6933     if (el == 0) {
6934         uint64_t sctlr = arm_sctlr(env, el);
6935         if (!(sctlr & SCTLR_EnRCTX)) {
6936             return CP_ACCESS_TRAP;
6937         }
6938     } else if (el == 1) {
6939         uint64_t hcr = arm_hcr_el2_eff(env);
6940         if (hcr & HCR_NV) {
6941             return CP_ACCESS_TRAP_EL2;
6942         }
6943     }
6944     return CP_ACCESS_OK;
6945 }
6946 
6947 static const ARMCPRegInfo predinv_reginfo[] = {
6948     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
6949       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
6950       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6951     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
6952       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
6953       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6954     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
6955       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
6956       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6957     /*
6958      * Note the AArch32 opcodes have a different OPC1.
6959      */
6960     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
6961       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
6962       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6963     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
6964       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
6965       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6966     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
6967       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
6968       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6969     REGINFO_SENTINEL
6970 };
6971 
6972 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
6973 {
6974     /* Read the high 32 bits of the current CCSIDR */
6975     return extract64(ccsidr_read(env, ri), 32, 32);
6976 }
6977 
6978 static const ARMCPRegInfo ccsidr2_reginfo[] = {
6979     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
6980       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
6981       .access = PL1_R,
6982       .accessfn = access_aa64_tid2,
6983       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
6984     REGINFO_SENTINEL
6985 };
6986 
6987 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
6988                                        bool isread)
6989 {
6990     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
6991         return CP_ACCESS_TRAP_EL2;
6992     }
6993 
6994     return CP_ACCESS_OK;
6995 }
6996 
6997 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
6998                                        bool isread)
6999 {
7000     if (arm_feature(env, ARM_FEATURE_V8)) {
7001         return access_aa64_tid3(env, ri, isread);
7002     }
7003 
7004     return CP_ACCESS_OK;
7005 }
7006 
7007 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7008                                      bool isread)
7009 {
7010     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7011         return CP_ACCESS_TRAP_EL2;
7012     }
7013 
7014     return CP_ACCESS_OK;
7015 }
7016 
7017 static const ARMCPRegInfo jazelle_regs[] = {
7018     { .name = "JIDR",
7019       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7020       .access = PL1_R, .accessfn = access_jazelle,
7021       .type = ARM_CP_CONST, .resetvalue = 0 },
7022     { .name = "JOSCR",
7023       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7024       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7025     { .name = "JMCR",
7026       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7027       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7028     REGINFO_SENTINEL
7029 };
7030 
7031 static const ARMCPRegInfo vhe_reginfo[] = {
7032     { .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7033       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7034       .access = PL2_RW,
7035       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2]) },
7036     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7037       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7038       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7039       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7040 #ifndef CONFIG_USER_ONLY
7041     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7042       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7043       .fieldoffset =
7044         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7045       .type = ARM_CP_IO, .access = PL2_RW,
7046       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7047     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7048       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7049       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7050       .resetfn = gt_hv_timer_reset,
7051       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7052     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7053       .type = ARM_CP_IO,
7054       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7055       .access = PL2_RW,
7056       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7057       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7058     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7059       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7060       .type = ARM_CP_IO | ARM_CP_ALIAS,
7061       .access = PL2_RW, .accessfn = e2h_access,
7062       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7063       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7064     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7065       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7066       .type = ARM_CP_IO | ARM_CP_ALIAS,
7067       .access = PL2_RW, .accessfn = e2h_access,
7068       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7069       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7070     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7071       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7072       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7073       .access = PL2_RW, .accessfn = e2h_access,
7074       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7075     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7076       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7077       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7078       .access = PL2_RW, .accessfn = e2h_access,
7079       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7080     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7081       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7082       .type = ARM_CP_IO | ARM_CP_ALIAS,
7083       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7084       .access = PL2_RW, .accessfn = e2h_access,
7085       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7086     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7087       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7088       .type = ARM_CP_IO | ARM_CP_ALIAS,
7089       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7090       .access = PL2_RW, .accessfn = e2h_access,
7091       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7092 #endif
7093     REGINFO_SENTINEL
7094 };
7095 
7096 #ifndef CONFIG_USER_ONLY
7097 static const ARMCPRegInfo ats1e1_reginfo[] = {
7098     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7099       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7100       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7101       .writefn = ats_write64 },
7102     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7103       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7104       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7105       .writefn = ats_write64 },
7106     REGINFO_SENTINEL
7107 };
7108 
7109 static const ARMCPRegInfo ats1cp_reginfo[] = {
7110     { .name = "ATS1CPRP",
7111       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7112       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7113       .writefn = ats_write },
7114     { .name = "ATS1CPWP",
7115       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7116       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7117       .writefn = ats_write },
7118     REGINFO_SENTINEL
7119 };
7120 #endif
7121 
7122 /*
7123  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7124  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7125  * is non-zero, which is never for ARMv7, optionally in ARMv8
7126  * and mandatorily for ARMv8.2 and up.
7127  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7128  * implementation is RAZ/WI we can ignore this detail, as we
7129  * do for ACTLR.
7130  */
7131 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7132     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7133       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7134       .access = PL1_RW, .accessfn = access_tacr,
7135       .type = ARM_CP_CONST, .resetvalue = 0 },
7136     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7137       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7138       .access = PL2_RW, .type = ARM_CP_CONST,
7139       .resetvalue = 0 },
7140     REGINFO_SENTINEL
7141 };
7142 
7143 void register_cp_regs_for_features(ARMCPU *cpu)
7144 {
7145     /* Register all the coprocessor registers based on feature bits */
7146     CPUARMState *env = &cpu->env;
7147     if (arm_feature(env, ARM_FEATURE_M)) {
7148         /* M profile has no coprocessor registers */
7149         return;
7150     }
7151 
7152     define_arm_cp_regs(cpu, cp_reginfo);
7153     if (!arm_feature(env, ARM_FEATURE_V8)) {
7154         /* Must go early as it is full of wildcards that may be
7155          * overridden by later definitions.
7156          */
7157         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7158     }
7159 
7160     if (arm_feature(env, ARM_FEATURE_V6)) {
7161         /* The ID registers all have impdef reset values */
7162         ARMCPRegInfo v6_idregs[] = {
7163             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7164               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7165               .access = PL1_R, .type = ARM_CP_CONST,
7166               .accessfn = access_aa32_tid3,
7167               .resetvalue = cpu->id_pfr0 },
7168             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7169              * the value of the GIC field until after we define these regs.
7170              */
7171             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7172               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7173               .access = PL1_R, .type = ARM_CP_NO_RAW,
7174               .accessfn = access_aa32_tid3,
7175               .readfn = id_pfr1_read,
7176               .writefn = arm_cp_write_ignore },
7177             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7178               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7179               .access = PL1_R, .type = ARM_CP_CONST,
7180               .accessfn = access_aa32_tid3,
7181               .resetvalue = cpu->isar.id_dfr0 },
7182             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7183               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7184               .access = PL1_R, .type = ARM_CP_CONST,
7185               .accessfn = access_aa32_tid3,
7186               .resetvalue = cpu->id_afr0 },
7187             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7188               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7189               .access = PL1_R, .type = ARM_CP_CONST,
7190               .accessfn = access_aa32_tid3,
7191               .resetvalue = cpu->isar.id_mmfr0 },
7192             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7193               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7194               .access = PL1_R, .type = ARM_CP_CONST,
7195               .accessfn = access_aa32_tid3,
7196               .resetvalue = cpu->isar.id_mmfr1 },
7197             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7198               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7199               .access = PL1_R, .type = ARM_CP_CONST,
7200               .accessfn = access_aa32_tid3,
7201               .resetvalue = cpu->isar.id_mmfr2 },
7202             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7203               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7204               .access = PL1_R, .type = ARM_CP_CONST,
7205               .accessfn = access_aa32_tid3,
7206               .resetvalue = cpu->isar.id_mmfr3 },
7207             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7208               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7209               .access = PL1_R, .type = ARM_CP_CONST,
7210               .accessfn = access_aa32_tid3,
7211               .resetvalue = cpu->isar.id_isar0 },
7212             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7213               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7214               .access = PL1_R, .type = ARM_CP_CONST,
7215               .accessfn = access_aa32_tid3,
7216               .resetvalue = cpu->isar.id_isar1 },
7217             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7218               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7219               .access = PL1_R, .type = ARM_CP_CONST,
7220               .accessfn = access_aa32_tid3,
7221               .resetvalue = cpu->isar.id_isar2 },
7222             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7223               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7224               .access = PL1_R, .type = ARM_CP_CONST,
7225               .accessfn = access_aa32_tid3,
7226               .resetvalue = cpu->isar.id_isar3 },
7227             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7228               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7229               .access = PL1_R, .type = ARM_CP_CONST,
7230               .accessfn = access_aa32_tid3,
7231               .resetvalue = cpu->isar.id_isar4 },
7232             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7233               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7234               .access = PL1_R, .type = ARM_CP_CONST,
7235               .accessfn = access_aa32_tid3,
7236               .resetvalue = cpu->isar.id_isar5 },
7237             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7238               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7239               .access = PL1_R, .type = ARM_CP_CONST,
7240               .accessfn = access_aa32_tid3,
7241               .resetvalue = cpu->isar.id_mmfr4 },
7242             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7243               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7244               .access = PL1_R, .type = ARM_CP_CONST,
7245               .accessfn = access_aa32_tid3,
7246               .resetvalue = cpu->isar.id_isar6 },
7247             REGINFO_SENTINEL
7248         };
7249         define_arm_cp_regs(cpu, v6_idregs);
7250         define_arm_cp_regs(cpu, v6_cp_reginfo);
7251     } else {
7252         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7253     }
7254     if (arm_feature(env, ARM_FEATURE_V6K)) {
7255         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7256     }
7257     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7258         !arm_feature(env, ARM_FEATURE_PMSA)) {
7259         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7260     }
7261     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7262         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7263     }
7264     if (arm_feature(env, ARM_FEATURE_V7)) {
7265         ARMCPRegInfo clidr = {
7266             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7267             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7268             .access = PL1_R, .type = ARM_CP_CONST,
7269             .accessfn = access_aa64_tid2,
7270             .resetvalue = cpu->clidr
7271         };
7272         define_one_arm_cp_reg(cpu, &clidr);
7273         define_arm_cp_regs(cpu, v7_cp_reginfo);
7274         define_debug_regs(cpu);
7275         define_pmu_regs(cpu);
7276     } else {
7277         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7278     }
7279     if (arm_feature(env, ARM_FEATURE_V8)) {
7280         /* AArch64 ID registers, which all have impdef reset values.
7281          * Note that within the ID register ranges the unused slots
7282          * must all RAZ, not UNDEF; future architecture versions may
7283          * define new registers here.
7284          */
7285         ARMCPRegInfo v8_idregs[] = {
7286             /*
7287              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7288              * emulation because we don't know the right value for the
7289              * GIC field until after we define these regs.
7290              */
7291             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7292               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7293               .access = PL1_R,
7294 #ifdef CONFIG_USER_ONLY
7295               .type = ARM_CP_CONST,
7296               .resetvalue = cpu->isar.id_aa64pfr0
7297 #else
7298               .type = ARM_CP_NO_RAW,
7299               .accessfn = access_aa64_tid3,
7300               .readfn = id_aa64pfr0_read,
7301               .writefn = arm_cp_write_ignore
7302 #endif
7303             },
7304             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7305               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7306               .access = PL1_R, .type = ARM_CP_CONST,
7307               .accessfn = access_aa64_tid3,
7308               .resetvalue = cpu->isar.id_aa64pfr1},
7309             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7310               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7311               .access = PL1_R, .type = ARM_CP_CONST,
7312               .accessfn = access_aa64_tid3,
7313               .resetvalue = 0 },
7314             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7315               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7316               .access = PL1_R, .type = ARM_CP_CONST,
7317               .accessfn = access_aa64_tid3,
7318               .resetvalue = 0 },
7319             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7320               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7321               .access = PL1_R, .type = ARM_CP_CONST,
7322               .accessfn = access_aa64_tid3,
7323               /* At present, only SVEver == 0 is defined anyway.  */
7324               .resetvalue = 0 },
7325             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7326               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7327               .access = PL1_R, .type = ARM_CP_CONST,
7328               .accessfn = access_aa64_tid3,
7329               .resetvalue = 0 },
7330             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7331               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7332               .access = PL1_R, .type = ARM_CP_CONST,
7333               .accessfn = access_aa64_tid3,
7334               .resetvalue = 0 },
7335             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7336               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7337               .access = PL1_R, .type = ARM_CP_CONST,
7338               .accessfn = access_aa64_tid3,
7339               .resetvalue = 0 },
7340             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7341               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7342               .access = PL1_R, .type = ARM_CP_CONST,
7343               .accessfn = access_aa64_tid3,
7344               .resetvalue = cpu->isar.id_aa64dfr0 },
7345             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7346               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7347               .access = PL1_R, .type = ARM_CP_CONST,
7348               .accessfn = access_aa64_tid3,
7349               .resetvalue = cpu->isar.id_aa64dfr1 },
7350             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7351               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7352               .access = PL1_R, .type = ARM_CP_CONST,
7353               .accessfn = access_aa64_tid3,
7354               .resetvalue = 0 },
7355             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7356               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7357               .access = PL1_R, .type = ARM_CP_CONST,
7358               .accessfn = access_aa64_tid3,
7359               .resetvalue = 0 },
7360             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7361               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7362               .access = PL1_R, .type = ARM_CP_CONST,
7363               .accessfn = access_aa64_tid3,
7364               .resetvalue = cpu->id_aa64afr0 },
7365             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7366               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7367               .access = PL1_R, .type = ARM_CP_CONST,
7368               .accessfn = access_aa64_tid3,
7369               .resetvalue = cpu->id_aa64afr1 },
7370             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7371               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7372               .access = PL1_R, .type = ARM_CP_CONST,
7373               .accessfn = access_aa64_tid3,
7374               .resetvalue = 0 },
7375             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7376               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7377               .access = PL1_R, .type = ARM_CP_CONST,
7378               .accessfn = access_aa64_tid3,
7379               .resetvalue = 0 },
7380             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7381               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7382               .access = PL1_R, .type = ARM_CP_CONST,
7383               .accessfn = access_aa64_tid3,
7384               .resetvalue = cpu->isar.id_aa64isar0 },
7385             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7386               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7387               .access = PL1_R, .type = ARM_CP_CONST,
7388               .accessfn = access_aa64_tid3,
7389               .resetvalue = cpu->isar.id_aa64isar1 },
7390             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7391               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7392               .access = PL1_R, .type = ARM_CP_CONST,
7393               .accessfn = access_aa64_tid3,
7394               .resetvalue = 0 },
7395             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7396               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7397               .access = PL1_R, .type = ARM_CP_CONST,
7398               .accessfn = access_aa64_tid3,
7399               .resetvalue = 0 },
7400             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7401               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7402               .access = PL1_R, .type = ARM_CP_CONST,
7403               .accessfn = access_aa64_tid3,
7404               .resetvalue = 0 },
7405             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7406               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7407               .access = PL1_R, .type = ARM_CP_CONST,
7408               .accessfn = access_aa64_tid3,
7409               .resetvalue = 0 },
7410             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7411               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7412               .access = PL1_R, .type = ARM_CP_CONST,
7413               .accessfn = access_aa64_tid3,
7414               .resetvalue = 0 },
7415             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7416               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7417               .access = PL1_R, .type = ARM_CP_CONST,
7418               .accessfn = access_aa64_tid3,
7419               .resetvalue = 0 },
7420             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7421               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7422               .access = PL1_R, .type = ARM_CP_CONST,
7423               .accessfn = access_aa64_tid3,
7424               .resetvalue = cpu->isar.id_aa64mmfr0 },
7425             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7426               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7427               .access = PL1_R, .type = ARM_CP_CONST,
7428               .accessfn = access_aa64_tid3,
7429               .resetvalue = cpu->isar.id_aa64mmfr1 },
7430             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7431               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7432               .access = PL1_R, .type = ARM_CP_CONST,
7433               .accessfn = access_aa64_tid3,
7434               .resetvalue = cpu->isar.id_aa64mmfr2 },
7435             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7436               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7437               .access = PL1_R, .type = ARM_CP_CONST,
7438               .accessfn = access_aa64_tid3,
7439               .resetvalue = 0 },
7440             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7441               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7442               .access = PL1_R, .type = ARM_CP_CONST,
7443               .accessfn = access_aa64_tid3,
7444               .resetvalue = 0 },
7445             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7446               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7447               .access = PL1_R, .type = ARM_CP_CONST,
7448               .accessfn = access_aa64_tid3,
7449               .resetvalue = 0 },
7450             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7451               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7452               .access = PL1_R, .type = ARM_CP_CONST,
7453               .accessfn = access_aa64_tid3,
7454               .resetvalue = 0 },
7455             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7456               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7457               .access = PL1_R, .type = ARM_CP_CONST,
7458               .accessfn = access_aa64_tid3,
7459               .resetvalue = 0 },
7460             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7461               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7462               .access = PL1_R, .type = ARM_CP_CONST,
7463               .accessfn = access_aa64_tid3,
7464               .resetvalue = cpu->isar.mvfr0 },
7465             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7466               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7467               .access = PL1_R, .type = ARM_CP_CONST,
7468               .accessfn = access_aa64_tid3,
7469               .resetvalue = cpu->isar.mvfr1 },
7470             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7471               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7472               .access = PL1_R, .type = ARM_CP_CONST,
7473               .accessfn = access_aa64_tid3,
7474               .resetvalue = cpu->isar.mvfr2 },
7475             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7476               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7477               .access = PL1_R, .type = ARM_CP_CONST,
7478               .accessfn = access_aa64_tid3,
7479               .resetvalue = 0 },
7480             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7481               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7482               .access = PL1_R, .type = ARM_CP_CONST,
7483               .accessfn = access_aa64_tid3,
7484               .resetvalue = 0 },
7485             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7486               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7487               .access = PL1_R, .type = ARM_CP_CONST,
7488               .accessfn = access_aa64_tid3,
7489               .resetvalue = 0 },
7490             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7491               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7492               .access = PL1_R, .type = ARM_CP_CONST,
7493               .accessfn = access_aa64_tid3,
7494               .resetvalue = 0 },
7495             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7496               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7497               .access = PL1_R, .type = ARM_CP_CONST,
7498               .accessfn = access_aa64_tid3,
7499               .resetvalue = 0 },
7500             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7501               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7502               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7503               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7504             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7505               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7506               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7507               .resetvalue = cpu->pmceid0 },
7508             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7509               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7510               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7511               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7512             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7513               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7514               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7515               .resetvalue = cpu->pmceid1 },
7516             REGINFO_SENTINEL
7517         };
7518 #ifdef CONFIG_USER_ONLY
7519         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7520             { .name = "ID_AA64PFR0_EL1",
7521               .exported_bits = 0x000f000f00ff0000,
7522               .fixed_bits    = 0x0000000000000011 },
7523             { .name = "ID_AA64PFR1_EL1",
7524               .exported_bits = 0x00000000000000f0 },
7525             { .name = "ID_AA64PFR*_EL1_RESERVED",
7526               .is_glob = true                     },
7527             { .name = "ID_AA64ZFR0_EL1"           },
7528             { .name = "ID_AA64MMFR0_EL1",
7529               .fixed_bits    = 0x00000000ff000000 },
7530             { .name = "ID_AA64MMFR1_EL1"          },
7531             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7532               .is_glob = true                     },
7533             { .name = "ID_AA64DFR0_EL1",
7534               .fixed_bits    = 0x0000000000000006 },
7535             { .name = "ID_AA64DFR1_EL1"           },
7536             { .name = "ID_AA64DFR*_EL1_RESERVED",
7537               .is_glob = true                     },
7538             { .name = "ID_AA64AFR*",
7539               .is_glob = true                     },
7540             { .name = "ID_AA64ISAR0_EL1",
7541               .exported_bits = 0x00fffffff0fffff0 },
7542             { .name = "ID_AA64ISAR1_EL1",
7543               .exported_bits = 0x000000f0ffffffff },
7544             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7545               .is_glob = true                     },
7546             REGUSERINFO_SENTINEL
7547         };
7548         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7549 #endif
7550         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7551         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7552             !arm_feature(env, ARM_FEATURE_EL2)) {
7553             ARMCPRegInfo rvbar = {
7554                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7555                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7556                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
7557             };
7558             define_one_arm_cp_reg(cpu, &rvbar);
7559         }
7560         define_arm_cp_regs(cpu, v8_idregs);
7561         define_arm_cp_regs(cpu, v8_cp_reginfo);
7562     }
7563     if (arm_feature(env, ARM_FEATURE_EL2)) {
7564         uint64_t vmpidr_def = mpidr_read_val(env);
7565         ARMCPRegInfo vpidr_regs[] = {
7566             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7567               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7568               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7569               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
7570               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7571             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7572               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7573               .access = PL2_RW, .resetvalue = cpu->midr,
7574               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7575             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7576               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7577               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7578               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
7579               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7580             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7581               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7582               .access = PL2_RW,
7583               .resetvalue = vmpidr_def,
7584               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7585             REGINFO_SENTINEL
7586         };
7587         define_arm_cp_regs(cpu, vpidr_regs);
7588         define_arm_cp_regs(cpu, el2_cp_reginfo);
7589         if (arm_feature(env, ARM_FEATURE_V8)) {
7590             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7591         }
7592         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7593         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7594             ARMCPRegInfo rvbar = {
7595                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
7596                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
7597                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
7598             };
7599             define_one_arm_cp_reg(cpu, &rvbar);
7600         }
7601     } else {
7602         /* If EL2 is missing but higher ELs are enabled, we need to
7603          * register the no_el2 reginfos.
7604          */
7605         if (arm_feature(env, ARM_FEATURE_EL3)) {
7606             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
7607              * of MIDR_EL1 and MPIDR_EL1.
7608              */
7609             ARMCPRegInfo vpidr_regs[] = {
7610                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7611                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7612                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
7613                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
7614                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7615                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7616                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7617                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
7618                   .type = ARM_CP_NO_RAW,
7619                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
7620                 REGINFO_SENTINEL
7621             };
7622             define_arm_cp_regs(cpu, vpidr_regs);
7623             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
7624             if (arm_feature(env, ARM_FEATURE_V8)) {
7625                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
7626             }
7627         }
7628     }
7629     if (arm_feature(env, ARM_FEATURE_EL3)) {
7630         define_arm_cp_regs(cpu, el3_cp_reginfo);
7631         ARMCPRegInfo el3_regs[] = {
7632             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
7633               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
7634               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
7635             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
7636               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
7637               .access = PL3_RW,
7638               .raw_writefn = raw_write, .writefn = sctlr_write,
7639               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
7640               .resetvalue = cpu->reset_sctlr },
7641             REGINFO_SENTINEL
7642         };
7643 
7644         define_arm_cp_regs(cpu, el3_regs);
7645     }
7646     /* The behaviour of NSACR is sufficiently various that we don't
7647      * try to describe it in a single reginfo:
7648      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
7649      *     reads as constant 0xc00 from NS EL1 and NS EL2
7650      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
7651      *  if v7 without EL3, register doesn't exist
7652      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
7653      */
7654     if (arm_feature(env, ARM_FEATURE_EL3)) {
7655         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7656             ARMCPRegInfo nsacr = {
7657                 .name = "NSACR", .type = ARM_CP_CONST,
7658                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7659                 .access = PL1_RW, .accessfn = nsacr_access,
7660                 .resetvalue = 0xc00
7661             };
7662             define_one_arm_cp_reg(cpu, &nsacr);
7663         } else {
7664             ARMCPRegInfo nsacr = {
7665                 .name = "NSACR",
7666                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7667                 .access = PL3_RW | PL1_R,
7668                 .resetvalue = 0,
7669                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
7670             };
7671             define_one_arm_cp_reg(cpu, &nsacr);
7672         }
7673     } else {
7674         if (arm_feature(env, ARM_FEATURE_V8)) {
7675             ARMCPRegInfo nsacr = {
7676                 .name = "NSACR", .type = ARM_CP_CONST,
7677                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7678                 .access = PL1_R,
7679                 .resetvalue = 0xc00
7680             };
7681             define_one_arm_cp_reg(cpu, &nsacr);
7682         }
7683     }
7684 
7685     if (arm_feature(env, ARM_FEATURE_PMSA)) {
7686         if (arm_feature(env, ARM_FEATURE_V6)) {
7687             /* PMSAv6 not implemented */
7688             assert(arm_feature(env, ARM_FEATURE_V7));
7689             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7690             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
7691         } else {
7692             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
7693         }
7694     } else {
7695         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7696         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
7697         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
7698         if (cpu_isar_feature(aa32_hpd, cpu)) {
7699             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
7700         }
7701     }
7702     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
7703         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
7704     }
7705     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
7706         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
7707     }
7708     if (arm_feature(env, ARM_FEATURE_VAPA)) {
7709         define_arm_cp_regs(cpu, vapa_cp_reginfo);
7710     }
7711     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
7712         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
7713     }
7714     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
7715         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
7716     }
7717     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
7718         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
7719     }
7720     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
7721         define_arm_cp_regs(cpu, omap_cp_reginfo);
7722     }
7723     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
7724         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
7725     }
7726     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7727         define_arm_cp_regs(cpu, xscale_cp_reginfo);
7728     }
7729     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
7730         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
7731     }
7732     if (arm_feature(env, ARM_FEATURE_LPAE)) {
7733         define_arm_cp_regs(cpu, lpae_cp_reginfo);
7734     }
7735     if (cpu_isar_feature(aa32_jazelle, cpu)) {
7736         define_arm_cp_regs(cpu, jazelle_regs);
7737     }
7738     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
7739      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
7740      * be read-only (ie write causes UNDEF exception).
7741      */
7742     {
7743         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
7744             /* Pre-v8 MIDR space.
7745              * Note that the MIDR isn't a simple constant register because
7746              * of the TI925 behaviour where writes to another register can
7747              * cause the MIDR value to change.
7748              *
7749              * Unimplemented registers in the c15 0 0 0 space default to
7750              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
7751              * and friends override accordingly.
7752              */
7753             { .name = "MIDR",
7754               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
7755               .access = PL1_R, .resetvalue = cpu->midr,
7756               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
7757               .readfn = midr_read,
7758               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7759               .type = ARM_CP_OVERRIDE },
7760             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
7761             { .name = "DUMMY",
7762               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
7763               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7764             { .name = "DUMMY",
7765               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
7766               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7767             { .name = "DUMMY",
7768               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
7769               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7770             { .name = "DUMMY",
7771               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
7772               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7773             { .name = "DUMMY",
7774               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
7775               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7776             REGINFO_SENTINEL
7777         };
7778         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
7779             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
7780               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
7781               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
7782               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7783               .readfn = midr_read },
7784             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
7785             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7786               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
7787               .access = PL1_R, .resetvalue = cpu->midr },
7788             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7789               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
7790               .access = PL1_R, .resetvalue = cpu->midr },
7791             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
7792               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
7793               .access = PL1_R,
7794               .accessfn = access_aa64_tid1,
7795               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
7796             REGINFO_SENTINEL
7797         };
7798         ARMCPRegInfo id_cp_reginfo[] = {
7799             /* These are common to v8 and pre-v8 */
7800             { .name = "CTR",
7801               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
7802               .access = PL1_R, .accessfn = ctr_el0_access,
7803               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
7804             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
7805               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
7806               .access = PL0_R, .accessfn = ctr_el0_access,
7807               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
7808             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
7809             { .name = "TCMTR",
7810               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
7811               .access = PL1_R,
7812               .accessfn = access_aa32_tid1,
7813               .type = ARM_CP_CONST, .resetvalue = 0 },
7814             REGINFO_SENTINEL
7815         };
7816         /* TLBTR is specific to VMSA */
7817         ARMCPRegInfo id_tlbtr_reginfo = {
7818               .name = "TLBTR",
7819               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
7820               .access = PL1_R,
7821               .accessfn = access_aa32_tid1,
7822               .type = ARM_CP_CONST, .resetvalue = 0,
7823         };
7824         /* MPUIR is specific to PMSA V6+ */
7825         ARMCPRegInfo id_mpuir_reginfo = {
7826               .name = "MPUIR",
7827               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
7828               .access = PL1_R, .type = ARM_CP_CONST,
7829               .resetvalue = cpu->pmsav7_dregion << 8
7830         };
7831         ARMCPRegInfo crn0_wi_reginfo = {
7832             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
7833             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
7834             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
7835         };
7836 #ifdef CONFIG_USER_ONLY
7837         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
7838             { .name = "MIDR_EL1",
7839               .exported_bits = 0x00000000ffffffff },
7840             { .name = "REVIDR_EL1"                },
7841             REGUSERINFO_SENTINEL
7842         };
7843         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
7844 #endif
7845         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
7846             arm_feature(env, ARM_FEATURE_STRONGARM)) {
7847             ARMCPRegInfo *r;
7848             /* Register the blanket "writes ignored" value first to cover the
7849              * whole space. Then update the specific ID registers to allow write
7850              * access, so that they ignore writes rather than causing them to
7851              * UNDEF.
7852              */
7853             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
7854             for (r = id_pre_v8_midr_cp_reginfo;
7855                  r->type != ARM_CP_SENTINEL; r++) {
7856                 r->access = PL1_RW;
7857             }
7858             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
7859                 r->access = PL1_RW;
7860             }
7861             id_mpuir_reginfo.access = PL1_RW;
7862             id_tlbtr_reginfo.access = PL1_RW;
7863         }
7864         if (arm_feature(env, ARM_FEATURE_V8)) {
7865             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
7866         } else {
7867             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
7868         }
7869         define_arm_cp_regs(cpu, id_cp_reginfo);
7870         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
7871             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
7872         } else if (arm_feature(env, ARM_FEATURE_V7)) {
7873             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
7874         }
7875     }
7876 
7877     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
7878         ARMCPRegInfo mpidr_cp_reginfo[] = {
7879             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
7880               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
7881               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
7882             REGINFO_SENTINEL
7883         };
7884 #ifdef CONFIG_USER_ONLY
7885         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
7886             { .name = "MPIDR_EL1",
7887               .fixed_bits = 0x0000000080000000 },
7888             REGUSERINFO_SENTINEL
7889         };
7890         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
7891 #endif
7892         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
7893     }
7894 
7895     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
7896         ARMCPRegInfo auxcr_reginfo[] = {
7897             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
7898               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
7899               .access = PL1_RW, .accessfn = access_tacr,
7900               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
7901             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
7902               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
7903               .access = PL2_RW, .type = ARM_CP_CONST,
7904               .resetvalue = 0 },
7905             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
7906               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
7907               .access = PL3_RW, .type = ARM_CP_CONST,
7908               .resetvalue = 0 },
7909             REGINFO_SENTINEL
7910         };
7911         define_arm_cp_regs(cpu, auxcr_reginfo);
7912         if (cpu_isar_feature(aa32_ac2, cpu)) {
7913             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
7914         }
7915     }
7916 
7917     if (arm_feature(env, ARM_FEATURE_CBAR)) {
7918         /*
7919          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
7920          * There are two flavours:
7921          *  (1) older 32-bit only cores have a simple 32-bit CBAR
7922          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
7923          *      32-bit register visible to AArch32 at a different encoding
7924          *      to the "flavour 1" register and with the bits rearranged to
7925          *      be able to squash a 64-bit address into the 32-bit view.
7926          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
7927          * in future if we support AArch32-only configs of some of the
7928          * AArch64 cores we might need to add a specific feature flag
7929          * to indicate cores with "flavour 2" CBAR.
7930          */
7931         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7932             /* 32 bit view is [31:18] 0...0 [43:32]. */
7933             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
7934                 | extract64(cpu->reset_cbar, 32, 12);
7935             ARMCPRegInfo cbar_reginfo[] = {
7936                 { .name = "CBAR",
7937                   .type = ARM_CP_CONST,
7938                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
7939                   .access = PL1_R, .resetvalue = cbar32 },
7940                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
7941                   .type = ARM_CP_CONST,
7942                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
7943                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
7944                 REGINFO_SENTINEL
7945             };
7946             /* We don't implement a r/w 64 bit CBAR currently */
7947             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
7948             define_arm_cp_regs(cpu, cbar_reginfo);
7949         } else {
7950             ARMCPRegInfo cbar = {
7951                 .name = "CBAR",
7952                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
7953                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
7954                 .fieldoffset = offsetof(CPUARMState,
7955                                         cp15.c15_config_base_address)
7956             };
7957             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
7958                 cbar.access = PL1_R;
7959                 cbar.fieldoffset = 0;
7960                 cbar.type = ARM_CP_CONST;
7961             }
7962             define_one_arm_cp_reg(cpu, &cbar);
7963         }
7964     }
7965 
7966     if (arm_feature(env, ARM_FEATURE_VBAR)) {
7967         ARMCPRegInfo vbar_cp_reginfo[] = {
7968             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
7969               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
7970               .access = PL1_RW, .writefn = vbar_write,
7971               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
7972                                      offsetof(CPUARMState, cp15.vbar_ns) },
7973               .resetvalue = 0 },
7974             REGINFO_SENTINEL
7975         };
7976         define_arm_cp_regs(cpu, vbar_cp_reginfo);
7977     }
7978 
7979     /* Generic registers whose values depend on the implementation */
7980     {
7981         ARMCPRegInfo sctlr = {
7982             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
7983             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
7984             .access = PL1_RW, .accessfn = access_tvm_trvm,
7985             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
7986                                    offsetof(CPUARMState, cp15.sctlr_ns) },
7987             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
7988             .raw_writefn = raw_write,
7989         };
7990         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7991             /* Normally we would always end the TB on an SCTLR write, but Linux
7992              * arch/arm/mach-pxa/sleep.S expects two instructions following
7993              * an MMU enable to execute from cache.  Imitate this behaviour.
7994              */
7995             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
7996         }
7997         define_one_arm_cp_reg(cpu, &sctlr);
7998     }
7999 
8000     if (cpu_isar_feature(aa64_lor, cpu)) {
8001         define_arm_cp_regs(cpu, lor_reginfo);
8002     }
8003     if (cpu_isar_feature(aa64_pan, cpu)) {
8004         define_one_arm_cp_reg(cpu, &pan_reginfo);
8005     }
8006 #ifndef CONFIG_USER_ONLY
8007     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8008         define_arm_cp_regs(cpu, ats1e1_reginfo);
8009     }
8010     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8011         define_arm_cp_regs(cpu, ats1cp_reginfo);
8012     }
8013 #endif
8014     if (cpu_isar_feature(aa64_uao, cpu)) {
8015         define_one_arm_cp_reg(cpu, &uao_reginfo);
8016     }
8017 
8018     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8019         define_arm_cp_regs(cpu, vhe_reginfo);
8020     }
8021 
8022     if (cpu_isar_feature(aa64_sve, cpu)) {
8023         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
8024         if (arm_feature(env, ARM_FEATURE_EL2)) {
8025             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
8026         } else {
8027             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
8028         }
8029         if (arm_feature(env, ARM_FEATURE_EL3)) {
8030             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
8031         }
8032     }
8033 
8034 #ifdef TARGET_AARCH64
8035     if (cpu_isar_feature(aa64_pauth, cpu)) {
8036         define_arm_cp_regs(cpu, pauth_reginfo);
8037     }
8038     if (cpu_isar_feature(aa64_rndr, cpu)) {
8039         define_arm_cp_regs(cpu, rndr_reginfo);
8040     }
8041 #ifndef CONFIG_USER_ONLY
8042     /* Data Cache clean instructions up to PoP */
8043     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8044         define_one_arm_cp_reg(cpu, dcpop_reg);
8045 
8046         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8047             define_one_arm_cp_reg(cpu, dcpodp_reg);
8048         }
8049     }
8050 #endif /*CONFIG_USER_ONLY*/
8051 #endif
8052 
8053     if (cpu_isar_feature(any_predinv, cpu)) {
8054         define_arm_cp_regs(cpu, predinv_reginfo);
8055     }
8056 
8057     if (cpu_isar_feature(any_ccidx, cpu)) {
8058         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8059     }
8060 
8061 #ifndef CONFIG_USER_ONLY
8062     /*
8063      * Register redirections and aliases must be done last,
8064      * after the registers from the other extensions have been defined.
8065      */
8066     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8067         define_arm_vh_e2h_redirects_aliases(cpu);
8068     }
8069 #endif
8070 }
8071 
8072 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
8073 {
8074     CPUState *cs = CPU(cpu);
8075     CPUARMState *env = &cpu->env;
8076 
8077     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8078         /*
8079          * The lower part of each SVE register aliases to the FPU
8080          * registers so we don't need to include both.
8081          */
8082 #ifdef TARGET_AARCH64
8083         if (isar_feature_aa64_sve(&cpu->isar)) {
8084             gdb_register_coprocessor(cs, arm_gdb_get_svereg, arm_gdb_set_svereg,
8085                                      arm_gen_dynamic_svereg_xml(cs, cs->gdb_num_regs),
8086                                      "sve-registers.xml", 0);
8087         } else
8088 #endif
8089         {
8090             gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
8091                                      aarch64_fpu_gdb_set_reg,
8092                                      34, "aarch64-fpu.xml", 0);
8093         }
8094     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
8095         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8096                                  51, "arm-neon.xml", 0);
8097     } else if (cpu_isar_feature(aa32_simd_r32, cpu)) {
8098         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8099                                  35, "arm-vfp3.xml", 0);
8100     } else if (cpu_isar_feature(aa32_vfp_simd, cpu)) {
8101         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8102                                  19, "arm-vfp.xml", 0);
8103     }
8104     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
8105                              arm_gen_dynamic_sysreg_xml(cs, cs->gdb_num_regs),
8106                              "system-registers.xml", 0);
8107 
8108 }
8109 
8110 /* Sort alphabetically by type name, except for "any". */
8111 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8112 {
8113     ObjectClass *class_a = (ObjectClass *)a;
8114     ObjectClass *class_b = (ObjectClass *)b;
8115     const char *name_a, *name_b;
8116 
8117     name_a = object_class_get_name(class_a);
8118     name_b = object_class_get_name(class_b);
8119     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8120         return 1;
8121     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8122         return -1;
8123     } else {
8124         return strcmp(name_a, name_b);
8125     }
8126 }
8127 
8128 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8129 {
8130     ObjectClass *oc = data;
8131     const char *typename;
8132     char *name;
8133 
8134     typename = object_class_get_name(oc);
8135     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8136     qemu_printf("  %s\n", name);
8137     g_free(name);
8138 }
8139 
8140 void arm_cpu_list(void)
8141 {
8142     GSList *list;
8143 
8144     list = object_class_get_list(TYPE_ARM_CPU, false);
8145     list = g_slist_sort(list, arm_cpu_list_compare);
8146     qemu_printf("Available CPUs:\n");
8147     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8148     g_slist_free(list);
8149 }
8150 
8151 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8152 {
8153     ObjectClass *oc = data;
8154     CpuDefinitionInfoList **cpu_list = user_data;
8155     CpuDefinitionInfoList *entry;
8156     CpuDefinitionInfo *info;
8157     const char *typename;
8158 
8159     typename = object_class_get_name(oc);
8160     info = g_malloc0(sizeof(*info));
8161     info->name = g_strndup(typename,
8162                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8163     info->q_typename = g_strdup(typename);
8164 
8165     entry = g_malloc0(sizeof(*entry));
8166     entry->value = info;
8167     entry->next = *cpu_list;
8168     *cpu_list = entry;
8169 }
8170 
8171 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8172 {
8173     CpuDefinitionInfoList *cpu_list = NULL;
8174     GSList *list;
8175 
8176     list = object_class_get_list(TYPE_ARM_CPU, false);
8177     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8178     g_slist_free(list);
8179 
8180     return cpu_list;
8181 }
8182 
8183 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8184                                    void *opaque, int state, int secstate,
8185                                    int crm, int opc1, int opc2,
8186                                    const char *name)
8187 {
8188     /* Private utility function for define_one_arm_cp_reg_with_opaque():
8189      * add a single reginfo struct to the hash table.
8190      */
8191     uint32_t *key = g_new(uint32_t, 1);
8192     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
8193     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
8194     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
8195 
8196     r2->name = g_strdup(name);
8197     /* Reset the secure state to the specific incoming state.  This is
8198      * necessary as the register may have been defined with both states.
8199      */
8200     r2->secure = secstate;
8201 
8202     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8203         /* Register is banked (using both entries in array).
8204          * Overwriting fieldoffset as the array is only used to define
8205          * banked registers but later only fieldoffset is used.
8206          */
8207         r2->fieldoffset = r->bank_fieldoffsets[ns];
8208     }
8209 
8210     if (state == ARM_CP_STATE_AA32) {
8211         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8212             /* If the register is banked then we don't need to migrate or
8213              * reset the 32-bit instance in certain cases:
8214              *
8215              * 1) If the register has both 32-bit and 64-bit instances then we
8216              *    can count on the 64-bit instance taking care of the
8217              *    non-secure bank.
8218              * 2) If ARMv8 is enabled then we can count on a 64-bit version
8219              *    taking care of the secure bank.  This requires that separate
8220              *    32 and 64-bit definitions are provided.
8221              */
8222             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8223                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
8224                 r2->type |= ARM_CP_ALIAS;
8225             }
8226         } else if ((secstate != r->secure) && !ns) {
8227             /* The register is not banked so we only want to allow migration of
8228              * the non-secure instance.
8229              */
8230             r2->type |= ARM_CP_ALIAS;
8231         }
8232 
8233         if (r->state == ARM_CP_STATE_BOTH) {
8234             /* We assume it is a cp15 register if the .cp field is left unset.
8235              */
8236             if (r2->cp == 0) {
8237                 r2->cp = 15;
8238             }
8239 
8240 #ifdef HOST_WORDS_BIGENDIAN
8241             if (r2->fieldoffset) {
8242                 r2->fieldoffset += sizeof(uint32_t);
8243             }
8244 #endif
8245         }
8246     }
8247     if (state == ARM_CP_STATE_AA64) {
8248         /* To allow abbreviation of ARMCPRegInfo
8249          * definitions, we treat cp == 0 as equivalent to
8250          * the value for "standard guest-visible sysreg".
8251          * STATE_BOTH definitions are also always "standard
8252          * sysreg" in their AArch64 view (the .cp value may
8253          * be non-zero for the benefit of the AArch32 view).
8254          */
8255         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8256             r2->cp = CP_REG_ARM64_SYSREG_CP;
8257         }
8258         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
8259                                   r2->opc0, opc1, opc2);
8260     } else {
8261         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
8262     }
8263     if (opaque) {
8264         r2->opaque = opaque;
8265     }
8266     /* reginfo passed to helpers is correct for the actual access,
8267      * and is never ARM_CP_STATE_BOTH:
8268      */
8269     r2->state = state;
8270     /* Make sure reginfo passed to helpers for wildcarded regs
8271      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
8272      */
8273     r2->crm = crm;
8274     r2->opc1 = opc1;
8275     r2->opc2 = opc2;
8276     /* By convention, for wildcarded registers only the first
8277      * entry is used for migration; the others are marked as
8278      * ALIAS so we don't try to transfer the register
8279      * multiple times. Special registers (ie NOP/WFI) are
8280      * never migratable and not even raw-accessible.
8281      */
8282     if ((r->type & ARM_CP_SPECIAL)) {
8283         r2->type |= ARM_CP_NO_RAW;
8284     }
8285     if (((r->crm == CP_ANY) && crm != 0) ||
8286         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8287         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8288         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8289     }
8290 
8291     /* Check that raw accesses are either forbidden or handled. Note that
8292      * we can't assert this earlier because the setup of fieldoffset for
8293      * banked registers has to be done first.
8294      */
8295     if (!(r2->type & ARM_CP_NO_RAW)) {
8296         assert(!raw_accessors_invalid(r2));
8297     }
8298 
8299     /* Overriding of an existing definition must be explicitly
8300      * requested.
8301      */
8302     if (!(r->type & ARM_CP_OVERRIDE)) {
8303         ARMCPRegInfo *oldreg;
8304         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
8305         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
8306             fprintf(stderr, "Register redefined: cp=%d %d bit "
8307                     "crn=%d crm=%d opc1=%d opc2=%d, "
8308                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
8309                     r2->crn, r2->crm, r2->opc1, r2->opc2,
8310                     oldreg->name, r2->name);
8311             g_assert_not_reached();
8312         }
8313     }
8314     g_hash_table_insert(cpu->cp_regs, key, r2);
8315 }
8316 
8317 
8318 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8319                                        const ARMCPRegInfo *r, void *opaque)
8320 {
8321     /* Define implementations of coprocessor registers.
8322      * We store these in a hashtable because typically
8323      * there are less than 150 registers in a space which
8324      * is 16*16*16*8*8 = 262144 in size.
8325      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8326      * If a register is defined twice then the second definition is
8327      * used, so this can be used to define some generic registers and
8328      * then override them with implementation specific variations.
8329      * At least one of the original and the second definition should
8330      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8331      * against accidental use.
8332      *
8333      * The state field defines whether the register is to be
8334      * visible in the AArch32 or AArch64 execution state. If the
8335      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8336      * reginfo structure for the AArch32 view, which sees the lower
8337      * 32 bits of the 64 bit register.
8338      *
8339      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8340      * be wildcarded. AArch64 registers are always considered to be 64
8341      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8342      * the register, if any.
8343      */
8344     int crm, opc1, opc2, state;
8345     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8346     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8347     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8348     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8349     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8350     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8351     /* 64 bit registers have only CRm and Opc1 fields */
8352     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8353     /* op0 only exists in the AArch64 encodings */
8354     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8355     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8356     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8357     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8358      * encodes a minimum access level for the register. We roll this
8359      * runtime check into our general permission check code, so check
8360      * here that the reginfo's specified permissions are strict enough
8361      * to encompass the generic architectural permission check.
8362      */
8363     if (r->state != ARM_CP_STATE_AA32) {
8364         int mask = 0;
8365         switch (r->opc1) {
8366         case 0:
8367             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8368             mask = PL0U_R | PL1_RW;
8369             break;
8370         case 1: case 2:
8371             /* min_EL EL1 */
8372             mask = PL1_RW;
8373             break;
8374         case 3:
8375             /* min_EL EL0 */
8376             mask = PL0_RW;
8377             break;
8378         case 4:
8379         case 5:
8380             /* min_EL EL2 */
8381             mask = PL2_RW;
8382             break;
8383         case 6:
8384             /* min_EL EL3 */
8385             mask = PL3_RW;
8386             break;
8387         case 7:
8388             /* min_EL EL1, secure mode only (we don't check the latter) */
8389             mask = PL1_RW;
8390             break;
8391         default:
8392             /* broken reginfo with out-of-range opc1 */
8393             assert(false);
8394             break;
8395         }
8396         /* assert our permissions are not too lax (stricter is fine) */
8397         assert((r->access & ~mask) == 0);
8398     }
8399 
8400     /* Check that the register definition has enough info to handle
8401      * reads and writes if they are permitted.
8402      */
8403     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
8404         if (r->access & PL3_R) {
8405             assert((r->fieldoffset ||
8406                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8407                    r->readfn);
8408         }
8409         if (r->access & PL3_W) {
8410             assert((r->fieldoffset ||
8411                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8412                    r->writefn);
8413         }
8414     }
8415     /* Bad type field probably means missing sentinel at end of reg list */
8416     assert(cptype_valid(r->type));
8417     for (crm = crmmin; crm <= crmmax; crm++) {
8418         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8419             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8420                 for (state = ARM_CP_STATE_AA32;
8421                      state <= ARM_CP_STATE_AA64; state++) {
8422                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8423                         continue;
8424                     }
8425                     if (state == ARM_CP_STATE_AA32) {
8426                         /* Under AArch32 CP registers can be common
8427                          * (same for secure and non-secure world) or banked.
8428                          */
8429                         char *name;
8430 
8431                         switch (r->secure) {
8432                         case ARM_CP_SECSTATE_S:
8433                         case ARM_CP_SECSTATE_NS:
8434                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8435                                                    r->secure, crm, opc1, opc2,
8436                                                    r->name);
8437                             break;
8438                         default:
8439                             name = g_strdup_printf("%s_S", r->name);
8440                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8441                                                    ARM_CP_SECSTATE_S,
8442                                                    crm, opc1, opc2, name);
8443                             g_free(name);
8444                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8445                                                    ARM_CP_SECSTATE_NS,
8446                                                    crm, opc1, opc2, r->name);
8447                             break;
8448                         }
8449                     } else {
8450                         /* AArch64 registers get mapped to non-secure instance
8451                          * of AArch32 */
8452                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8453                                                ARM_CP_SECSTATE_NS,
8454                                                crm, opc1, opc2, r->name);
8455                     }
8456                 }
8457             }
8458         }
8459     }
8460 }
8461 
8462 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
8463                                     const ARMCPRegInfo *regs, void *opaque)
8464 {
8465     /* Define a whole list of registers */
8466     const ARMCPRegInfo *r;
8467     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8468         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
8469     }
8470 }
8471 
8472 /*
8473  * Modify ARMCPRegInfo for access from userspace.
8474  *
8475  * This is a data driven modification directed by
8476  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8477  * user-space cannot alter any values and dynamic values pertaining to
8478  * execution state are hidden from user space view anyway.
8479  */
8480 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
8481 {
8482     const ARMCPRegUserSpaceInfo *m;
8483     ARMCPRegInfo *r;
8484 
8485     for (m = mods; m->name; m++) {
8486         GPatternSpec *pat = NULL;
8487         if (m->is_glob) {
8488             pat = g_pattern_spec_new(m->name);
8489         }
8490         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8491             if (pat && g_pattern_match_string(pat, r->name)) {
8492                 r->type = ARM_CP_CONST;
8493                 r->access = PL0U_R;
8494                 r->resetvalue = 0;
8495                 /* continue */
8496             } else if (strcmp(r->name, m->name) == 0) {
8497                 r->type = ARM_CP_CONST;
8498                 r->access = PL0U_R;
8499                 r->resetvalue &= m->exported_bits;
8500                 r->resetvalue |= m->fixed_bits;
8501                 break;
8502             }
8503         }
8504         if (pat) {
8505             g_pattern_spec_free(pat);
8506         }
8507     }
8508 }
8509 
8510 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8511 {
8512     return g_hash_table_lookup(cpregs, &encoded_cp);
8513 }
8514 
8515 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8516                          uint64_t value)
8517 {
8518     /* Helper coprocessor write function for write-ignore registers */
8519 }
8520 
8521 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8522 {
8523     /* Helper coprocessor write function for read-as-zero registers */
8524     return 0;
8525 }
8526 
8527 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8528 {
8529     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8530 }
8531 
8532 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8533 {
8534     /* Return true if it is not valid for us to switch to
8535      * this CPU mode (ie all the UNPREDICTABLE cases in
8536      * the ARM ARM CPSRWriteByInstr pseudocode).
8537      */
8538 
8539     /* Changes to or from Hyp via MSR and CPS are illegal. */
8540     if (write_type == CPSRWriteByInstr &&
8541         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8542          mode == ARM_CPU_MODE_HYP)) {
8543         return 1;
8544     }
8545 
8546     switch (mode) {
8547     case ARM_CPU_MODE_USR:
8548         return 0;
8549     case ARM_CPU_MODE_SYS:
8550     case ARM_CPU_MODE_SVC:
8551     case ARM_CPU_MODE_ABT:
8552     case ARM_CPU_MODE_UND:
8553     case ARM_CPU_MODE_IRQ:
8554     case ARM_CPU_MODE_FIQ:
8555         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
8556          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
8557          */
8558         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
8559          * and CPS are treated as illegal mode changes.
8560          */
8561         if (write_type == CPSRWriteByInstr &&
8562             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
8563             (arm_hcr_el2_eff(env) & HCR_TGE)) {
8564             return 1;
8565         }
8566         return 0;
8567     case ARM_CPU_MODE_HYP:
8568         return !arm_feature(env, ARM_FEATURE_EL2)
8569             || arm_current_el(env) < 2 || arm_is_secure_below_el3(env);
8570     case ARM_CPU_MODE_MON:
8571         return arm_current_el(env) < 3;
8572     default:
8573         return 1;
8574     }
8575 }
8576 
8577 uint32_t cpsr_read(CPUARMState *env)
8578 {
8579     int ZF;
8580     ZF = (env->ZF == 0);
8581     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
8582         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
8583         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
8584         | ((env->condexec_bits & 0xfc) << 8)
8585         | (env->GE << 16) | (env->daif & CPSR_AIF);
8586 }
8587 
8588 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
8589                 CPSRWriteType write_type)
8590 {
8591     uint32_t changed_daif;
8592 
8593     if (mask & CPSR_NZCV) {
8594         env->ZF = (~val) & CPSR_Z;
8595         env->NF = val;
8596         env->CF = (val >> 29) & 1;
8597         env->VF = (val << 3) & 0x80000000;
8598     }
8599     if (mask & CPSR_Q)
8600         env->QF = ((val & CPSR_Q) != 0);
8601     if (mask & CPSR_T)
8602         env->thumb = ((val & CPSR_T) != 0);
8603     if (mask & CPSR_IT_0_1) {
8604         env->condexec_bits &= ~3;
8605         env->condexec_bits |= (val >> 25) & 3;
8606     }
8607     if (mask & CPSR_IT_2_7) {
8608         env->condexec_bits &= 3;
8609         env->condexec_bits |= (val >> 8) & 0xfc;
8610     }
8611     if (mask & CPSR_GE) {
8612         env->GE = (val >> 16) & 0xf;
8613     }
8614 
8615     /* In a V7 implementation that includes the security extensions but does
8616      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
8617      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
8618      * bits respectively.
8619      *
8620      * In a V8 implementation, it is permitted for privileged software to
8621      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
8622      */
8623     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
8624         arm_feature(env, ARM_FEATURE_EL3) &&
8625         !arm_feature(env, ARM_FEATURE_EL2) &&
8626         !arm_is_secure(env)) {
8627 
8628         changed_daif = (env->daif ^ val) & mask;
8629 
8630         if (changed_daif & CPSR_A) {
8631             /* Check to see if we are allowed to change the masking of async
8632              * abort exceptions from a non-secure state.
8633              */
8634             if (!(env->cp15.scr_el3 & SCR_AW)) {
8635                 qemu_log_mask(LOG_GUEST_ERROR,
8636                               "Ignoring attempt to switch CPSR_A flag from "
8637                               "non-secure world with SCR.AW bit clear\n");
8638                 mask &= ~CPSR_A;
8639             }
8640         }
8641 
8642         if (changed_daif & CPSR_F) {
8643             /* Check to see if we are allowed to change the masking of FIQ
8644              * exceptions from a non-secure state.
8645              */
8646             if (!(env->cp15.scr_el3 & SCR_FW)) {
8647                 qemu_log_mask(LOG_GUEST_ERROR,
8648                               "Ignoring attempt to switch CPSR_F flag from "
8649                               "non-secure world with SCR.FW bit clear\n");
8650                 mask &= ~CPSR_F;
8651             }
8652 
8653             /* Check whether non-maskable FIQ (NMFI) support is enabled.
8654              * If this bit is set software is not allowed to mask
8655              * FIQs, but is allowed to set CPSR_F to 0.
8656              */
8657             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
8658                 (val & CPSR_F)) {
8659                 qemu_log_mask(LOG_GUEST_ERROR,
8660                               "Ignoring attempt to enable CPSR_F flag "
8661                               "(non-maskable FIQ [NMFI] support enabled)\n");
8662                 mask &= ~CPSR_F;
8663             }
8664         }
8665     }
8666 
8667     env->daif &= ~(CPSR_AIF & mask);
8668     env->daif |= val & CPSR_AIF & mask;
8669 
8670     if (write_type != CPSRWriteRaw &&
8671         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
8672         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
8673             /* Note that we can only get here in USR mode if this is a
8674              * gdb stub write; for this case we follow the architectural
8675              * behaviour for guest writes in USR mode of ignoring an attempt
8676              * to switch mode. (Those are caught by translate.c for writes
8677              * triggered by guest instructions.)
8678              */
8679             mask &= ~CPSR_M;
8680         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
8681             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
8682              * v7, and has defined behaviour in v8:
8683              *  + leave CPSR.M untouched
8684              *  + allow changes to the other CPSR fields
8685              *  + set PSTATE.IL
8686              * For user changes via the GDB stub, we don't set PSTATE.IL,
8687              * as this would be unnecessarily harsh for a user error.
8688              */
8689             mask &= ~CPSR_M;
8690             if (write_type != CPSRWriteByGDBStub &&
8691                 arm_feature(env, ARM_FEATURE_V8)) {
8692                 mask |= CPSR_IL;
8693                 val |= CPSR_IL;
8694             }
8695             qemu_log_mask(LOG_GUEST_ERROR,
8696                           "Illegal AArch32 mode switch attempt from %s to %s\n",
8697                           aarch32_mode_name(env->uncached_cpsr),
8698                           aarch32_mode_name(val));
8699         } else {
8700             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
8701                           write_type == CPSRWriteExceptionReturn ?
8702                           "Exception return from AArch32" :
8703                           "AArch32 mode switch from",
8704                           aarch32_mode_name(env->uncached_cpsr),
8705                           aarch32_mode_name(val), env->regs[15]);
8706             switch_mode(env, val & CPSR_M);
8707         }
8708     }
8709     mask &= ~CACHED_CPSR_BITS;
8710     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
8711 }
8712 
8713 /* Sign/zero extend */
8714 uint32_t HELPER(sxtb16)(uint32_t x)
8715 {
8716     uint32_t res;
8717     res = (uint16_t)(int8_t)x;
8718     res |= (uint32_t)(int8_t)(x >> 16) << 16;
8719     return res;
8720 }
8721 
8722 uint32_t HELPER(uxtb16)(uint32_t x)
8723 {
8724     uint32_t res;
8725     res = (uint16_t)(uint8_t)x;
8726     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
8727     return res;
8728 }
8729 
8730 int32_t HELPER(sdiv)(int32_t num, int32_t den)
8731 {
8732     if (den == 0)
8733       return 0;
8734     if (num == INT_MIN && den == -1)
8735       return INT_MIN;
8736     return num / den;
8737 }
8738 
8739 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
8740 {
8741     if (den == 0)
8742       return 0;
8743     return num / den;
8744 }
8745 
8746 uint32_t HELPER(rbit)(uint32_t x)
8747 {
8748     return revbit32(x);
8749 }
8750 
8751 #ifdef CONFIG_USER_ONLY
8752 
8753 static void switch_mode(CPUARMState *env, int mode)
8754 {
8755     ARMCPU *cpu = env_archcpu(env);
8756 
8757     if (mode != ARM_CPU_MODE_USR) {
8758         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
8759     }
8760 }
8761 
8762 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
8763                                  uint32_t cur_el, bool secure)
8764 {
8765     return 1;
8766 }
8767 
8768 void aarch64_sync_64_to_32(CPUARMState *env)
8769 {
8770     g_assert_not_reached();
8771 }
8772 
8773 #else
8774 
8775 static void switch_mode(CPUARMState *env, int mode)
8776 {
8777     int old_mode;
8778     int i;
8779 
8780     old_mode = env->uncached_cpsr & CPSR_M;
8781     if (mode == old_mode)
8782         return;
8783 
8784     if (old_mode == ARM_CPU_MODE_FIQ) {
8785         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
8786         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
8787     } else if (mode == ARM_CPU_MODE_FIQ) {
8788         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
8789         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
8790     }
8791 
8792     i = bank_number(old_mode);
8793     env->banked_r13[i] = env->regs[13];
8794     env->banked_spsr[i] = env->spsr;
8795 
8796     i = bank_number(mode);
8797     env->regs[13] = env->banked_r13[i];
8798     env->spsr = env->banked_spsr[i];
8799 
8800     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
8801     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
8802 }
8803 
8804 /* Physical Interrupt Target EL Lookup Table
8805  *
8806  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
8807  *
8808  * The below multi-dimensional table is used for looking up the target
8809  * exception level given numerous condition criteria.  Specifically, the
8810  * target EL is based on SCR and HCR routing controls as well as the
8811  * currently executing EL and secure state.
8812  *
8813  *    Dimensions:
8814  *    target_el_table[2][2][2][2][2][4]
8815  *                    |  |  |  |  |  +--- Current EL
8816  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
8817  *                    |  |  |  +--------- HCR mask override
8818  *                    |  |  +------------ SCR exec state control
8819  *                    |  +--------------- SCR mask override
8820  *                    +------------------ 32-bit(0)/64-bit(1) EL3
8821  *
8822  *    The table values are as such:
8823  *    0-3 = EL0-EL3
8824  *     -1 = Cannot occur
8825  *
8826  * The ARM ARM target EL table includes entries indicating that an "exception
8827  * is not taken".  The two cases where this is applicable are:
8828  *    1) An exception is taken from EL3 but the SCR does not have the exception
8829  *    routed to EL3.
8830  *    2) An exception is taken from EL2 but the HCR does not have the exception
8831  *    routed to EL2.
8832  * In these two cases, the below table contain a target of EL1.  This value is
8833  * returned as it is expected that the consumer of the table data will check
8834  * for "target EL >= current EL" to ensure the exception is not taken.
8835  *
8836  *            SCR     HCR
8837  *         64  EA     AMO                 From
8838  *        BIT IRQ     IMO      Non-secure         Secure
8839  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
8840  */
8841 static const int8_t target_el_table[2][2][2][2][2][4] = {
8842     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
8843        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
8844       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
8845        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
8846      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
8847        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
8848       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
8849        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
8850     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
8851        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
8852       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
8853        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
8854      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
8855        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
8856       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
8857        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
8858 };
8859 
8860 /*
8861  * Determine the target EL for physical exceptions
8862  */
8863 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
8864                                  uint32_t cur_el, bool secure)
8865 {
8866     CPUARMState *env = cs->env_ptr;
8867     bool rw;
8868     bool scr;
8869     bool hcr;
8870     int target_el;
8871     /* Is the highest EL AArch64? */
8872     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
8873     uint64_t hcr_el2;
8874 
8875     if (arm_feature(env, ARM_FEATURE_EL3)) {
8876         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
8877     } else {
8878         /* Either EL2 is the highest EL (and so the EL2 register width
8879          * is given by is64); or there is no EL2 or EL3, in which case
8880          * the value of 'rw' does not affect the table lookup anyway.
8881          */
8882         rw = is64;
8883     }
8884 
8885     hcr_el2 = arm_hcr_el2_eff(env);
8886     switch (excp_idx) {
8887     case EXCP_IRQ:
8888         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
8889         hcr = hcr_el2 & HCR_IMO;
8890         break;
8891     case EXCP_FIQ:
8892         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
8893         hcr = hcr_el2 & HCR_FMO;
8894         break;
8895     default:
8896         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
8897         hcr = hcr_el2 & HCR_AMO;
8898         break;
8899     };
8900 
8901     /*
8902      * For these purposes, TGE and AMO/IMO/FMO both force the
8903      * interrupt to EL2.  Fold TGE into the bit extracted above.
8904      */
8905     hcr |= (hcr_el2 & HCR_TGE) != 0;
8906 
8907     /* Perform a table-lookup for the target EL given the current state */
8908     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
8909 
8910     assert(target_el > 0);
8911 
8912     return target_el;
8913 }
8914 
8915 void arm_log_exception(int idx)
8916 {
8917     if (qemu_loglevel_mask(CPU_LOG_INT)) {
8918         const char *exc = NULL;
8919         static const char * const excnames[] = {
8920             [EXCP_UDEF] = "Undefined Instruction",
8921             [EXCP_SWI] = "SVC",
8922             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
8923             [EXCP_DATA_ABORT] = "Data Abort",
8924             [EXCP_IRQ] = "IRQ",
8925             [EXCP_FIQ] = "FIQ",
8926             [EXCP_BKPT] = "Breakpoint",
8927             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
8928             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
8929             [EXCP_HVC] = "Hypervisor Call",
8930             [EXCP_HYP_TRAP] = "Hypervisor Trap",
8931             [EXCP_SMC] = "Secure Monitor Call",
8932             [EXCP_VIRQ] = "Virtual IRQ",
8933             [EXCP_VFIQ] = "Virtual FIQ",
8934             [EXCP_SEMIHOST] = "Semihosting call",
8935             [EXCP_NOCP] = "v7M NOCP UsageFault",
8936             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
8937             [EXCP_STKOF] = "v8M STKOF UsageFault",
8938             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
8939             [EXCP_LSERR] = "v8M LSERR UsageFault",
8940             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
8941         };
8942 
8943         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
8944             exc = excnames[idx];
8945         }
8946         if (!exc) {
8947             exc = "unknown";
8948         }
8949         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
8950     }
8951 }
8952 
8953 /*
8954  * Function used to synchronize QEMU's AArch64 register set with AArch32
8955  * register set.  This is necessary when switching between AArch32 and AArch64
8956  * execution state.
8957  */
8958 void aarch64_sync_32_to_64(CPUARMState *env)
8959 {
8960     int i;
8961     uint32_t mode = env->uncached_cpsr & CPSR_M;
8962 
8963     /* We can blanket copy R[0:7] to X[0:7] */
8964     for (i = 0; i < 8; i++) {
8965         env->xregs[i] = env->regs[i];
8966     }
8967 
8968     /*
8969      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
8970      * Otherwise, they come from the banked user regs.
8971      */
8972     if (mode == ARM_CPU_MODE_FIQ) {
8973         for (i = 8; i < 13; i++) {
8974             env->xregs[i] = env->usr_regs[i - 8];
8975         }
8976     } else {
8977         for (i = 8; i < 13; i++) {
8978             env->xregs[i] = env->regs[i];
8979         }
8980     }
8981 
8982     /*
8983      * Registers x13-x23 are the various mode SP and FP registers. Registers
8984      * r13 and r14 are only copied if we are in that mode, otherwise we copy
8985      * from the mode banked register.
8986      */
8987     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
8988         env->xregs[13] = env->regs[13];
8989         env->xregs[14] = env->regs[14];
8990     } else {
8991         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
8992         /* HYP is an exception in that it is copied from r14 */
8993         if (mode == ARM_CPU_MODE_HYP) {
8994             env->xregs[14] = env->regs[14];
8995         } else {
8996             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
8997         }
8998     }
8999 
9000     if (mode == ARM_CPU_MODE_HYP) {
9001         env->xregs[15] = env->regs[13];
9002     } else {
9003         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9004     }
9005 
9006     if (mode == ARM_CPU_MODE_IRQ) {
9007         env->xregs[16] = env->regs[14];
9008         env->xregs[17] = env->regs[13];
9009     } else {
9010         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9011         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9012     }
9013 
9014     if (mode == ARM_CPU_MODE_SVC) {
9015         env->xregs[18] = env->regs[14];
9016         env->xregs[19] = env->regs[13];
9017     } else {
9018         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9019         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9020     }
9021 
9022     if (mode == ARM_CPU_MODE_ABT) {
9023         env->xregs[20] = env->regs[14];
9024         env->xregs[21] = env->regs[13];
9025     } else {
9026         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9027         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9028     }
9029 
9030     if (mode == ARM_CPU_MODE_UND) {
9031         env->xregs[22] = env->regs[14];
9032         env->xregs[23] = env->regs[13];
9033     } else {
9034         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9035         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9036     }
9037 
9038     /*
9039      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9040      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9041      * FIQ bank for r8-r14.
9042      */
9043     if (mode == ARM_CPU_MODE_FIQ) {
9044         for (i = 24; i < 31; i++) {
9045             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9046         }
9047     } else {
9048         for (i = 24; i < 29; i++) {
9049             env->xregs[i] = env->fiq_regs[i - 24];
9050         }
9051         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9052         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9053     }
9054 
9055     env->pc = env->regs[15];
9056 }
9057 
9058 /*
9059  * Function used to synchronize QEMU's AArch32 register set with AArch64
9060  * register set.  This is necessary when switching between AArch32 and AArch64
9061  * execution state.
9062  */
9063 void aarch64_sync_64_to_32(CPUARMState *env)
9064 {
9065     int i;
9066     uint32_t mode = env->uncached_cpsr & CPSR_M;
9067 
9068     /* We can blanket copy X[0:7] to R[0:7] */
9069     for (i = 0; i < 8; i++) {
9070         env->regs[i] = env->xregs[i];
9071     }
9072 
9073     /*
9074      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9075      * Otherwise, we copy x8-x12 into the banked user regs.
9076      */
9077     if (mode == ARM_CPU_MODE_FIQ) {
9078         for (i = 8; i < 13; i++) {
9079             env->usr_regs[i - 8] = env->xregs[i];
9080         }
9081     } else {
9082         for (i = 8; i < 13; i++) {
9083             env->regs[i] = env->xregs[i];
9084         }
9085     }
9086 
9087     /*
9088      * Registers r13 & r14 depend on the current mode.
9089      * If we are in a given mode, we copy the corresponding x registers to r13
9090      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9091      * for the mode.
9092      */
9093     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9094         env->regs[13] = env->xregs[13];
9095         env->regs[14] = env->xregs[14];
9096     } else {
9097         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9098 
9099         /*
9100          * HYP is an exception in that it does not have its own banked r14 but
9101          * shares the USR r14
9102          */
9103         if (mode == ARM_CPU_MODE_HYP) {
9104             env->regs[14] = env->xregs[14];
9105         } else {
9106             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9107         }
9108     }
9109 
9110     if (mode == ARM_CPU_MODE_HYP) {
9111         env->regs[13] = env->xregs[15];
9112     } else {
9113         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9114     }
9115 
9116     if (mode == ARM_CPU_MODE_IRQ) {
9117         env->regs[14] = env->xregs[16];
9118         env->regs[13] = env->xregs[17];
9119     } else {
9120         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9121         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9122     }
9123 
9124     if (mode == ARM_CPU_MODE_SVC) {
9125         env->regs[14] = env->xregs[18];
9126         env->regs[13] = env->xregs[19];
9127     } else {
9128         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9129         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9130     }
9131 
9132     if (mode == ARM_CPU_MODE_ABT) {
9133         env->regs[14] = env->xregs[20];
9134         env->regs[13] = env->xregs[21];
9135     } else {
9136         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9137         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9138     }
9139 
9140     if (mode == ARM_CPU_MODE_UND) {
9141         env->regs[14] = env->xregs[22];
9142         env->regs[13] = env->xregs[23];
9143     } else {
9144         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9145         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9146     }
9147 
9148     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9149      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9150      * FIQ bank for r8-r14.
9151      */
9152     if (mode == ARM_CPU_MODE_FIQ) {
9153         for (i = 24; i < 31; i++) {
9154             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9155         }
9156     } else {
9157         for (i = 24; i < 29; i++) {
9158             env->fiq_regs[i - 24] = env->xregs[i];
9159         }
9160         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9161         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9162     }
9163 
9164     env->regs[15] = env->pc;
9165 }
9166 
9167 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9168                                    uint32_t mask, uint32_t offset,
9169                                    uint32_t newpc)
9170 {
9171     int new_el;
9172 
9173     /* Change the CPU state so as to actually take the exception. */
9174     switch_mode(env, new_mode);
9175 
9176     /*
9177      * For exceptions taken to AArch32 we must clear the SS bit in both
9178      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9179      */
9180     env->uncached_cpsr &= ~PSTATE_SS;
9181     env->spsr = cpsr_read(env);
9182     /* Clear IT bits.  */
9183     env->condexec_bits = 0;
9184     /* Switch to the new mode, and to the correct instruction set.  */
9185     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9186 
9187     /* This must be after mode switching. */
9188     new_el = arm_current_el(env);
9189 
9190     /* Set new mode endianness */
9191     env->uncached_cpsr &= ~CPSR_E;
9192     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9193         env->uncached_cpsr |= CPSR_E;
9194     }
9195     /* J and IL must always be cleared for exception entry */
9196     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9197     env->daif |= mask;
9198 
9199     if (new_mode == ARM_CPU_MODE_HYP) {
9200         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9201         env->elr_el[2] = env->regs[15];
9202     } else {
9203         /* CPSR.PAN is normally preserved preserved unless...  */
9204         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9205             switch (new_el) {
9206             case 3:
9207                 if (!arm_is_secure_below_el3(env)) {
9208                     /* ... the target is EL3, from non-secure state.  */
9209                     env->uncached_cpsr &= ~CPSR_PAN;
9210                     break;
9211                 }
9212                 /* ... the target is EL3, from secure state ... */
9213                 /* fall through */
9214             case 1:
9215                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9216                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9217                     env->uncached_cpsr |= CPSR_PAN;
9218                 }
9219                 break;
9220             }
9221         }
9222         /*
9223          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9224          * and we should just guard the thumb mode on V4
9225          */
9226         if (arm_feature(env, ARM_FEATURE_V4T)) {
9227             env->thumb =
9228                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9229         }
9230         env->regs[14] = env->regs[15] + offset;
9231     }
9232     env->regs[15] = newpc;
9233     arm_rebuild_hflags(env);
9234 }
9235 
9236 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9237 {
9238     /*
9239      * Handle exception entry to Hyp mode; this is sufficiently
9240      * different to entry to other AArch32 modes that we handle it
9241      * separately here.
9242      *
9243      * The vector table entry used is always the 0x14 Hyp mode entry point,
9244      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
9245      * The offset applied to the preferred return address is always zero
9246      * (see DDI0487C.a section G1.12.3).
9247      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9248      */
9249     uint32_t addr, mask;
9250     ARMCPU *cpu = ARM_CPU(cs);
9251     CPUARMState *env = &cpu->env;
9252 
9253     switch (cs->exception_index) {
9254     case EXCP_UDEF:
9255         addr = 0x04;
9256         break;
9257     case EXCP_SWI:
9258         addr = 0x14;
9259         break;
9260     case EXCP_BKPT:
9261         /* Fall through to prefetch abort.  */
9262     case EXCP_PREFETCH_ABORT:
9263         env->cp15.ifar_s = env->exception.vaddress;
9264         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9265                       (uint32_t)env->exception.vaddress);
9266         addr = 0x0c;
9267         break;
9268     case EXCP_DATA_ABORT:
9269         env->cp15.dfar_s = env->exception.vaddress;
9270         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9271                       (uint32_t)env->exception.vaddress);
9272         addr = 0x10;
9273         break;
9274     case EXCP_IRQ:
9275         addr = 0x18;
9276         break;
9277     case EXCP_FIQ:
9278         addr = 0x1c;
9279         break;
9280     case EXCP_HVC:
9281         addr = 0x08;
9282         break;
9283     case EXCP_HYP_TRAP:
9284         addr = 0x14;
9285         break;
9286     default:
9287         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9288     }
9289 
9290     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9291         if (!arm_feature(env, ARM_FEATURE_V8)) {
9292             /*
9293              * QEMU syndrome values are v8-style. v7 has the IL bit
9294              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9295              * If this is a v7 CPU, squash the IL bit in those cases.
9296              */
9297             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9298                 (cs->exception_index == EXCP_DATA_ABORT &&
9299                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9300                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9301                 env->exception.syndrome &= ~ARM_EL_IL;
9302             }
9303         }
9304         env->cp15.esr_el[2] = env->exception.syndrome;
9305     }
9306 
9307     if (arm_current_el(env) != 2 && addr < 0x14) {
9308         addr = 0x14;
9309     }
9310 
9311     mask = 0;
9312     if (!(env->cp15.scr_el3 & SCR_EA)) {
9313         mask |= CPSR_A;
9314     }
9315     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9316         mask |= CPSR_I;
9317     }
9318     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9319         mask |= CPSR_F;
9320     }
9321 
9322     addr += env->cp15.hvbar;
9323 
9324     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9325 }
9326 
9327 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9328 {
9329     ARMCPU *cpu = ARM_CPU(cs);
9330     CPUARMState *env = &cpu->env;
9331     uint32_t addr;
9332     uint32_t mask;
9333     int new_mode;
9334     uint32_t offset;
9335     uint32_t moe;
9336 
9337     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9338     switch (syn_get_ec(env->exception.syndrome)) {
9339     case EC_BREAKPOINT:
9340     case EC_BREAKPOINT_SAME_EL:
9341         moe = 1;
9342         break;
9343     case EC_WATCHPOINT:
9344     case EC_WATCHPOINT_SAME_EL:
9345         moe = 10;
9346         break;
9347     case EC_AA32_BKPT:
9348         moe = 3;
9349         break;
9350     case EC_VECTORCATCH:
9351         moe = 5;
9352         break;
9353     default:
9354         moe = 0;
9355         break;
9356     }
9357 
9358     if (moe) {
9359         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9360     }
9361 
9362     if (env->exception.target_el == 2) {
9363         arm_cpu_do_interrupt_aarch32_hyp(cs);
9364         return;
9365     }
9366 
9367     switch (cs->exception_index) {
9368     case EXCP_UDEF:
9369         new_mode = ARM_CPU_MODE_UND;
9370         addr = 0x04;
9371         mask = CPSR_I;
9372         if (env->thumb)
9373             offset = 2;
9374         else
9375             offset = 4;
9376         break;
9377     case EXCP_SWI:
9378         new_mode = ARM_CPU_MODE_SVC;
9379         addr = 0x08;
9380         mask = CPSR_I;
9381         /* The PC already points to the next instruction.  */
9382         offset = 0;
9383         break;
9384     case EXCP_BKPT:
9385         /* Fall through to prefetch abort.  */
9386     case EXCP_PREFETCH_ABORT:
9387         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9388         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9389         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9390                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9391         new_mode = ARM_CPU_MODE_ABT;
9392         addr = 0x0c;
9393         mask = CPSR_A | CPSR_I;
9394         offset = 4;
9395         break;
9396     case EXCP_DATA_ABORT:
9397         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9398         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9399         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9400                       env->exception.fsr,
9401                       (uint32_t)env->exception.vaddress);
9402         new_mode = ARM_CPU_MODE_ABT;
9403         addr = 0x10;
9404         mask = CPSR_A | CPSR_I;
9405         offset = 8;
9406         break;
9407     case EXCP_IRQ:
9408         new_mode = ARM_CPU_MODE_IRQ;
9409         addr = 0x18;
9410         /* Disable IRQ and imprecise data aborts.  */
9411         mask = CPSR_A | CPSR_I;
9412         offset = 4;
9413         if (env->cp15.scr_el3 & SCR_IRQ) {
9414             /* IRQ routed to monitor mode */
9415             new_mode = ARM_CPU_MODE_MON;
9416             mask |= CPSR_F;
9417         }
9418         break;
9419     case EXCP_FIQ:
9420         new_mode = ARM_CPU_MODE_FIQ;
9421         addr = 0x1c;
9422         /* Disable FIQ, IRQ and imprecise data aborts.  */
9423         mask = CPSR_A | CPSR_I | CPSR_F;
9424         if (env->cp15.scr_el3 & SCR_FIQ) {
9425             /* FIQ routed to monitor mode */
9426             new_mode = ARM_CPU_MODE_MON;
9427         }
9428         offset = 4;
9429         break;
9430     case EXCP_VIRQ:
9431         new_mode = ARM_CPU_MODE_IRQ;
9432         addr = 0x18;
9433         /* Disable IRQ and imprecise data aborts.  */
9434         mask = CPSR_A | CPSR_I;
9435         offset = 4;
9436         break;
9437     case EXCP_VFIQ:
9438         new_mode = ARM_CPU_MODE_FIQ;
9439         addr = 0x1c;
9440         /* Disable FIQ, IRQ and imprecise data aborts.  */
9441         mask = CPSR_A | CPSR_I | CPSR_F;
9442         offset = 4;
9443         break;
9444     case EXCP_SMC:
9445         new_mode = ARM_CPU_MODE_MON;
9446         addr = 0x08;
9447         mask = CPSR_A | CPSR_I | CPSR_F;
9448         offset = 0;
9449         break;
9450     default:
9451         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9452         return; /* Never happens.  Keep compiler happy.  */
9453     }
9454 
9455     if (new_mode == ARM_CPU_MODE_MON) {
9456         addr += env->cp15.mvbar;
9457     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9458         /* High vectors. When enabled, base address cannot be remapped. */
9459         addr += 0xffff0000;
9460     } else {
9461         /* ARM v7 architectures provide a vector base address register to remap
9462          * the interrupt vector table.
9463          * This register is only followed in non-monitor mode, and is banked.
9464          * Note: only bits 31:5 are valid.
9465          */
9466         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9467     }
9468 
9469     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9470         env->cp15.scr_el3 &= ~SCR_NS;
9471     }
9472 
9473     take_aarch32_exception(env, new_mode, mask, offset, addr);
9474 }
9475 
9476 /* Handle exception entry to a target EL which is using AArch64 */
9477 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
9478 {
9479     ARMCPU *cpu = ARM_CPU(cs);
9480     CPUARMState *env = &cpu->env;
9481     unsigned int new_el = env->exception.target_el;
9482     target_ulong addr = env->cp15.vbar_el[new_el];
9483     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
9484     unsigned int old_mode;
9485     unsigned int cur_el = arm_current_el(env);
9486 
9487     /*
9488      * Note that new_el can never be 0.  If cur_el is 0, then
9489      * el0_a64 is is_a64(), else el0_a64 is ignored.
9490      */
9491     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
9492 
9493     if (cur_el < new_el) {
9494         /* Entry vector offset depends on whether the implemented EL
9495          * immediately lower than the target level is using AArch32 or AArch64
9496          */
9497         bool is_aa64;
9498         uint64_t hcr;
9499 
9500         switch (new_el) {
9501         case 3:
9502             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
9503             break;
9504         case 2:
9505             hcr = arm_hcr_el2_eff(env);
9506             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
9507                 is_aa64 = (hcr & HCR_RW) != 0;
9508                 break;
9509             }
9510             /* fall through */
9511         case 1:
9512             is_aa64 = is_a64(env);
9513             break;
9514         default:
9515             g_assert_not_reached();
9516         }
9517 
9518         if (is_aa64) {
9519             addr += 0x400;
9520         } else {
9521             addr += 0x600;
9522         }
9523     } else if (pstate_read(env) & PSTATE_SP) {
9524         addr += 0x200;
9525     }
9526 
9527     switch (cs->exception_index) {
9528     case EXCP_PREFETCH_ABORT:
9529     case EXCP_DATA_ABORT:
9530         env->cp15.far_el[new_el] = env->exception.vaddress;
9531         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
9532                       env->cp15.far_el[new_el]);
9533         /* fall through */
9534     case EXCP_BKPT:
9535     case EXCP_UDEF:
9536     case EXCP_SWI:
9537     case EXCP_HVC:
9538     case EXCP_HYP_TRAP:
9539     case EXCP_SMC:
9540         if (syn_get_ec(env->exception.syndrome) == EC_ADVSIMDFPACCESSTRAP) {
9541             /*
9542              * QEMU internal FP/SIMD syndromes from AArch32 include the
9543              * TA and coproc fields which are only exposed if the exception
9544              * is taken to AArch32 Hyp mode. Mask them out to get a valid
9545              * AArch64 format syndrome.
9546              */
9547             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
9548         }
9549         env->cp15.esr_el[new_el] = env->exception.syndrome;
9550         break;
9551     case EXCP_IRQ:
9552     case EXCP_VIRQ:
9553         addr += 0x80;
9554         break;
9555     case EXCP_FIQ:
9556     case EXCP_VFIQ:
9557         addr += 0x100;
9558         break;
9559     default:
9560         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9561     }
9562 
9563     if (is_a64(env)) {
9564         old_mode = pstate_read(env);
9565         aarch64_save_sp(env, arm_current_el(env));
9566         env->elr_el[new_el] = env->pc;
9567     } else {
9568         old_mode = cpsr_read(env);
9569         env->elr_el[new_el] = env->regs[15];
9570 
9571         aarch64_sync_32_to_64(env);
9572 
9573         env->condexec_bits = 0;
9574     }
9575     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
9576 
9577     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
9578                   env->elr_el[new_el]);
9579 
9580     if (cpu_isar_feature(aa64_pan, cpu)) {
9581         /* The value of PSTATE.PAN is normally preserved, except when ... */
9582         new_mode |= old_mode & PSTATE_PAN;
9583         switch (new_el) {
9584         case 2:
9585             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
9586             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
9587                 != (HCR_E2H | HCR_TGE)) {
9588                 break;
9589             }
9590             /* fall through */
9591         case 1:
9592             /* ... the target is EL1 ... */
9593             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
9594             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
9595                 new_mode |= PSTATE_PAN;
9596             }
9597             break;
9598         }
9599     }
9600 
9601     pstate_write(env, PSTATE_DAIF | new_mode);
9602     env->aarch64 = 1;
9603     aarch64_restore_sp(env, new_el);
9604     helper_rebuild_hflags_a64(env, new_el);
9605 
9606     env->pc = addr;
9607 
9608     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
9609                   new_el, env->pc, pstate_read(env));
9610 }
9611 
9612 /*
9613  * Do semihosting call and set the appropriate return value. All the
9614  * permission and validity checks have been done at translate time.
9615  *
9616  * We only see semihosting exceptions in TCG only as they are not
9617  * trapped to the hypervisor in KVM.
9618  */
9619 #ifdef CONFIG_TCG
9620 static void handle_semihosting(CPUState *cs)
9621 {
9622     ARMCPU *cpu = ARM_CPU(cs);
9623     CPUARMState *env = &cpu->env;
9624 
9625     if (is_a64(env)) {
9626         qemu_log_mask(CPU_LOG_INT,
9627                       "...handling as semihosting call 0x%" PRIx64 "\n",
9628                       env->xregs[0]);
9629         env->xregs[0] = do_arm_semihosting(env);
9630         env->pc += 4;
9631     } else {
9632         qemu_log_mask(CPU_LOG_INT,
9633                       "...handling as semihosting call 0x%x\n",
9634                       env->regs[0]);
9635         env->regs[0] = do_arm_semihosting(env);
9636         env->regs[15] += env->thumb ? 2 : 4;
9637     }
9638 }
9639 #endif
9640 
9641 /* Handle a CPU exception for A and R profile CPUs.
9642  * Do any appropriate logging, handle PSCI calls, and then hand off
9643  * to the AArch64-entry or AArch32-entry function depending on the
9644  * target exception level's register width.
9645  */
9646 void arm_cpu_do_interrupt(CPUState *cs)
9647 {
9648     ARMCPU *cpu = ARM_CPU(cs);
9649     CPUARMState *env = &cpu->env;
9650     unsigned int new_el = env->exception.target_el;
9651 
9652     assert(!arm_feature(env, ARM_FEATURE_M));
9653 
9654     arm_log_exception(cs->exception_index);
9655     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
9656                   new_el);
9657     if (qemu_loglevel_mask(CPU_LOG_INT)
9658         && !excp_is_internal(cs->exception_index)) {
9659         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
9660                       syn_get_ec(env->exception.syndrome),
9661                       env->exception.syndrome);
9662     }
9663 
9664     if (arm_is_psci_call(cpu, cs->exception_index)) {
9665         arm_handle_psci_call(cpu);
9666         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
9667         return;
9668     }
9669 
9670     /*
9671      * Semihosting semantics depend on the register width of the code
9672      * that caused the exception, not the target exception level, so
9673      * must be handled here.
9674      */
9675 #ifdef CONFIG_TCG
9676     if (cs->exception_index == EXCP_SEMIHOST) {
9677         handle_semihosting(cs);
9678         return;
9679     }
9680 #endif
9681 
9682     /* Hooks may change global state so BQL should be held, also the
9683      * BQL needs to be held for any modification of
9684      * cs->interrupt_request.
9685      */
9686     g_assert(qemu_mutex_iothread_locked());
9687 
9688     arm_call_pre_el_change_hook(cpu);
9689 
9690     assert(!excp_is_internal(cs->exception_index));
9691     if (arm_el_is_aa64(env, new_el)) {
9692         arm_cpu_do_interrupt_aarch64(cs);
9693     } else {
9694         arm_cpu_do_interrupt_aarch32(cs);
9695     }
9696 
9697     arm_call_el_change_hook(cpu);
9698 
9699     if (!kvm_enabled()) {
9700         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
9701     }
9702 }
9703 #endif /* !CONFIG_USER_ONLY */
9704 
9705 /* Return the exception level which controls this address translation regime */
9706 static uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
9707 {
9708     switch (mmu_idx) {
9709     case ARMMMUIdx_E20_0:
9710     case ARMMMUIdx_E20_2:
9711     case ARMMMUIdx_E20_2_PAN:
9712     case ARMMMUIdx_Stage2:
9713     case ARMMMUIdx_E2:
9714         return 2;
9715     case ARMMMUIdx_SE3:
9716         return 3;
9717     case ARMMMUIdx_SE10_0:
9718         return arm_el_is_aa64(env, 3) ? 1 : 3;
9719     case ARMMMUIdx_SE10_1:
9720     case ARMMMUIdx_SE10_1_PAN:
9721     case ARMMMUIdx_Stage1_E0:
9722     case ARMMMUIdx_Stage1_E1:
9723     case ARMMMUIdx_Stage1_E1_PAN:
9724     case ARMMMUIdx_E10_0:
9725     case ARMMMUIdx_E10_1:
9726     case ARMMMUIdx_E10_1_PAN:
9727     case ARMMMUIdx_MPrivNegPri:
9728     case ARMMMUIdx_MUserNegPri:
9729     case ARMMMUIdx_MPriv:
9730     case ARMMMUIdx_MUser:
9731     case ARMMMUIdx_MSPrivNegPri:
9732     case ARMMMUIdx_MSUserNegPri:
9733     case ARMMMUIdx_MSPriv:
9734     case ARMMMUIdx_MSUser:
9735         return 1;
9736     default:
9737         g_assert_not_reached();
9738     }
9739 }
9740 
9741 uint64_t arm_sctlr(CPUARMState *env, int el)
9742 {
9743     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
9744     if (el == 0) {
9745         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
9746         el = (mmu_idx == ARMMMUIdx_E20_0 ? 2 : 1);
9747     }
9748     return env->cp15.sctlr_el[el];
9749 }
9750 
9751 /* Return the SCTLR value which controls this address translation regime */
9752 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
9753 {
9754     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
9755 }
9756 
9757 #ifndef CONFIG_USER_ONLY
9758 
9759 /* Return true if the specified stage of address translation is disabled */
9760 static inline bool regime_translation_disabled(CPUARMState *env,
9761                                                ARMMMUIdx mmu_idx)
9762 {
9763     if (arm_feature(env, ARM_FEATURE_M)) {
9764         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
9765                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
9766         case R_V7M_MPU_CTRL_ENABLE_MASK:
9767             /* Enabled, but not for HardFault and NMI */
9768             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
9769         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
9770             /* Enabled for all cases */
9771             return false;
9772         case 0:
9773         default:
9774             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
9775              * we warned about that in armv7m_nvic.c when the guest set it.
9776              */
9777             return true;
9778         }
9779     }
9780 
9781     if (mmu_idx == ARMMMUIdx_Stage2) {
9782         /* HCR.DC means HCR.VM behaves as 1 */
9783         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
9784     }
9785 
9786     if (env->cp15.hcr_el2 & HCR_TGE) {
9787         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
9788         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
9789             return true;
9790         }
9791     }
9792 
9793     if ((env->cp15.hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
9794         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
9795         return true;
9796     }
9797 
9798     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
9799 }
9800 
9801 static inline bool regime_translation_big_endian(CPUARMState *env,
9802                                                  ARMMMUIdx mmu_idx)
9803 {
9804     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
9805 }
9806 
9807 /* Return the TTBR associated with this translation regime */
9808 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
9809                                    int ttbrn)
9810 {
9811     if (mmu_idx == ARMMMUIdx_Stage2) {
9812         return env->cp15.vttbr_el2;
9813     }
9814     if (ttbrn == 0) {
9815         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
9816     } else {
9817         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
9818     }
9819 }
9820 
9821 #endif /* !CONFIG_USER_ONLY */
9822 
9823 /* Return the TCR controlling this translation regime */
9824 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
9825 {
9826     if (mmu_idx == ARMMMUIdx_Stage2) {
9827         return &env->cp15.vtcr_el2;
9828     }
9829     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
9830 }
9831 
9832 /* Convert a possible stage1+2 MMU index into the appropriate
9833  * stage 1 MMU index
9834  */
9835 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
9836 {
9837     switch (mmu_idx) {
9838     case ARMMMUIdx_E10_0:
9839         return ARMMMUIdx_Stage1_E0;
9840     case ARMMMUIdx_E10_1:
9841         return ARMMMUIdx_Stage1_E1;
9842     case ARMMMUIdx_E10_1_PAN:
9843         return ARMMMUIdx_Stage1_E1_PAN;
9844     default:
9845         return mmu_idx;
9846     }
9847 }
9848 
9849 /* Return true if the translation regime is using LPAE format page tables */
9850 static inline bool regime_using_lpae_format(CPUARMState *env,
9851                                             ARMMMUIdx mmu_idx)
9852 {
9853     int el = regime_el(env, mmu_idx);
9854     if (el == 2 || arm_el_is_aa64(env, el)) {
9855         return true;
9856     }
9857     if (arm_feature(env, ARM_FEATURE_LPAE)
9858         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
9859         return true;
9860     }
9861     return false;
9862 }
9863 
9864 /* Returns true if the stage 1 translation regime is using LPAE format page
9865  * tables. Used when raising alignment exceptions, whose FSR changes depending
9866  * on whether the long or short descriptor format is in use. */
9867 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
9868 {
9869     mmu_idx = stage_1_mmu_idx(mmu_idx);
9870 
9871     return regime_using_lpae_format(env, mmu_idx);
9872 }
9873 
9874 #ifndef CONFIG_USER_ONLY
9875 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
9876 {
9877     switch (mmu_idx) {
9878     case ARMMMUIdx_SE10_0:
9879     case ARMMMUIdx_E20_0:
9880     case ARMMMUIdx_Stage1_E0:
9881     case ARMMMUIdx_MUser:
9882     case ARMMMUIdx_MSUser:
9883     case ARMMMUIdx_MUserNegPri:
9884     case ARMMMUIdx_MSUserNegPri:
9885         return true;
9886     default:
9887         return false;
9888     case ARMMMUIdx_E10_0:
9889     case ARMMMUIdx_E10_1:
9890     case ARMMMUIdx_E10_1_PAN:
9891         g_assert_not_reached();
9892     }
9893 }
9894 
9895 /* Translate section/page access permissions to page
9896  * R/W protection flags
9897  *
9898  * @env:         CPUARMState
9899  * @mmu_idx:     MMU index indicating required translation regime
9900  * @ap:          The 3-bit access permissions (AP[2:0])
9901  * @domain_prot: The 2-bit domain access permissions
9902  */
9903 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
9904                                 int ap, int domain_prot)
9905 {
9906     bool is_user = regime_is_user(env, mmu_idx);
9907 
9908     if (domain_prot == 3) {
9909         return PAGE_READ | PAGE_WRITE;
9910     }
9911 
9912     switch (ap) {
9913     case 0:
9914         if (arm_feature(env, ARM_FEATURE_V7)) {
9915             return 0;
9916         }
9917         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
9918         case SCTLR_S:
9919             return is_user ? 0 : PAGE_READ;
9920         case SCTLR_R:
9921             return PAGE_READ;
9922         default:
9923             return 0;
9924         }
9925     case 1:
9926         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
9927     case 2:
9928         if (is_user) {
9929             return PAGE_READ;
9930         } else {
9931             return PAGE_READ | PAGE_WRITE;
9932         }
9933     case 3:
9934         return PAGE_READ | PAGE_WRITE;
9935     case 4: /* Reserved.  */
9936         return 0;
9937     case 5:
9938         return is_user ? 0 : PAGE_READ;
9939     case 6:
9940         return PAGE_READ;
9941     case 7:
9942         if (!arm_feature(env, ARM_FEATURE_V6K)) {
9943             return 0;
9944         }
9945         return PAGE_READ;
9946     default:
9947         g_assert_not_reached();
9948     }
9949 }
9950 
9951 /* Translate section/page access permissions to page
9952  * R/W protection flags.
9953  *
9954  * @ap:      The 2-bit simple AP (AP[2:1])
9955  * @is_user: TRUE if accessing from PL0
9956  */
9957 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
9958 {
9959     switch (ap) {
9960     case 0:
9961         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
9962     case 1:
9963         return PAGE_READ | PAGE_WRITE;
9964     case 2:
9965         return is_user ? 0 : PAGE_READ;
9966     case 3:
9967         return PAGE_READ;
9968     default:
9969         g_assert_not_reached();
9970     }
9971 }
9972 
9973 static inline int
9974 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
9975 {
9976     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
9977 }
9978 
9979 /* Translate S2 section/page access permissions to protection flags
9980  *
9981  * @env:     CPUARMState
9982  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
9983  * @xn:      XN (execute-never) bit
9984  */
9985 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
9986 {
9987     int prot = 0;
9988 
9989     if (s2ap & 1) {
9990         prot |= PAGE_READ;
9991     }
9992     if (s2ap & 2) {
9993         prot |= PAGE_WRITE;
9994     }
9995     if (!xn) {
9996         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
9997             prot |= PAGE_EXEC;
9998         }
9999     }
10000     return prot;
10001 }
10002 
10003 /* Translate section/page access permissions to protection flags
10004  *
10005  * @env:     CPUARMState
10006  * @mmu_idx: MMU index indicating required translation regime
10007  * @is_aa64: TRUE if AArch64
10008  * @ap:      The 2-bit simple AP (AP[2:1])
10009  * @ns:      NS (non-secure) bit
10010  * @xn:      XN (execute-never) bit
10011  * @pxn:     PXN (privileged execute-never) bit
10012  */
10013 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10014                       int ap, int ns, int xn, int pxn)
10015 {
10016     bool is_user = regime_is_user(env, mmu_idx);
10017     int prot_rw, user_rw;
10018     bool have_wxn;
10019     int wxn = 0;
10020 
10021     assert(mmu_idx != ARMMMUIdx_Stage2);
10022 
10023     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10024     if (is_user) {
10025         prot_rw = user_rw;
10026     } else {
10027         if (user_rw && regime_is_pan(env, mmu_idx)) {
10028             /* PAN forbids data accesses but doesn't affect insn fetch */
10029             prot_rw = 0;
10030         } else {
10031             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10032         }
10033     }
10034 
10035     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10036         return prot_rw;
10037     }
10038 
10039     /* TODO have_wxn should be replaced with
10040      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10041      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10042      * compatible processors have EL2, which is required for [U]WXN.
10043      */
10044     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10045 
10046     if (have_wxn) {
10047         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10048     }
10049 
10050     if (is_aa64) {
10051         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10052             xn = pxn || (user_rw & PAGE_WRITE);
10053         }
10054     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10055         switch (regime_el(env, mmu_idx)) {
10056         case 1:
10057         case 3:
10058             if (is_user) {
10059                 xn = xn || !(user_rw & PAGE_READ);
10060             } else {
10061                 int uwxn = 0;
10062                 if (have_wxn) {
10063                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10064                 }
10065                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10066                      (uwxn && (user_rw & PAGE_WRITE));
10067             }
10068             break;
10069         case 2:
10070             break;
10071         }
10072     } else {
10073         xn = wxn = 0;
10074     }
10075 
10076     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10077         return prot_rw;
10078     }
10079     return prot_rw | PAGE_EXEC;
10080 }
10081 
10082 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10083                                      uint32_t *table, uint32_t address)
10084 {
10085     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10086     TCR *tcr = regime_tcr(env, mmu_idx);
10087 
10088     if (address & tcr->mask) {
10089         if (tcr->raw_tcr & TTBCR_PD1) {
10090             /* Translation table walk disabled for TTBR1 */
10091             return false;
10092         }
10093         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10094     } else {
10095         if (tcr->raw_tcr & TTBCR_PD0) {
10096             /* Translation table walk disabled for TTBR0 */
10097             return false;
10098         }
10099         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10100     }
10101     *table |= (address >> 18) & 0x3ffc;
10102     return true;
10103 }
10104 
10105 /* Translate a S1 pagetable walk through S2 if needed.  */
10106 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10107                                hwaddr addr, MemTxAttrs txattrs,
10108                                ARMMMUFaultInfo *fi)
10109 {
10110     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10111         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10112         target_ulong s2size;
10113         hwaddr s2pa;
10114         int s2prot;
10115         int ret;
10116         ARMCacheAttrs cacheattrs = {};
10117         ARMCacheAttrs *pcacheattrs = NULL;
10118 
10119         if (env->cp15.hcr_el2 & HCR_PTW) {
10120             /*
10121              * PTW means we must fault if this S1 walk touches S2 Device
10122              * memory; otherwise we don't care about the attributes and can
10123              * save the S2 translation the effort of computing them.
10124              */
10125             pcacheattrs = &cacheattrs;
10126         }
10127 
10128         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_Stage2, &s2pa,
10129                                  &txattrs, &s2prot, &s2size, fi, pcacheattrs);
10130         if (ret) {
10131             assert(fi->type != ARMFault_None);
10132             fi->s2addr = addr;
10133             fi->stage2 = true;
10134             fi->s1ptw = true;
10135             return ~0;
10136         }
10137         if (pcacheattrs && (pcacheattrs->attrs & 0xf0) == 0) {
10138             /* Access was to Device memory: generate Permission fault */
10139             fi->type = ARMFault_Permission;
10140             fi->s2addr = addr;
10141             fi->stage2 = true;
10142             fi->s1ptw = true;
10143             return ~0;
10144         }
10145         addr = s2pa;
10146     }
10147     return addr;
10148 }
10149 
10150 /* All loads done in the course of a page table walk go through here. */
10151 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10152                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10153 {
10154     ARMCPU *cpu = ARM_CPU(cs);
10155     CPUARMState *env = &cpu->env;
10156     MemTxAttrs attrs = {};
10157     MemTxResult result = MEMTX_OK;
10158     AddressSpace *as;
10159     uint32_t data;
10160 
10161     attrs.secure = is_secure;
10162     as = arm_addressspace(cs, attrs);
10163     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10164     if (fi->s1ptw) {
10165         return 0;
10166     }
10167     if (regime_translation_big_endian(env, mmu_idx)) {
10168         data = address_space_ldl_be(as, addr, attrs, &result);
10169     } else {
10170         data = address_space_ldl_le(as, addr, attrs, &result);
10171     }
10172     if (result == MEMTX_OK) {
10173         return data;
10174     }
10175     fi->type = ARMFault_SyncExternalOnWalk;
10176     fi->ea = arm_extabort_type(result);
10177     return 0;
10178 }
10179 
10180 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10181                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10182 {
10183     ARMCPU *cpu = ARM_CPU(cs);
10184     CPUARMState *env = &cpu->env;
10185     MemTxAttrs attrs = {};
10186     MemTxResult result = MEMTX_OK;
10187     AddressSpace *as;
10188     uint64_t data;
10189 
10190     attrs.secure = is_secure;
10191     as = arm_addressspace(cs, attrs);
10192     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10193     if (fi->s1ptw) {
10194         return 0;
10195     }
10196     if (regime_translation_big_endian(env, mmu_idx)) {
10197         data = address_space_ldq_be(as, addr, attrs, &result);
10198     } else {
10199         data = address_space_ldq_le(as, addr, attrs, &result);
10200     }
10201     if (result == MEMTX_OK) {
10202         return data;
10203     }
10204     fi->type = ARMFault_SyncExternalOnWalk;
10205     fi->ea = arm_extabort_type(result);
10206     return 0;
10207 }
10208 
10209 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10210                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10211                              hwaddr *phys_ptr, int *prot,
10212                              target_ulong *page_size,
10213                              ARMMMUFaultInfo *fi)
10214 {
10215     CPUState *cs = env_cpu(env);
10216     int level = 1;
10217     uint32_t table;
10218     uint32_t desc;
10219     int type;
10220     int ap;
10221     int domain = 0;
10222     int domain_prot;
10223     hwaddr phys_addr;
10224     uint32_t dacr;
10225 
10226     /* Pagetable walk.  */
10227     /* Lookup l1 descriptor.  */
10228     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10229         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10230         fi->type = ARMFault_Translation;
10231         goto do_fault;
10232     }
10233     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10234                        mmu_idx, fi);
10235     if (fi->type != ARMFault_None) {
10236         goto do_fault;
10237     }
10238     type = (desc & 3);
10239     domain = (desc >> 5) & 0x0f;
10240     if (regime_el(env, mmu_idx) == 1) {
10241         dacr = env->cp15.dacr_ns;
10242     } else {
10243         dacr = env->cp15.dacr_s;
10244     }
10245     domain_prot = (dacr >> (domain * 2)) & 3;
10246     if (type == 0) {
10247         /* Section translation fault.  */
10248         fi->type = ARMFault_Translation;
10249         goto do_fault;
10250     }
10251     if (type != 2) {
10252         level = 2;
10253     }
10254     if (domain_prot == 0 || domain_prot == 2) {
10255         fi->type = ARMFault_Domain;
10256         goto do_fault;
10257     }
10258     if (type == 2) {
10259         /* 1Mb section.  */
10260         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10261         ap = (desc >> 10) & 3;
10262         *page_size = 1024 * 1024;
10263     } else {
10264         /* Lookup l2 entry.  */
10265         if (type == 1) {
10266             /* Coarse pagetable.  */
10267             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10268         } else {
10269             /* Fine pagetable.  */
10270             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10271         }
10272         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10273                            mmu_idx, fi);
10274         if (fi->type != ARMFault_None) {
10275             goto do_fault;
10276         }
10277         switch (desc & 3) {
10278         case 0: /* Page translation fault.  */
10279             fi->type = ARMFault_Translation;
10280             goto do_fault;
10281         case 1: /* 64k page.  */
10282             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10283             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10284             *page_size = 0x10000;
10285             break;
10286         case 2: /* 4k page.  */
10287             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10288             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10289             *page_size = 0x1000;
10290             break;
10291         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10292             if (type == 1) {
10293                 /* ARMv6/XScale extended small page format */
10294                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10295                     || arm_feature(env, ARM_FEATURE_V6)) {
10296                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10297                     *page_size = 0x1000;
10298                 } else {
10299                     /* UNPREDICTABLE in ARMv5; we choose to take a
10300                      * page translation fault.
10301                      */
10302                     fi->type = ARMFault_Translation;
10303                     goto do_fault;
10304                 }
10305             } else {
10306                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10307                 *page_size = 0x400;
10308             }
10309             ap = (desc >> 4) & 3;
10310             break;
10311         default:
10312             /* Never happens, but compiler isn't smart enough to tell.  */
10313             abort();
10314         }
10315     }
10316     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10317     *prot |= *prot ? PAGE_EXEC : 0;
10318     if (!(*prot & (1 << access_type))) {
10319         /* Access permission fault.  */
10320         fi->type = ARMFault_Permission;
10321         goto do_fault;
10322     }
10323     *phys_ptr = phys_addr;
10324     return false;
10325 do_fault:
10326     fi->domain = domain;
10327     fi->level = level;
10328     return true;
10329 }
10330 
10331 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10332                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10333                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10334                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10335 {
10336     CPUState *cs = env_cpu(env);
10337     int level = 1;
10338     uint32_t table;
10339     uint32_t desc;
10340     uint32_t xn;
10341     uint32_t pxn = 0;
10342     int type;
10343     int ap;
10344     int domain = 0;
10345     int domain_prot;
10346     hwaddr phys_addr;
10347     uint32_t dacr;
10348     bool ns;
10349 
10350     /* Pagetable walk.  */
10351     /* Lookup l1 descriptor.  */
10352     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10353         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10354         fi->type = ARMFault_Translation;
10355         goto do_fault;
10356     }
10357     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10358                        mmu_idx, fi);
10359     if (fi->type != ARMFault_None) {
10360         goto do_fault;
10361     }
10362     type = (desc & 3);
10363     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
10364         /* Section translation fault, or attempt to use the encoding
10365          * which is Reserved on implementations without PXN.
10366          */
10367         fi->type = ARMFault_Translation;
10368         goto do_fault;
10369     }
10370     if ((type == 1) || !(desc & (1 << 18))) {
10371         /* Page or Section.  */
10372         domain = (desc >> 5) & 0x0f;
10373     }
10374     if (regime_el(env, mmu_idx) == 1) {
10375         dacr = env->cp15.dacr_ns;
10376     } else {
10377         dacr = env->cp15.dacr_s;
10378     }
10379     if (type == 1) {
10380         level = 2;
10381     }
10382     domain_prot = (dacr >> (domain * 2)) & 3;
10383     if (domain_prot == 0 || domain_prot == 2) {
10384         /* Section or Page domain fault */
10385         fi->type = ARMFault_Domain;
10386         goto do_fault;
10387     }
10388     if (type != 1) {
10389         if (desc & (1 << 18)) {
10390             /* Supersection.  */
10391             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
10392             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
10393             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
10394             *page_size = 0x1000000;
10395         } else {
10396             /* Section.  */
10397             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10398             *page_size = 0x100000;
10399         }
10400         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
10401         xn = desc & (1 << 4);
10402         pxn = desc & 1;
10403         ns = extract32(desc, 19, 1);
10404     } else {
10405         if (arm_feature(env, ARM_FEATURE_PXN)) {
10406             pxn = (desc >> 2) & 1;
10407         }
10408         ns = extract32(desc, 3, 1);
10409         /* Lookup l2 entry.  */
10410         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10411         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10412                            mmu_idx, fi);
10413         if (fi->type != ARMFault_None) {
10414             goto do_fault;
10415         }
10416         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
10417         switch (desc & 3) {
10418         case 0: /* Page translation fault.  */
10419             fi->type = ARMFault_Translation;
10420             goto do_fault;
10421         case 1: /* 64k page.  */
10422             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10423             xn = desc & (1 << 15);
10424             *page_size = 0x10000;
10425             break;
10426         case 2: case 3: /* 4k page.  */
10427             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10428             xn = desc & 1;
10429             *page_size = 0x1000;
10430             break;
10431         default:
10432             /* Never happens, but compiler isn't smart enough to tell.  */
10433             abort();
10434         }
10435     }
10436     if (domain_prot == 3) {
10437         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10438     } else {
10439         if (pxn && !regime_is_user(env, mmu_idx)) {
10440             xn = 1;
10441         }
10442         if (xn && access_type == MMU_INST_FETCH) {
10443             fi->type = ARMFault_Permission;
10444             goto do_fault;
10445         }
10446 
10447         if (arm_feature(env, ARM_FEATURE_V6K) &&
10448                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
10449             /* The simplified model uses AP[0] as an access control bit.  */
10450             if ((ap & 1) == 0) {
10451                 /* Access flag fault.  */
10452                 fi->type = ARMFault_AccessFlag;
10453                 goto do_fault;
10454             }
10455             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
10456         } else {
10457             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10458         }
10459         if (*prot && !xn) {
10460             *prot |= PAGE_EXEC;
10461         }
10462         if (!(*prot & (1 << access_type))) {
10463             /* Access permission fault.  */
10464             fi->type = ARMFault_Permission;
10465             goto do_fault;
10466         }
10467     }
10468     if (ns) {
10469         /* The NS bit will (as required by the architecture) have no effect if
10470          * the CPU doesn't support TZ or this is a non-secure translation
10471          * regime, because the attribute will already be non-secure.
10472          */
10473         attrs->secure = false;
10474     }
10475     *phys_ptr = phys_addr;
10476     return false;
10477 do_fault:
10478     fi->domain = domain;
10479     fi->level = level;
10480     return true;
10481 }
10482 
10483 /*
10484  * check_s2_mmu_setup
10485  * @cpu:        ARMCPU
10486  * @is_aa64:    True if the translation regime is in AArch64 state
10487  * @startlevel: Suggested starting level
10488  * @inputsize:  Bitsize of IPAs
10489  * @stride:     Page-table stride (See the ARM ARM)
10490  *
10491  * Returns true if the suggested S2 translation parameters are OK and
10492  * false otherwise.
10493  */
10494 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
10495                                int inputsize, int stride)
10496 {
10497     const int grainsize = stride + 3;
10498     int startsizecheck;
10499 
10500     /* Negative levels are never allowed.  */
10501     if (level < 0) {
10502         return false;
10503     }
10504 
10505     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
10506     if (startsizecheck < 1 || startsizecheck > stride + 4) {
10507         return false;
10508     }
10509 
10510     if (is_aa64) {
10511         CPUARMState *env = &cpu->env;
10512         unsigned int pamax = arm_pamax(cpu);
10513 
10514         switch (stride) {
10515         case 13: /* 64KB Pages.  */
10516             if (level == 0 || (level == 1 && pamax <= 42)) {
10517                 return false;
10518             }
10519             break;
10520         case 11: /* 16KB Pages.  */
10521             if (level == 0 || (level == 1 && pamax <= 40)) {
10522                 return false;
10523             }
10524             break;
10525         case 9: /* 4KB Pages.  */
10526             if (level == 0 && pamax <= 42) {
10527                 return false;
10528             }
10529             break;
10530         default:
10531             g_assert_not_reached();
10532         }
10533 
10534         /* Inputsize checks.  */
10535         if (inputsize > pamax &&
10536             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
10537             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
10538             return false;
10539         }
10540     } else {
10541         /* AArch32 only supports 4KB pages. Assert on that.  */
10542         assert(stride == 9);
10543 
10544         if (level == 0) {
10545             return false;
10546         }
10547     }
10548     return true;
10549 }
10550 
10551 /* Translate from the 4-bit stage 2 representation of
10552  * memory attributes (without cache-allocation hints) to
10553  * the 8-bit representation of the stage 1 MAIR registers
10554  * (which includes allocation hints).
10555  *
10556  * ref: shared/translation/attrs/S2AttrDecode()
10557  *      .../S2ConvertAttrsHints()
10558  */
10559 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
10560 {
10561     uint8_t hiattr = extract32(s2attrs, 2, 2);
10562     uint8_t loattr = extract32(s2attrs, 0, 2);
10563     uint8_t hihint = 0, lohint = 0;
10564 
10565     if (hiattr != 0) { /* normal memory */
10566         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
10567             hiattr = loattr = 1; /* non-cacheable */
10568         } else {
10569             if (hiattr != 1) { /* Write-through or write-back */
10570                 hihint = 3; /* RW allocate */
10571             }
10572             if (loattr != 1) { /* Write-through or write-back */
10573                 lohint = 3; /* RW allocate */
10574             }
10575         }
10576     }
10577 
10578     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
10579 }
10580 #endif /* !CONFIG_USER_ONLY */
10581 
10582 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
10583 {
10584     if (regime_has_2_ranges(mmu_idx)) {
10585         return extract64(tcr, 37, 2);
10586     } else if (mmu_idx == ARMMMUIdx_Stage2) {
10587         return 0; /* VTCR_EL2 */
10588     } else {
10589         /* Replicate the single TBI bit so we always have 2 bits.  */
10590         return extract32(tcr, 20, 1) * 3;
10591     }
10592 }
10593 
10594 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
10595 {
10596     if (regime_has_2_ranges(mmu_idx)) {
10597         return extract64(tcr, 51, 2);
10598     } else if (mmu_idx == ARMMMUIdx_Stage2) {
10599         return 0; /* VTCR_EL2 */
10600     } else {
10601         /* Replicate the single TBID bit so we always have 2 bits.  */
10602         return extract32(tcr, 29, 1) * 3;
10603     }
10604 }
10605 
10606 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
10607                                    ARMMMUIdx mmu_idx, bool data)
10608 {
10609     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
10610     bool epd, hpd, using16k, using64k;
10611     int select, tsz, tbi;
10612 
10613     if (!regime_has_2_ranges(mmu_idx)) {
10614         select = 0;
10615         tsz = extract32(tcr, 0, 6);
10616         using64k = extract32(tcr, 14, 1);
10617         using16k = extract32(tcr, 15, 1);
10618         if (mmu_idx == ARMMMUIdx_Stage2) {
10619             /* VTCR_EL2 */
10620             hpd = false;
10621         } else {
10622             hpd = extract32(tcr, 24, 1);
10623         }
10624         epd = false;
10625     } else {
10626         /*
10627          * Bit 55 is always between the two regions, and is canonical for
10628          * determining if address tagging is enabled.
10629          */
10630         select = extract64(va, 55, 1);
10631         if (!select) {
10632             tsz = extract32(tcr, 0, 6);
10633             epd = extract32(tcr, 7, 1);
10634             using64k = extract32(tcr, 14, 1);
10635             using16k = extract32(tcr, 15, 1);
10636             hpd = extract64(tcr, 41, 1);
10637         } else {
10638             int tg = extract32(tcr, 30, 2);
10639             using16k = tg == 1;
10640             using64k = tg == 3;
10641             tsz = extract32(tcr, 16, 6);
10642             epd = extract32(tcr, 23, 1);
10643             hpd = extract64(tcr, 42, 1);
10644         }
10645     }
10646     tsz = MIN(tsz, 39);  /* TODO: ARMv8.4-TTST */
10647     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
10648 
10649     /* Present TBI as a composite with TBID.  */
10650     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
10651     if (!data) {
10652         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
10653     }
10654     tbi = (tbi >> select) & 1;
10655 
10656     return (ARMVAParameters) {
10657         .tsz = tsz,
10658         .select = select,
10659         .tbi = tbi,
10660         .epd = epd,
10661         .hpd = hpd,
10662         .using16k = using16k,
10663         .using64k = using64k,
10664     };
10665 }
10666 
10667 #ifndef CONFIG_USER_ONLY
10668 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
10669                                           ARMMMUIdx mmu_idx)
10670 {
10671     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
10672     uint32_t el = regime_el(env, mmu_idx);
10673     int select, tsz;
10674     bool epd, hpd;
10675 
10676     if (mmu_idx == ARMMMUIdx_Stage2) {
10677         /* VTCR */
10678         bool sext = extract32(tcr, 4, 1);
10679         bool sign = extract32(tcr, 3, 1);
10680 
10681         /*
10682          * If the sign-extend bit is not the same as t0sz[3], the result
10683          * is unpredictable. Flag this as a guest error.
10684          */
10685         if (sign != sext) {
10686             qemu_log_mask(LOG_GUEST_ERROR,
10687                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
10688         }
10689         tsz = sextract32(tcr, 0, 4) + 8;
10690         select = 0;
10691         hpd = false;
10692         epd = false;
10693     } else if (el == 2) {
10694         /* HTCR */
10695         tsz = extract32(tcr, 0, 3);
10696         select = 0;
10697         hpd = extract64(tcr, 24, 1);
10698         epd = false;
10699     } else {
10700         int t0sz = extract32(tcr, 0, 3);
10701         int t1sz = extract32(tcr, 16, 3);
10702 
10703         if (t1sz == 0) {
10704             select = va > (0xffffffffu >> t0sz);
10705         } else {
10706             /* Note that we will detect errors later.  */
10707             select = va >= ~(0xffffffffu >> t1sz);
10708         }
10709         if (!select) {
10710             tsz = t0sz;
10711             epd = extract32(tcr, 7, 1);
10712             hpd = extract64(tcr, 41, 1);
10713         } else {
10714             tsz = t1sz;
10715             epd = extract32(tcr, 23, 1);
10716             hpd = extract64(tcr, 42, 1);
10717         }
10718         /* For aarch32, hpd0 is not enabled without t2e as well.  */
10719         hpd &= extract32(tcr, 6, 1);
10720     }
10721 
10722     return (ARMVAParameters) {
10723         .tsz = tsz,
10724         .select = select,
10725         .epd = epd,
10726         .hpd = hpd,
10727     };
10728 }
10729 
10730 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
10731                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
10732                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
10733                                target_ulong *page_size_ptr,
10734                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10735 {
10736     ARMCPU *cpu = env_archcpu(env);
10737     CPUState *cs = CPU(cpu);
10738     /* Read an LPAE long-descriptor translation table. */
10739     ARMFaultType fault_type = ARMFault_Translation;
10740     uint32_t level;
10741     ARMVAParameters param;
10742     uint64_t ttbr;
10743     hwaddr descaddr, indexmask, indexmask_grainsize;
10744     uint32_t tableattrs;
10745     target_ulong page_size;
10746     uint32_t attrs;
10747     int32_t stride;
10748     int addrsize, inputsize;
10749     TCR *tcr = regime_tcr(env, mmu_idx);
10750     int ap, ns, xn, pxn;
10751     uint32_t el = regime_el(env, mmu_idx);
10752     uint64_t descaddrmask;
10753     bool aarch64 = arm_el_is_aa64(env, el);
10754     bool guarded = false;
10755 
10756     /* TODO: This code does not support shareability levels. */
10757     if (aarch64) {
10758         param = aa64_va_parameters(env, address, mmu_idx,
10759                                    access_type != MMU_INST_FETCH);
10760         level = 0;
10761         addrsize = 64 - 8 * param.tbi;
10762         inputsize = 64 - param.tsz;
10763     } else {
10764         param = aa32_va_parameters(env, address, mmu_idx);
10765         level = 1;
10766         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
10767         inputsize = addrsize - param.tsz;
10768     }
10769 
10770     /*
10771      * We determined the region when collecting the parameters, but we
10772      * have not yet validated that the address is valid for the region.
10773      * Extract the top bits and verify that they all match select.
10774      *
10775      * For aa32, if inputsize == addrsize, then we have selected the
10776      * region by exclusion in aa32_va_parameters and there is no more
10777      * validation to do here.
10778      */
10779     if (inputsize < addrsize) {
10780         target_ulong top_bits = sextract64(address, inputsize,
10781                                            addrsize - inputsize);
10782         if (-top_bits != param.select) {
10783             /* The gap between the two regions is a Translation fault */
10784             fault_type = ARMFault_Translation;
10785             goto do_fault;
10786         }
10787     }
10788 
10789     if (param.using64k) {
10790         stride = 13;
10791     } else if (param.using16k) {
10792         stride = 11;
10793     } else {
10794         stride = 9;
10795     }
10796 
10797     /* Note that QEMU ignores shareability and cacheability attributes,
10798      * so we don't need to do anything with the SH, ORGN, IRGN fields
10799      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
10800      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
10801      * implement any ASID-like capability so we can ignore it (instead
10802      * we will always flush the TLB any time the ASID is changed).
10803      */
10804     ttbr = regime_ttbr(env, mmu_idx, param.select);
10805 
10806     /* Here we should have set up all the parameters for the translation:
10807      * inputsize, ttbr, epd, stride, tbi
10808      */
10809 
10810     if (param.epd) {
10811         /* Translation table walk disabled => Translation fault on TLB miss
10812          * Note: This is always 0 on 64-bit EL2 and EL3.
10813          */
10814         goto do_fault;
10815     }
10816 
10817     if (mmu_idx != ARMMMUIdx_Stage2) {
10818         /* The starting level depends on the virtual address size (which can
10819          * be up to 48 bits) and the translation granule size. It indicates
10820          * the number of strides (stride bits at a time) needed to
10821          * consume the bits of the input address. In the pseudocode this is:
10822          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
10823          * where their 'inputsize' is our 'inputsize', 'grainsize' is
10824          * our 'stride + 3' and 'stride' is our 'stride'.
10825          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
10826          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
10827          * = 4 - (inputsize - 4) / stride;
10828          */
10829         level = 4 - (inputsize - 4) / stride;
10830     } else {
10831         /* For stage 2 translations the starting level is specified by the
10832          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
10833          */
10834         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
10835         uint32_t startlevel;
10836         bool ok;
10837 
10838         if (!aarch64 || stride == 9) {
10839             /* AArch32 or 4KB pages */
10840             startlevel = 2 - sl0;
10841         } else {
10842             /* 16KB or 64KB pages */
10843             startlevel = 3 - sl0;
10844         }
10845 
10846         /* Check that the starting level is valid. */
10847         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
10848                                 inputsize, stride);
10849         if (!ok) {
10850             fault_type = ARMFault_Translation;
10851             goto do_fault;
10852         }
10853         level = startlevel;
10854     }
10855 
10856     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
10857     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
10858 
10859     /* Now we can extract the actual base address from the TTBR */
10860     descaddr = extract64(ttbr, 0, 48);
10861     /*
10862      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
10863      * and also to mask out CnP (bit 0) which could validly be non-zero.
10864      */
10865     descaddr &= ~indexmask;
10866 
10867     /* The address field in the descriptor goes up to bit 39 for ARMv7
10868      * but up to bit 47 for ARMv8, but we use the descaddrmask
10869      * up to bit 39 for AArch32, because we don't need other bits in that case
10870      * to construct next descriptor address (anyway they should be all zeroes).
10871      */
10872     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
10873                    ~indexmask_grainsize;
10874 
10875     /* Secure accesses start with the page table in secure memory and
10876      * can be downgraded to non-secure at any step. Non-secure accesses
10877      * remain non-secure. We implement this by just ORing in the NSTable/NS
10878      * bits at each step.
10879      */
10880     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
10881     for (;;) {
10882         uint64_t descriptor;
10883         bool nstable;
10884 
10885         descaddr |= (address >> (stride * (4 - level))) & indexmask;
10886         descaddr &= ~7ULL;
10887         nstable = extract32(tableattrs, 4, 1);
10888         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
10889         if (fi->type != ARMFault_None) {
10890             goto do_fault;
10891         }
10892 
10893         if (!(descriptor & 1) ||
10894             (!(descriptor & 2) && (level == 3))) {
10895             /* Invalid, or the Reserved level 3 encoding */
10896             goto do_fault;
10897         }
10898         descaddr = descriptor & descaddrmask;
10899 
10900         if ((descriptor & 2) && (level < 3)) {
10901             /* Table entry. The top five bits are attributes which may
10902              * propagate down through lower levels of the table (and
10903              * which are all arranged so that 0 means "no effect", so
10904              * we can gather them up by ORing in the bits at each level).
10905              */
10906             tableattrs |= extract64(descriptor, 59, 5);
10907             level++;
10908             indexmask = indexmask_grainsize;
10909             continue;
10910         }
10911         /* Block entry at level 1 or 2, or page entry at level 3.
10912          * These are basically the same thing, although the number
10913          * of bits we pull in from the vaddr varies.
10914          */
10915         page_size = (1ULL << ((stride * (4 - level)) + 3));
10916         descaddr |= (address & (page_size - 1));
10917         /* Extract attributes from the descriptor */
10918         attrs = extract64(descriptor, 2, 10)
10919             | (extract64(descriptor, 52, 12) << 10);
10920 
10921         if (mmu_idx == ARMMMUIdx_Stage2) {
10922             /* Stage 2 table descriptors do not include any attribute fields */
10923             break;
10924         }
10925         /* Merge in attributes from table descriptors */
10926         attrs |= nstable << 3; /* NS */
10927         guarded = extract64(descriptor, 50, 1);  /* GP */
10928         if (param.hpd) {
10929             /* HPD disables all the table attributes except NSTable.  */
10930             break;
10931         }
10932         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
10933         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
10934          * means "force PL1 access only", which means forcing AP[1] to 0.
10935          */
10936         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
10937         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
10938         break;
10939     }
10940     /* Here descaddr is the final physical address, and attributes
10941      * are all in attrs.
10942      */
10943     fault_type = ARMFault_AccessFlag;
10944     if ((attrs & (1 << 8)) == 0) {
10945         /* Access flag */
10946         goto do_fault;
10947     }
10948 
10949     ap = extract32(attrs, 4, 2);
10950     xn = extract32(attrs, 12, 1);
10951 
10952     if (mmu_idx == ARMMMUIdx_Stage2) {
10953         ns = true;
10954         *prot = get_S2prot(env, ap, xn);
10955     } else {
10956         ns = extract32(attrs, 3, 1);
10957         pxn = extract32(attrs, 11, 1);
10958         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
10959     }
10960 
10961     fault_type = ARMFault_Permission;
10962     if (!(*prot & (1 << access_type))) {
10963         goto do_fault;
10964     }
10965 
10966     if (ns) {
10967         /* The NS bit will (as required by the architecture) have no effect if
10968          * the CPU doesn't support TZ or this is a non-secure translation
10969          * regime, because the attribute will already be non-secure.
10970          */
10971         txattrs->secure = false;
10972     }
10973     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
10974     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
10975         txattrs->target_tlb_bit0 = true;
10976     }
10977 
10978     if (cacheattrs != NULL) {
10979         if (mmu_idx == ARMMMUIdx_Stage2) {
10980             cacheattrs->attrs = convert_stage2_attrs(env,
10981                                                      extract32(attrs, 0, 4));
10982         } else {
10983             /* Index into MAIR registers for cache attributes */
10984             uint8_t attrindx = extract32(attrs, 0, 3);
10985             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
10986             assert(attrindx <= 7);
10987             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
10988         }
10989         cacheattrs->shareability = extract32(attrs, 6, 2);
10990     }
10991 
10992     *phys_ptr = descaddr;
10993     *page_size_ptr = page_size;
10994     return false;
10995 
10996 do_fault:
10997     fi->type = fault_type;
10998     fi->level = level;
10999     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11000     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2);
11001     return true;
11002 }
11003 
11004 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11005                                                 ARMMMUIdx mmu_idx,
11006                                                 int32_t address, int *prot)
11007 {
11008     if (!arm_feature(env, ARM_FEATURE_M)) {
11009         *prot = PAGE_READ | PAGE_WRITE;
11010         switch (address) {
11011         case 0xF0000000 ... 0xFFFFFFFF:
11012             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11013                 /* hivecs execing is ok */
11014                 *prot |= PAGE_EXEC;
11015             }
11016             break;
11017         case 0x00000000 ... 0x7FFFFFFF:
11018             *prot |= PAGE_EXEC;
11019             break;
11020         }
11021     } else {
11022         /* Default system address map for M profile cores.
11023          * The architecture specifies which regions are execute-never;
11024          * at the MPU level no other checks are defined.
11025          */
11026         switch (address) {
11027         case 0x00000000 ... 0x1fffffff: /* ROM */
11028         case 0x20000000 ... 0x3fffffff: /* SRAM */
11029         case 0x60000000 ... 0x7fffffff: /* RAM */
11030         case 0x80000000 ... 0x9fffffff: /* RAM */
11031             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11032             break;
11033         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11034         case 0xa0000000 ... 0xbfffffff: /* Device */
11035         case 0xc0000000 ... 0xdfffffff: /* Device */
11036         case 0xe0000000 ... 0xffffffff: /* System */
11037             *prot = PAGE_READ | PAGE_WRITE;
11038             break;
11039         default:
11040             g_assert_not_reached();
11041         }
11042     }
11043 }
11044 
11045 static bool pmsav7_use_background_region(ARMCPU *cpu,
11046                                          ARMMMUIdx mmu_idx, bool is_user)
11047 {
11048     /* Return true if we should use the default memory map as a
11049      * "background" region if there are no hits against any MPU regions.
11050      */
11051     CPUARMState *env = &cpu->env;
11052 
11053     if (is_user) {
11054         return false;
11055     }
11056 
11057     if (arm_feature(env, ARM_FEATURE_M)) {
11058         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11059             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11060     } else {
11061         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11062     }
11063 }
11064 
11065 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11066 {
11067     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11068     return arm_feature(env, ARM_FEATURE_M) &&
11069         extract32(address, 20, 12) == 0xe00;
11070 }
11071 
11072 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11073 {
11074     /* True if address is in the M profile system region
11075      * 0xe0000000 - 0xffffffff
11076      */
11077     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11078 }
11079 
11080 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11081                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11082                                  hwaddr *phys_ptr, int *prot,
11083                                  target_ulong *page_size,
11084                                  ARMMMUFaultInfo *fi)
11085 {
11086     ARMCPU *cpu = env_archcpu(env);
11087     int n;
11088     bool is_user = regime_is_user(env, mmu_idx);
11089 
11090     *phys_ptr = address;
11091     *page_size = TARGET_PAGE_SIZE;
11092     *prot = 0;
11093 
11094     if (regime_translation_disabled(env, mmu_idx) ||
11095         m_is_ppb_region(env, address)) {
11096         /* MPU disabled or M profile PPB access: use default memory map.
11097          * The other case which uses the default memory map in the
11098          * v7M ARM ARM pseudocode is exception vector reads from the vector
11099          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11100          * which always does a direct read using address_space_ldl(), rather
11101          * than going via this function, so we don't need to check that here.
11102          */
11103         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11104     } else { /* MPU enabled */
11105         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11106             /* region search */
11107             uint32_t base = env->pmsav7.drbar[n];
11108             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11109             uint32_t rmask;
11110             bool srdis = false;
11111 
11112             if (!(env->pmsav7.drsr[n] & 0x1)) {
11113                 continue;
11114             }
11115 
11116             if (!rsize) {
11117                 qemu_log_mask(LOG_GUEST_ERROR,
11118                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11119                 continue;
11120             }
11121             rsize++;
11122             rmask = (1ull << rsize) - 1;
11123 
11124             if (base & rmask) {
11125                 qemu_log_mask(LOG_GUEST_ERROR,
11126                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11127                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11128                               n, base, rmask);
11129                 continue;
11130             }
11131 
11132             if (address < base || address > base + rmask) {
11133                 /*
11134                  * Address not in this region. We must check whether the
11135                  * region covers addresses in the same page as our address.
11136                  * In that case we must not report a size that covers the
11137                  * whole page for a subsequent hit against a different MPU
11138                  * region or the background region, because it would result in
11139                  * incorrect TLB hits for subsequent accesses to addresses that
11140                  * are in this MPU region.
11141                  */
11142                 if (ranges_overlap(base, rmask,
11143                                    address & TARGET_PAGE_MASK,
11144                                    TARGET_PAGE_SIZE)) {
11145                     *page_size = 1;
11146                 }
11147                 continue;
11148             }
11149 
11150             /* Region matched */
11151 
11152             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11153                 int i, snd;
11154                 uint32_t srdis_mask;
11155 
11156                 rsize -= 3; /* sub region size (power of 2) */
11157                 snd = ((address - base) >> rsize) & 0x7;
11158                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11159 
11160                 srdis_mask = srdis ? 0x3 : 0x0;
11161                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11162                     /* This will check in groups of 2, 4 and then 8, whether
11163                      * the subregion bits are consistent. rsize is incremented
11164                      * back up to give the region size, considering consistent
11165                      * adjacent subregions as one region. Stop testing if rsize
11166                      * is already big enough for an entire QEMU page.
11167                      */
11168                     int snd_rounded = snd & ~(i - 1);
11169                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11170                                                      snd_rounded + 8, i);
11171                     if (srdis_mask ^ srdis_multi) {
11172                         break;
11173                     }
11174                     srdis_mask = (srdis_mask << i) | srdis_mask;
11175                     rsize++;
11176                 }
11177             }
11178             if (srdis) {
11179                 continue;
11180             }
11181             if (rsize < TARGET_PAGE_BITS) {
11182                 *page_size = 1 << rsize;
11183             }
11184             break;
11185         }
11186 
11187         if (n == -1) { /* no hits */
11188             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11189                 /* background fault */
11190                 fi->type = ARMFault_Background;
11191                 return true;
11192             }
11193             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11194         } else { /* a MPU hit! */
11195             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11196             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11197 
11198             if (m_is_system_region(env, address)) {
11199                 /* System space is always execute never */
11200                 xn = 1;
11201             }
11202 
11203             if (is_user) { /* User mode AP bit decoding */
11204                 switch (ap) {
11205                 case 0:
11206                 case 1:
11207                 case 5:
11208                     break; /* no access */
11209                 case 3:
11210                     *prot |= PAGE_WRITE;
11211                     /* fall through */
11212                 case 2:
11213                 case 6:
11214                     *prot |= PAGE_READ | PAGE_EXEC;
11215                     break;
11216                 case 7:
11217                     /* for v7M, same as 6; for R profile a reserved value */
11218                     if (arm_feature(env, ARM_FEATURE_M)) {
11219                         *prot |= PAGE_READ | PAGE_EXEC;
11220                         break;
11221                     }
11222                     /* fall through */
11223                 default:
11224                     qemu_log_mask(LOG_GUEST_ERROR,
11225                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11226                                   PRIx32 "\n", n, ap);
11227                 }
11228             } else { /* Priv. mode AP bits decoding */
11229                 switch (ap) {
11230                 case 0:
11231                     break; /* no access */
11232                 case 1:
11233                 case 2:
11234                 case 3:
11235                     *prot |= PAGE_WRITE;
11236                     /* fall through */
11237                 case 5:
11238                 case 6:
11239                     *prot |= PAGE_READ | PAGE_EXEC;
11240                     break;
11241                 case 7:
11242                     /* for v7M, same as 6; for R profile a reserved value */
11243                     if (arm_feature(env, ARM_FEATURE_M)) {
11244                         *prot |= PAGE_READ | PAGE_EXEC;
11245                         break;
11246                     }
11247                     /* fall through */
11248                 default:
11249                     qemu_log_mask(LOG_GUEST_ERROR,
11250                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11251                                   PRIx32 "\n", n, ap);
11252                 }
11253             }
11254 
11255             /* execute never */
11256             if (xn) {
11257                 *prot &= ~PAGE_EXEC;
11258             }
11259         }
11260     }
11261 
11262     fi->type = ARMFault_Permission;
11263     fi->level = 1;
11264     return !(*prot & (1 << access_type));
11265 }
11266 
11267 static bool v8m_is_sau_exempt(CPUARMState *env,
11268                               uint32_t address, MMUAccessType access_type)
11269 {
11270     /* The architecture specifies that certain address ranges are
11271      * exempt from v8M SAU/IDAU checks.
11272      */
11273     return
11274         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
11275         (address >= 0xe0000000 && address <= 0xe0002fff) ||
11276         (address >= 0xe000e000 && address <= 0xe000efff) ||
11277         (address >= 0xe002e000 && address <= 0xe002efff) ||
11278         (address >= 0xe0040000 && address <= 0xe0041fff) ||
11279         (address >= 0xe00ff000 && address <= 0xe00fffff);
11280 }
11281 
11282 void v8m_security_lookup(CPUARMState *env, uint32_t address,
11283                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
11284                                 V8M_SAttributes *sattrs)
11285 {
11286     /* Look up the security attributes for this address. Compare the
11287      * pseudocode SecurityCheck() function.
11288      * We assume the caller has zero-initialized *sattrs.
11289      */
11290     ARMCPU *cpu = env_archcpu(env);
11291     int r;
11292     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
11293     int idau_region = IREGION_NOTVALID;
11294     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11295     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11296 
11297     if (cpu->idau) {
11298         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
11299         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
11300 
11301         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
11302                    &idau_nsc);
11303     }
11304 
11305     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
11306         /* 0xf0000000..0xffffffff is always S for insn fetches */
11307         return;
11308     }
11309 
11310     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
11311         sattrs->ns = !regime_is_secure(env, mmu_idx);
11312         return;
11313     }
11314 
11315     if (idau_region != IREGION_NOTVALID) {
11316         sattrs->irvalid = true;
11317         sattrs->iregion = idau_region;
11318     }
11319 
11320     switch (env->sau.ctrl & 3) {
11321     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
11322         break;
11323     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
11324         sattrs->ns = true;
11325         break;
11326     default: /* SAU.ENABLE == 1 */
11327         for (r = 0; r < cpu->sau_sregion; r++) {
11328             if (env->sau.rlar[r] & 1) {
11329                 uint32_t base = env->sau.rbar[r] & ~0x1f;
11330                 uint32_t limit = env->sau.rlar[r] | 0x1f;
11331 
11332                 if (base <= address && limit >= address) {
11333                     if (base > addr_page_base || limit < addr_page_limit) {
11334                         sattrs->subpage = true;
11335                     }
11336                     if (sattrs->srvalid) {
11337                         /* If we hit in more than one region then we must report
11338                          * as Secure, not NS-Callable, with no valid region
11339                          * number info.
11340                          */
11341                         sattrs->ns = false;
11342                         sattrs->nsc = false;
11343                         sattrs->sregion = 0;
11344                         sattrs->srvalid = false;
11345                         break;
11346                     } else {
11347                         if (env->sau.rlar[r] & 2) {
11348                             sattrs->nsc = true;
11349                         } else {
11350                             sattrs->ns = true;
11351                         }
11352                         sattrs->srvalid = true;
11353                         sattrs->sregion = r;
11354                     }
11355                 } else {
11356                     /*
11357                      * Address not in this region. We must check whether the
11358                      * region covers addresses in the same page as our address.
11359                      * In that case we must not report a size that covers the
11360                      * whole page for a subsequent hit against a different MPU
11361                      * region or the background region, because it would result
11362                      * in incorrect TLB hits for subsequent accesses to
11363                      * addresses that are in this MPU region.
11364                      */
11365                     if (limit >= base &&
11366                         ranges_overlap(base, limit - base + 1,
11367                                        addr_page_base,
11368                                        TARGET_PAGE_SIZE)) {
11369                         sattrs->subpage = true;
11370                     }
11371                 }
11372             }
11373         }
11374         break;
11375     }
11376 
11377     /*
11378      * The IDAU will override the SAU lookup results if it specifies
11379      * higher security than the SAU does.
11380      */
11381     if (!idau_ns) {
11382         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
11383             sattrs->ns = false;
11384             sattrs->nsc = idau_nsc;
11385         }
11386     }
11387 }
11388 
11389 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
11390                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
11391                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
11392                               int *prot, bool *is_subpage,
11393                               ARMMMUFaultInfo *fi, uint32_t *mregion)
11394 {
11395     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
11396      * that a full phys-to-virt translation does).
11397      * mregion is (if not NULL) set to the region number which matched,
11398      * or -1 if no region number is returned (MPU off, address did not
11399      * hit a region, address hit in multiple regions).
11400      * We set is_subpage to true if the region hit doesn't cover the
11401      * entire TARGET_PAGE the address is within.
11402      */
11403     ARMCPU *cpu = env_archcpu(env);
11404     bool is_user = regime_is_user(env, mmu_idx);
11405     uint32_t secure = regime_is_secure(env, mmu_idx);
11406     int n;
11407     int matchregion = -1;
11408     bool hit = false;
11409     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11410     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11411 
11412     *is_subpage = false;
11413     *phys_ptr = address;
11414     *prot = 0;
11415     if (mregion) {
11416         *mregion = -1;
11417     }
11418 
11419     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
11420      * was an exception vector read from the vector table (which is always
11421      * done using the default system address map), because those accesses
11422      * are done in arm_v7m_load_vector(), which always does a direct
11423      * read using address_space_ldl(), rather than going via this function.
11424      */
11425     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
11426         hit = true;
11427     } else if (m_is_ppb_region(env, address)) {
11428         hit = true;
11429     } else {
11430         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11431             hit = true;
11432         }
11433 
11434         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11435             /* region search */
11436             /* Note that the base address is bits [31:5] from the register
11437              * with bits [4:0] all zeroes, but the limit address is bits
11438              * [31:5] from the register with bits [4:0] all ones.
11439              */
11440             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
11441             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
11442 
11443             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
11444                 /* Region disabled */
11445                 continue;
11446             }
11447 
11448             if (address < base || address > limit) {
11449                 /*
11450                  * Address not in this region. We must check whether the
11451                  * region covers addresses in the same page as our address.
11452                  * In that case we must not report a size that covers the
11453                  * whole page for a subsequent hit against a different MPU
11454                  * region or the background region, because it would result in
11455                  * incorrect TLB hits for subsequent accesses to addresses that
11456                  * are in this MPU region.
11457                  */
11458                 if (limit >= base &&
11459                     ranges_overlap(base, limit - base + 1,
11460                                    addr_page_base,
11461                                    TARGET_PAGE_SIZE)) {
11462                     *is_subpage = true;
11463                 }
11464                 continue;
11465             }
11466 
11467             if (base > addr_page_base || limit < addr_page_limit) {
11468                 *is_subpage = true;
11469             }
11470 
11471             if (matchregion != -1) {
11472                 /* Multiple regions match -- always a failure (unlike
11473                  * PMSAv7 where highest-numbered-region wins)
11474                  */
11475                 fi->type = ARMFault_Permission;
11476                 fi->level = 1;
11477                 return true;
11478             }
11479 
11480             matchregion = n;
11481             hit = true;
11482         }
11483     }
11484 
11485     if (!hit) {
11486         /* background fault */
11487         fi->type = ARMFault_Background;
11488         return true;
11489     }
11490 
11491     if (matchregion == -1) {
11492         /* hit using the background region */
11493         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11494     } else {
11495         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
11496         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
11497 
11498         if (m_is_system_region(env, address)) {
11499             /* System space is always execute never */
11500             xn = 1;
11501         }
11502 
11503         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
11504         if (*prot && !xn) {
11505             *prot |= PAGE_EXEC;
11506         }
11507         /* We don't need to look the attribute up in the MAIR0/MAIR1
11508          * registers because that only tells us about cacheability.
11509          */
11510         if (mregion) {
11511             *mregion = matchregion;
11512         }
11513     }
11514 
11515     fi->type = ARMFault_Permission;
11516     fi->level = 1;
11517     return !(*prot & (1 << access_type));
11518 }
11519 
11520 
11521 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
11522                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11523                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
11524                                  int *prot, target_ulong *page_size,
11525                                  ARMMMUFaultInfo *fi)
11526 {
11527     uint32_t secure = regime_is_secure(env, mmu_idx);
11528     V8M_SAttributes sattrs = {};
11529     bool ret;
11530     bool mpu_is_subpage;
11531 
11532     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
11533         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
11534         if (access_type == MMU_INST_FETCH) {
11535             /* Instruction fetches always use the MMU bank and the
11536              * transaction attribute determined by the fetch address,
11537              * regardless of CPU state. This is painful for QEMU
11538              * to handle, because it would mean we need to encode
11539              * into the mmu_idx not just the (user, negpri) information
11540              * for the current security state but also that for the
11541              * other security state, which would balloon the number
11542              * of mmu_idx values needed alarmingly.
11543              * Fortunately we can avoid this because it's not actually
11544              * possible to arbitrarily execute code from memory with
11545              * the wrong security attribute: it will always generate
11546              * an exception of some kind or another, apart from the
11547              * special case of an NS CPU executing an SG instruction
11548              * in S&NSC memory. So we always just fail the translation
11549              * here and sort things out in the exception handler
11550              * (including possibly emulating an SG instruction).
11551              */
11552             if (sattrs.ns != !secure) {
11553                 if (sattrs.nsc) {
11554                     fi->type = ARMFault_QEMU_NSCExec;
11555                 } else {
11556                     fi->type = ARMFault_QEMU_SFault;
11557                 }
11558                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
11559                 *phys_ptr = address;
11560                 *prot = 0;
11561                 return true;
11562             }
11563         } else {
11564             /* For data accesses we always use the MMU bank indicated
11565              * by the current CPU state, but the security attributes
11566              * might downgrade a secure access to nonsecure.
11567              */
11568             if (sattrs.ns) {
11569                 txattrs->secure = false;
11570             } else if (!secure) {
11571                 /* NS access to S memory must fault.
11572                  * Architecturally we should first check whether the
11573                  * MPU information for this address indicates that we
11574                  * are doing an unaligned access to Device memory, which
11575                  * should generate a UsageFault instead. QEMU does not
11576                  * currently check for that kind of unaligned access though.
11577                  * If we added it we would need to do so as a special case
11578                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
11579                  */
11580                 fi->type = ARMFault_QEMU_SFault;
11581                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
11582                 *phys_ptr = address;
11583                 *prot = 0;
11584                 return true;
11585             }
11586         }
11587     }
11588 
11589     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
11590                             txattrs, prot, &mpu_is_subpage, fi, NULL);
11591     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
11592     return ret;
11593 }
11594 
11595 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
11596                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11597                                  hwaddr *phys_ptr, int *prot,
11598                                  ARMMMUFaultInfo *fi)
11599 {
11600     int n;
11601     uint32_t mask;
11602     uint32_t base;
11603     bool is_user = regime_is_user(env, mmu_idx);
11604 
11605     if (regime_translation_disabled(env, mmu_idx)) {
11606         /* MPU disabled.  */
11607         *phys_ptr = address;
11608         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11609         return false;
11610     }
11611 
11612     *phys_ptr = address;
11613     for (n = 7; n >= 0; n--) {
11614         base = env->cp15.c6_region[n];
11615         if ((base & 1) == 0) {
11616             continue;
11617         }
11618         mask = 1 << ((base >> 1) & 0x1f);
11619         /* Keep this shift separate from the above to avoid an
11620            (undefined) << 32.  */
11621         mask = (mask << 1) - 1;
11622         if (((base ^ address) & ~mask) == 0) {
11623             break;
11624         }
11625     }
11626     if (n < 0) {
11627         fi->type = ARMFault_Background;
11628         return true;
11629     }
11630 
11631     if (access_type == MMU_INST_FETCH) {
11632         mask = env->cp15.pmsav5_insn_ap;
11633     } else {
11634         mask = env->cp15.pmsav5_data_ap;
11635     }
11636     mask = (mask >> (n * 4)) & 0xf;
11637     switch (mask) {
11638     case 0:
11639         fi->type = ARMFault_Permission;
11640         fi->level = 1;
11641         return true;
11642     case 1:
11643         if (is_user) {
11644             fi->type = ARMFault_Permission;
11645             fi->level = 1;
11646             return true;
11647         }
11648         *prot = PAGE_READ | PAGE_WRITE;
11649         break;
11650     case 2:
11651         *prot = PAGE_READ;
11652         if (!is_user) {
11653             *prot |= PAGE_WRITE;
11654         }
11655         break;
11656     case 3:
11657         *prot = PAGE_READ | PAGE_WRITE;
11658         break;
11659     case 5:
11660         if (is_user) {
11661             fi->type = ARMFault_Permission;
11662             fi->level = 1;
11663             return true;
11664         }
11665         *prot = PAGE_READ;
11666         break;
11667     case 6:
11668         *prot = PAGE_READ;
11669         break;
11670     default:
11671         /* Bad permission.  */
11672         fi->type = ARMFault_Permission;
11673         fi->level = 1;
11674         return true;
11675     }
11676     *prot |= PAGE_EXEC;
11677     return false;
11678 }
11679 
11680 /* Combine either inner or outer cacheability attributes for normal
11681  * memory, according to table D4-42 and pseudocode procedure
11682  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
11683  *
11684  * NB: only stage 1 includes allocation hints (RW bits), leading to
11685  * some asymmetry.
11686  */
11687 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
11688 {
11689     if (s1 == 4 || s2 == 4) {
11690         /* non-cacheable has precedence */
11691         return 4;
11692     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
11693         /* stage 1 write-through takes precedence */
11694         return s1;
11695     } else if (extract32(s2, 2, 2) == 2) {
11696         /* stage 2 write-through takes precedence, but the allocation hint
11697          * is still taken from stage 1
11698          */
11699         return (2 << 2) | extract32(s1, 0, 2);
11700     } else { /* write-back */
11701         return s1;
11702     }
11703 }
11704 
11705 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
11706  * and CombineS1S2Desc()
11707  *
11708  * @s1:      Attributes from stage 1 walk
11709  * @s2:      Attributes from stage 2 walk
11710  */
11711 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
11712 {
11713     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
11714     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
11715     ARMCacheAttrs ret;
11716 
11717     /* Combine shareability attributes (table D4-43) */
11718     if (s1.shareability == 2 || s2.shareability == 2) {
11719         /* if either are outer-shareable, the result is outer-shareable */
11720         ret.shareability = 2;
11721     } else if (s1.shareability == 3 || s2.shareability == 3) {
11722         /* if either are inner-shareable, the result is inner-shareable */
11723         ret.shareability = 3;
11724     } else {
11725         /* both non-shareable */
11726         ret.shareability = 0;
11727     }
11728 
11729     /* Combine memory type and cacheability attributes */
11730     if (s1hi == 0 || s2hi == 0) {
11731         /* Device has precedence over normal */
11732         if (s1lo == 0 || s2lo == 0) {
11733             /* nGnRnE has precedence over anything */
11734             ret.attrs = 0;
11735         } else if (s1lo == 4 || s2lo == 4) {
11736             /* non-Reordering has precedence over Reordering */
11737             ret.attrs = 4;  /* nGnRE */
11738         } else if (s1lo == 8 || s2lo == 8) {
11739             /* non-Gathering has precedence over Gathering */
11740             ret.attrs = 8;  /* nGRE */
11741         } else {
11742             ret.attrs = 0xc; /* GRE */
11743         }
11744 
11745         /* Any location for which the resultant memory type is any
11746          * type of Device memory is always treated as Outer Shareable.
11747          */
11748         ret.shareability = 2;
11749     } else { /* Normal memory */
11750         /* Outer/inner cacheability combine independently */
11751         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
11752                   | combine_cacheattr_nibble(s1lo, s2lo);
11753 
11754         if (ret.attrs == 0x44) {
11755             /* Any location for which the resultant memory type is Normal
11756              * Inner Non-cacheable, Outer Non-cacheable is always treated
11757              * as Outer Shareable.
11758              */
11759             ret.shareability = 2;
11760         }
11761     }
11762 
11763     return ret;
11764 }
11765 
11766 
11767 /* get_phys_addr - get the physical address for this virtual address
11768  *
11769  * Find the physical address corresponding to the given virtual address,
11770  * by doing a translation table walk on MMU based systems or using the
11771  * MPU state on MPU based systems.
11772  *
11773  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11774  * prot and page_size may not be filled in, and the populated fsr value provides
11775  * information on why the translation aborted, in the format of a
11776  * DFSR/IFSR fault register, with the following caveats:
11777  *  * we honour the short vs long DFSR format differences.
11778  *  * the WnR bit is never set (the caller must do this).
11779  *  * for PSMAv5 based systems we don't bother to return a full FSR format
11780  *    value.
11781  *
11782  * @env: CPUARMState
11783  * @address: virtual address to get physical address for
11784  * @access_type: 0 for read, 1 for write, 2 for execute
11785  * @mmu_idx: MMU index indicating required translation regime
11786  * @phys_ptr: set to the physical address corresponding to the virtual address
11787  * @attrs: set to the memory transaction attributes to use
11788  * @prot: set to the permissions for the page containing phys_ptr
11789  * @page_size: set to the size of the page containing phys_ptr
11790  * @fi: set to fault info if the translation fails
11791  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11792  */
11793 bool get_phys_addr(CPUARMState *env, target_ulong address,
11794                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
11795                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
11796                    target_ulong *page_size,
11797                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11798 {
11799     if (mmu_idx == ARMMMUIdx_E10_0 ||
11800         mmu_idx == ARMMMUIdx_E10_1 ||
11801         mmu_idx == ARMMMUIdx_E10_1_PAN) {
11802         /* Call ourselves recursively to do the stage 1 and then stage 2
11803          * translations.
11804          */
11805         if (arm_feature(env, ARM_FEATURE_EL2)) {
11806             hwaddr ipa;
11807             int s2_prot;
11808             int ret;
11809             ARMCacheAttrs cacheattrs2 = {};
11810 
11811             ret = get_phys_addr(env, address, access_type,
11812                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
11813                                 prot, page_size, fi, cacheattrs);
11814 
11815             /* If S1 fails or S2 is disabled, return early.  */
11816             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
11817                 *phys_ptr = ipa;
11818                 return ret;
11819             }
11820 
11821             /* S1 is done. Now do S2 translation.  */
11822             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_Stage2,
11823                                      phys_ptr, attrs, &s2_prot,
11824                                      page_size, fi,
11825                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
11826             fi->s2addr = ipa;
11827             /* Combine the S1 and S2 perms.  */
11828             *prot &= s2_prot;
11829 
11830             /* Combine the S1 and S2 cache attributes, if needed */
11831             if (!ret && cacheattrs != NULL) {
11832                 if (env->cp15.hcr_el2 & HCR_DC) {
11833                     /*
11834                      * HCR.DC forces the first stage attributes to
11835                      *  Normal Non-Shareable,
11836                      *  Inner Write-Back Read-Allocate Write-Allocate,
11837                      *  Outer Write-Back Read-Allocate Write-Allocate.
11838                      */
11839                     cacheattrs->attrs = 0xff;
11840                     cacheattrs->shareability = 0;
11841                 }
11842                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
11843             }
11844 
11845             return ret;
11846         } else {
11847             /*
11848              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
11849              */
11850             mmu_idx = stage_1_mmu_idx(mmu_idx);
11851         }
11852     }
11853 
11854     /* The page table entries may downgrade secure to non-secure, but
11855      * cannot upgrade an non-secure translation regime's attributes
11856      * to secure.
11857      */
11858     attrs->secure = regime_is_secure(env, mmu_idx);
11859     attrs->user = regime_is_user(env, mmu_idx);
11860 
11861     /* Fast Context Switch Extension. This doesn't exist at all in v8.
11862      * In v7 and earlier it affects all stage 1 translations.
11863      */
11864     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
11865         && !arm_feature(env, ARM_FEATURE_V8)) {
11866         if (regime_el(env, mmu_idx) == 3) {
11867             address += env->cp15.fcseidr_s;
11868         } else {
11869             address += env->cp15.fcseidr_ns;
11870         }
11871     }
11872 
11873     if (arm_feature(env, ARM_FEATURE_PMSA)) {
11874         bool ret;
11875         *page_size = TARGET_PAGE_SIZE;
11876 
11877         if (arm_feature(env, ARM_FEATURE_V8)) {
11878             /* PMSAv8 */
11879             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
11880                                        phys_ptr, attrs, prot, page_size, fi);
11881         } else if (arm_feature(env, ARM_FEATURE_V7)) {
11882             /* PMSAv7 */
11883             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
11884                                        phys_ptr, prot, page_size, fi);
11885         } else {
11886             /* Pre-v7 MPU */
11887             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
11888                                        phys_ptr, prot, fi);
11889         }
11890         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
11891                       " mmu_idx %u -> %s (prot %c%c%c)\n",
11892                       access_type == MMU_DATA_LOAD ? "reading" :
11893                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
11894                       (uint32_t)address, mmu_idx,
11895                       ret ? "Miss" : "Hit",
11896                       *prot & PAGE_READ ? 'r' : '-',
11897                       *prot & PAGE_WRITE ? 'w' : '-',
11898                       *prot & PAGE_EXEC ? 'x' : '-');
11899 
11900         return ret;
11901     }
11902 
11903     /* Definitely a real MMU, not an MPU */
11904 
11905     if (regime_translation_disabled(env, mmu_idx)) {
11906         /*
11907          * MMU disabled.  S1 addresses within aa64 translation regimes are
11908          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
11909          */
11910         if (mmu_idx != ARMMMUIdx_Stage2) {
11911             int r_el = regime_el(env, mmu_idx);
11912             if (arm_el_is_aa64(env, r_el)) {
11913                 int pamax = arm_pamax(env_archcpu(env));
11914                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
11915                 int addrtop, tbi;
11916 
11917                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11918                 if (access_type == MMU_INST_FETCH) {
11919                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11920                 }
11921                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
11922                 addrtop = (tbi ? 55 : 63);
11923 
11924                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
11925                     fi->type = ARMFault_AddressSize;
11926                     fi->level = 0;
11927                     fi->stage2 = false;
11928                     return 1;
11929                 }
11930 
11931                 /*
11932                  * When TBI is disabled, we've just validated that all of the
11933                  * bits above PAMax are zero, so logically we only need to
11934                  * clear the top byte for TBI.  But it's clearer to follow
11935                  * the pseudocode set of addrdesc.paddress.
11936                  */
11937                 address = extract64(address, 0, 52);
11938             }
11939         }
11940         *phys_ptr = address;
11941         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11942         *page_size = TARGET_PAGE_SIZE;
11943         return 0;
11944     }
11945 
11946     if (regime_using_lpae_format(env, mmu_idx)) {
11947         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
11948                                   phys_ptr, attrs, prot, page_size,
11949                                   fi, cacheattrs);
11950     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
11951         return get_phys_addr_v6(env, address, access_type, mmu_idx,
11952                                 phys_ptr, attrs, prot, page_size, fi);
11953     } else {
11954         return get_phys_addr_v5(env, address, access_type, mmu_idx,
11955                                     phys_ptr, prot, page_size, fi);
11956     }
11957 }
11958 
11959 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
11960                                          MemTxAttrs *attrs)
11961 {
11962     ARMCPU *cpu = ARM_CPU(cs);
11963     CPUARMState *env = &cpu->env;
11964     hwaddr phys_addr;
11965     target_ulong page_size;
11966     int prot;
11967     bool ret;
11968     ARMMMUFaultInfo fi = {};
11969     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
11970 
11971     *attrs = (MemTxAttrs) {};
11972 
11973     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
11974                         attrs, &prot, &page_size, &fi, NULL);
11975 
11976     if (ret) {
11977         return -1;
11978     }
11979     return phys_addr;
11980 }
11981 
11982 #endif
11983 
11984 /* Note that signed overflow is undefined in C.  The following routines are
11985    careful to use unsigned types where modulo arithmetic is required.
11986    Failure to do so _will_ break on newer gcc.  */
11987 
11988 /* Signed saturating arithmetic.  */
11989 
11990 /* Perform 16-bit signed saturating addition.  */
11991 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
11992 {
11993     uint16_t res;
11994 
11995     res = a + b;
11996     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
11997         if (a & 0x8000)
11998             res = 0x8000;
11999         else
12000             res = 0x7fff;
12001     }
12002     return res;
12003 }
12004 
12005 /* Perform 8-bit signed saturating addition.  */
12006 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
12007 {
12008     uint8_t res;
12009 
12010     res = a + b;
12011     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
12012         if (a & 0x80)
12013             res = 0x80;
12014         else
12015             res = 0x7f;
12016     }
12017     return res;
12018 }
12019 
12020 /* Perform 16-bit signed saturating subtraction.  */
12021 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
12022 {
12023     uint16_t res;
12024 
12025     res = a - b;
12026     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
12027         if (a & 0x8000)
12028             res = 0x8000;
12029         else
12030             res = 0x7fff;
12031     }
12032     return res;
12033 }
12034 
12035 /* Perform 8-bit signed saturating subtraction.  */
12036 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12037 {
12038     uint8_t res;
12039 
12040     res = a - b;
12041     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12042         if (a & 0x80)
12043             res = 0x80;
12044         else
12045             res = 0x7f;
12046     }
12047     return res;
12048 }
12049 
12050 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12051 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12052 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12053 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12054 #define PFX q
12055 
12056 #include "op_addsub.h"
12057 
12058 /* Unsigned saturating arithmetic.  */
12059 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12060 {
12061     uint16_t res;
12062     res = a + b;
12063     if (res < a)
12064         res = 0xffff;
12065     return res;
12066 }
12067 
12068 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12069 {
12070     if (a > b)
12071         return a - b;
12072     else
12073         return 0;
12074 }
12075 
12076 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12077 {
12078     uint8_t res;
12079     res = a + b;
12080     if (res < a)
12081         res = 0xff;
12082     return res;
12083 }
12084 
12085 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12086 {
12087     if (a > b)
12088         return a - b;
12089     else
12090         return 0;
12091 }
12092 
12093 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12094 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12095 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12096 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12097 #define PFX uq
12098 
12099 #include "op_addsub.h"
12100 
12101 /* Signed modulo arithmetic.  */
12102 #define SARITH16(a, b, n, op) do { \
12103     int32_t sum; \
12104     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12105     RESULT(sum, n, 16); \
12106     if (sum >= 0) \
12107         ge |= 3 << (n * 2); \
12108     } while(0)
12109 
12110 #define SARITH8(a, b, n, op) do { \
12111     int32_t sum; \
12112     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
12113     RESULT(sum, n, 8); \
12114     if (sum >= 0) \
12115         ge |= 1 << n; \
12116     } while(0)
12117 
12118 
12119 #define ADD16(a, b, n) SARITH16(a, b, n, +)
12120 #define SUB16(a, b, n) SARITH16(a, b, n, -)
12121 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
12122 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
12123 #define PFX s
12124 #define ARITH_GE
12125 
12126 #include "op_addsub.h"
12127 
12128 /* Unsigned modulo arithmetic.  */
12129 #define ADD16(a, b, n) do { \
12130     uint32_t sum; \
12131     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
12132     RESULT(sum, n, 16); \
12133     if ((sum >> 16) == 1) \
12134         ge |= 3 << (n * 2); \
12135     } while(0)
12136 
12137 #define ADD8(a, b, n) do { \
12138     uint32_t sum; \
12139     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
12140     RESULT(sum, n, 8); \
12141     if ((sum >> 8) == 1) \
12142         ge |= 1 << n; \
12143     } while(0)
12144 
12145 #define SUB16(a, b, n) do { \
12146     uint32_t sum; \
12147     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
12148     RESULT(sum, n, 16); \
12149     if ((sum >> 16) == 0) \
12150         ge |= 3 << (n * 2); \
12151     } while(0)
12152 
12153 #define SUB8(a, b, n) do { \
12154     uint32_t sum; \
12155     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
12156     RESULT(sum, n, 8); \
12157     if ((sum >> 8) == 0) \
12158         ge |= 1 << n; \
12159     } while(0)
12160 
12161 #define PFX u
12162 #define ARITH_GE
12163 
12164 #include "op_addsub.h"
12165 
12166 /* Halved signed arithmetic.  */
12167 #define ADD16(a, b, n) \
12168   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
12169 #define SUB16(a, b, n) \
12170   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
12171 #define ADD8(a, b, n) \
12172   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
12173 #define SUB8(a, b, n) \
12174   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
12175 #define PFX sh
12176 
12177 #include "op_addsub.h"
12178 
12179 /* Halved unsigned arithmetic.  */
12180 #define ADD16(a, b, n) \
12181   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12182 #define SUB16(a, b, n) \
12183   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12184 #define ADD8(a, b, n) \
12185   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12186 #define SUB8(a, b, n) \
12187   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12188 #define PFX uh
12189 
12190 #include "op_addsub.h"
12191 
12192 static inline uint8_t do_usad(uint8_t a, uint8_t b)
12193 {
12194     if (a > b)
12195         return a - b;
12196     else
12197         return b - a;
12198 }
12199 
12200 /* Unsigned sum of absolute byte differences.  */
12201 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
12202 {
12203     uint32_t sum;
12204     sum = do_usad(a, b);
12205     sum += do_usad(a >> 8, b >> 8);
12206     sum += do_usad(a >> 16, b >>16);
12207     sum += do_usad(a >> 24, b >> 24);
12208     return sum;
12209 }
12210 
12211 /* For ARMv6 SEL instruction.  */
12212 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
12213 {
12214     uint32_t mask;
12215 
12216     mask = 0;
12217     if (flags & 1)
12218         mask |= 0xff;
12219     if (flags & 2)
12220         mask |= 0xff00;
12221     if (flags & 4)
12222         mask |= 0xff0000;
12223     if (flags & 8)
12224         mask |= 0xff000000;
12225     return (a & mask) | (b & ~mask);
12226 }
12227 
12228 /* CRC helpers.
12229  * The upper bytes of val (above the number specified by 'bytes') must have
12230  * been zeroed out by the caller.
12231  */
12232 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12233 {
12234     uint8_t buf[4];
12235 
12236     stl_le_p(buf, val);
12237 
12238     /* zlib crc32 converts the accumulator and output to one's complement.  */
12239     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12240 }
12241 
12242 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12243 {
12244     uint8_t buf[4];
12245 
12246     stl_le_p(buf, val);
12247 
12248     /* Linux crc32c converts the output to one's complement.  */
12249     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12250 }
12251 
12252 /* Return the exception level to which FP-disabled exceptions should
12253  * be taken, or 0 if FP is enabled.
12254  */
12255 int fp_exception_el(CPUARMState *env, int cur_el)
12256 {
12257 #ifndef CONFIG_USER_ONLY
12258     /* CPACR and the CPTR registers don't exist before v6, so FP is
12259      * always accessible
12260      */
12261     if (!arm_feature(env, ARM_FEATURE_V6)) {
12262         return 0;
12263     }
12264 
12265     if (arm_feature(env, ARM_FEATURE_M)) {
12266         /* CPACR can cause a NOCP UsageFault taken to current security state */
12267         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
12268             return 1;
12269         }
12270 
12271         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
12272             if (!extract32(env->v7m.nsacr, 10, 1)) {
12273                 /* FP insns cause a NOCP UsageFault taken to Secure */
12274                 return 3;
12275             }
12276         }
12277 
12278         return 0;
12279     }
12280 
12281     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12282      * 0, 2 : trap EL0 and EL1/PL1 accesses
12283      * 1    : trap only EL0 accesses
12284      * 3    : trap no accesses
12285      * This register is ignored if E2H+TGE are both set.
12286      */
12287     if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12288         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12289 
12290         switch (fpen) {
12291         case 0:
12292         case 2:
12293             if (cur_el == 0 || cur_el == 1) {
12294                 /* Trap to PL1, which might be EL1 or EL3 */
12295                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12296                     return 3;
12297                 }
12298                 return 1;
12299             }
12300             if (cur_el == 3 && !is_a64(env)) {
12301                 /* Secure PL1 running at EL3 */
12302                 return 3;
12303             }
12304             break;
12305         case 1:
12306             if (cur_el == 0) {
12307                 return 1;
12308             }
12309             break;
12310         case 3:
12311             break;
12312         }
12313     }
12314 
12315     /*
12316      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
12317      * to control non-secure access to the FPU. It doesn't have any
12318      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
12319      */
12320     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
12321          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
12322         if (!extract32(env->cp15.nsacr, 10, 1)) {
12323             /* FP insns act as UNDEF */
12324             return cur_el == 2 ? 2 : 1;
12325         }
12326     }
12327 
12328     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12329      * check because zero bits in the registers mean "don't trap".
12330      */
12331 
12332     /* CPTR_EL2 : present in v7VE or v8 */
12333     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12334         && !arm_is_secure_below_el3(env)) {
12335         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12336         return 2;
12337     }
12338 
12339     /* CPTR_EL3 : present in v8 */
12340     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12341         /* Trap all FP ops to EL3 */
12342         return 3;
12343     }
12344 #endif
12345     return 0;
12346 }
12347 
12348 /* Return the exception level we're running at if this is our mmu_idx */
12349 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
12350 {
12351     if (mmu_idx & ARM_MMU_IDX_M) {
12352         return mmu_idx & ARM_MMU_IDX_M_PRIV;
12353     }
12354 
12355     switch (mmu_idx) {
12356     case ARMMMUIdx_E10_0:
12357     case ARMMMUIdx_E20_0:
12358     case ARMMMUIdx_SE10_0:
12359         return 0;
12360     case ARMMMUIdx_E10_1:
12361     case ARMMMUIdx_E10_1_PAN:
12362     case ARMMMUIdx_SE10_1:
12363     case ARMMMUIdx_SE10_1_PAN:
12364         return 1;
12365     case ARMMMUIdx_E2:
12366     case ARMMMUIdx_E20_2:
12367     case ARMMMUIdx_E20_2_PAN:
12368         return 2;
12369     case ARMMMUIdx_SE3:
12370         return 3;
12371     default:
12372         g_assert_not_reached();
12373     }
12374 }
12375 
12376 #ifndef CONFIG_TCG
12377 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
12378 {
12379     g_assert_not_reached();
12380 }
12381 #endif
12382 
12383 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
12384 {
12385     if (arm_feature(env, ARM_FEATURE_M)) {
12386         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
12387     }
12388 
12389     /* See ARM pseudo-function ELIsInHost.  */
12390     switch (el) {
12391     case 0:
12392         if (arm_is_secure_below_el3(env)) {
12393             return ARMMMUIdx_SE10_0;
12394         }
12395         if ((env->cp15.hcr_el2 & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)
12396             && arm_el_is_aa64(env, 2)) {
12397             return ARMMMUIdx_E20_0;
12398         }
12399         return ARMMMUIdx_E10_0;
12400     case 1:
12401         if (arm_is_secure_below_el3(env)) {
12402             if (env->pstate & PSTATE_PAN) {
12403                 return ARMMMUIdx_SE10_1_PAN;
12404             }
12405             return ARMMMUIdx_SE10_1;
12406         }
12407         if (env->pstate & PSTATE_PAN) {
12408             return ARMMMUIdx_E10_1_PAN;
12409         }
12410         return ARMMMUIdx_E10_1;
12411     case 2:
12412         /* TODO: ARMv8.4-SecEL2 */
12413         /* Note that TGE does not apply at EL2.  */
12414         if ((env->cp15.hcr_el2 & HCR_E2H) && arm_el_is_aa64(env, 2)) {
12415             if (env->pstate & PSTATE_PAN) {
12416                 return ARMMMUIdx_E20_2_PAN;
12417             }
12418             return ARMMMUIdx_E20_2;
12419         }
12420         return ARMMMUIdx_E2;
12421     case 3:
12422         return ARMMMUIdx_SE3;
12423     default:
12424         g_assert_not_reached();
12425     }
12426 }
12427 
12428 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
12429 {
12430     return arm_mmu_idx_el(env, arm_current_el(env));
12431 }
12432 
12433 #ifndef CONFIG_USER_ONLY
12434 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
12435 {
12436     return stage_1_mmu_idx(arm_mmu_idx(env));
12437 }
12438 #endif
12439 
12440 static uint32_t rebuild_hflags_common(CPUARMState *env, int fp_el,
12441                                       ARMMMUIdx mmu_idx, uint32_t flags)
12442 {
12443     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
12444     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX,
12445                        arm_to_core_mmu_idx(mmu_idx));
12446 
12447     if (arm_singlestep_active(env)) {
12448         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
12449     }
12450     return flags;
12451 }
12452 
12453 static uint32_t rebuild_hflags_common_32(CPUARMState *env, int fp_el,
12454                                          ARMMMUIdx mmu_idx, uint32_t flags)
12455 {
12456     bool sctlr_b = arm_sctlr_b(env);
12457 
12458     if (sctlr_b) {
12459         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, 1);
12460     }
12461     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
12462         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
12463     }
12464     flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
12465 
12466     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
12467 }
12468 
12469 static uint32_t rebuild_hflags_m32(CPUARMState *env, int fp_el,
12470                                    ARMMMUIdx mmu_idx)
12471 {
12472     uint32_t flags = 0;
12473 
12474     if (arm_v7m_is_handler_mode(env)) {
12475         flags = FIELD_DP32(flags, TBFLAG_M32, HANDLER, 1);
12476     }
12477 
12478     /*
12479      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
12480      * is suppressing them because the requested execution priority
12481      * is less than 0.
12482      */
12483     if (arm_feature(env, ARM_FEATURE_V8) &&
12484         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
12485           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
12486         flags = FIELD_DP32(flags, TBFLAG_M32, STACKCHECK, 1);
12487     }
12488 
12489     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
12490 }
12491 
12492 static uint32_t rebuild_hflags_aprofile(CPUARMState *env)
12493 {
12494     int flags = 0;
12495 
12496     flags = FIELD_DP32(flags, TBFLAG_ANY, DEBUG_TARGET_EL,
12497                        arm_debug_target_el(env));
12498     return flags;
12499 }
12500 
12501 static uint32_t rebuild_hflags_a32(CPUARMState *env, int fp_el,
12502                                    ARMMMUIdx mmu_idx)
12503 {
12504     uint32_t flags = rebuild_hflags_aprofile(env);
12505 
12506     if (arm_el_is_aa64(env, 1)) {
12507         flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
12508     }
12509 
12510     if (arm_current_el(env) < 2 && env->cp15.hstr_el2 &&
12511         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12512         flags = FIELD_DP32(flags, TBFLAG_A32, HSTR_ACTIVE, 1);
12513     }
12514 
12515     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
12516 }
12517 
12518 static uint32_t rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
12519                                    ARMMMUIdx mmu_idx)
12520 {
12521     uint32_t flags = rebuild_hflags_aprofile(env);
12522     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
12523     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
12524     uint64_t sctlr;
12525     int tbii, tbid;
12526 
12527     flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
12528 
12529     /* Get control bits for tagged addresses.  */
12530     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
12531     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
12532 
12533     flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
12534     flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
12535 
12536     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
12537         int sve_el = sve_exception_el(env, el);
12538         uint32_t zcr_len;
12539 
12540         /*
12541          * If SVE is disabled, but FP is enabled,
12542          * then the effective len is 0.
12543          */
12544         if (sve_el != 0 && fp_el == 0) {
12545             zcr_len = 0;
12546         } else {
12547             zcr_len = sve_zcr_len_for_el(env, el);
12548         }
12549         flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
12550         flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
12551     }
12552 
12553     sctlr = regime_sctlr(env, stage1);
12554 
12555     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
12556         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
12557     }
12558 
12559     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
12560         /*
12561          * In order to save space in flags, we record only whether
12562          * pauth is "inactive", meaning all insns are implemented as
12563          * a nop, or "active" when some action must be performed.
12564          * The decision of which action to take is left to a helper.
12565          */
12566         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
12567             flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
12568         }
12569     }
12570 
12571     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
12572         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
12573         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
12574             flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
12575         }
12576     }
12577 
12578     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
12579     if (!(env->pstate & PSTATE_UAO)) {
12580         switch (mmu_idx) {
12581         case ARMMMUIdx_E10_1:
12582         case ARMMMUIdx_E10_1_PAN:
12583         case ARMMMUIdx_SE10_1:
12584         case ARMMMUIdx_SE10_1_PAN:
12585             /* TODO: ARMv8.3-NV */
12586             flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
12587             break;
12588         case ARMMMUIdx_E20_2:
12589         case ARMMMUIdx_E20_2_PAN:
12590             /* TODO: ARMv8.4-SecEL2 */
12591             /*
12592              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
12593              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
12594              */
12595             if (env->cp15.hcr_el2 & HCR_TGE) {
12596                 flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
12597             }
12598             break;
12599         default:
12600             break;
12601         }
12602     }
12603 
12604     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
12605 }
12606 
12607 static uint32_t rebuild_hflags_internal(CPUARMState *env)
12608 {
12609     int el = arm_current_el(env);
12610     int fp_el = fp_exception_el(env, el);
12611     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12612 
12613     if (is_a64(env)) {
12614         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
12615     } else if (arm_feature(env, ARM_FEATURE_M)) {
12616         return rebuild_hflags_m32(env, fp_el, mmu_idx);
12617     } else {
12618         return rebuild_hflags_a32(env, fp_el, mmu_idx);
12619     }
12620 }
12621 
12622 void arm_rebuild_hflags(CPUARMState *env)
12623 {
12624     env->hflags = rebuild_hflags_internal(env);
12625 }
12626 
12627 /*
12628  * If we have triggered a EL state change we can't rely on the
12629  * translator having passed it to us, we need to recompute.
12630  */
12631 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
12632 {
12633     int el = arm_current_el(env);
12634     int fp_el = fp_exception_el(env, el);
12635     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12636     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
12637 }
12638 
12639 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
12640 {
12641     int fp_el = fp_exception_el(env, el);
12642     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12643 
12644     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
12645 }
12646 
12647 /*
12648  * If we have triggered a EL state change we can't rely on the
12649  * translator having passed it to us, we need to recompute.
12650  */
12651 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
12652 {
12653     int el = arm_current_el(env);
12654     int fp_el = fp_exception_el(env, el);
12655     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12656     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
12657 }
12658 
12659 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
12660 {
12661     int fp_el = fp_exception_el(env, el);
12662     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12663 
12664     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
12665 }
12666 
12667 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
12668 {
12669     int fp_el = fp_exception_el(env, el);
12670     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12671 
12672     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
12673 }
12674 
12675 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
12676 {
12677 #ifdef CONFIG_DEBUG_TCG
12678     uint32_t env_flags_current = env->hflags;
12679     uint32_t env_flags_rebuilt = rebuild_hflags_internal(env);
12680 
12681     if (unlikely(env_flags_current != env_flags_rebuilt)) {
12682         fprintf(stderr, "TCG hflags mismatch (current:0x%08x rebuilt:0x%08x)\n",
12683                 env_flags_current, env_flags_rebuilt);
12684         abort();
12685     }
12686 #endif
12687 }
12688 
12689 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
12690                           target_ulong *cs_base, uint32_t *pflags)
12691 {
12692     uint32_t flags = env->hflags;
12693     uint32_t pstate_for_ss;
12694 
12695     *cs_base = 0;
12696     assert_hflags_rebuild_correctly(env);
12697 
12698     if (FIELD_EX32(flags, TBFLAG_ANY, AARCH64_STATE)) {
12699         *pc = env->pc;
12700         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
12701             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
12702         }
12703         pstate_for_ss = env->pstate;
12704     } else {
12705         *pc = env->regs[15];
12706 
12707         if (arm_feature(env, ARM_FEATURE_M)) {
12708             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
12709                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
12710                 != env->v7m.secure) {
12711                 flags = FIELD_DP32(flags, TBFLAG_M32, FPCCR_S_WRONG, 1);
12712             }
12713 
12714             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
12715                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
12716                  (env->v7m.secure &&
12717                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
12718                 /*
12719                  * ASPEN is set, but FPCA/SFPA indicate that there is no
12720                  * active FP context; we must create a new FP context before
12721                  * executing any FP insn.
12722                  */
12723                 flags = FIELD_DP32(flags, TBFLAG_M32, NEW_FP_CTXT_NEEDED, 1);
12724             }
12725 
12726             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
12727             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
12728                 flags = FIELD_DP32(flags, TBFLAG_M32, LSPACT, 1);
12729             }
12730         } else {
12731             /*
12732              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
12733              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
12734              */
12735             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
12736                 flags = FIELD_DP32(flags, TBFLAG_A32,
12737                                    XSCALE_CPAR, env->cp15.c15_cpar);
12738             } else {
12739                 flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN,
12740                                    env->vfp.vec_len);
12741                 flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE,
12742                                    env->vfp.vec_stride);
12743             }
12744             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
12745                 flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
12746             }
12747         }
12748 
12749         flags = FIELD_DP32(flags, TBFLAG_AM32, THUMB, env->thumb);
12750         flags = FIELD_DP32(flags, TBFLAG_AM32, CONDEXEC, env->condexec_bits);
12751         pstate_for_ss = env->uncached_cpsr;
12752     }
12753 
12754     /*
12755      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
12756      * states defined in the ARM ARM for software singlestep:
12757      *  SS_ACTIVE   PSTATE.SS   State
12758      *     0            x       Inactive (the TB flag for SS is always 0)
12759      *     1            0       Active-pending
12760      *     1            1       Active-not-pending
12761      * SS_ACTIVE is set in hflags; PSTATE_SS is computed every TB.
12762      */
12763     if (FIELD_EX32(flags, TBFLAG_ANY, SS_ACTIVE) &&
12764         (pstate_for_ss & PSTATE_SS)) {
12765         flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
12766     }
12767 
12768     *pflags = flags;
12769 }
12770 
12771 #ifdef TARGET_AARCH64
12772 /*
12773  * The manual says that when SVE is enabled and VQ is widened the
12774  * implementation is allowed to zero the previously inaccessible
12775  * portion of the registers.  The corollary to that is that when
12776  * SVE is enabled and VQ is narrowed we are also allowed to zero
12777  * the now inaccessible portion of the registers.
12778  *
12779  * The intent of this is that no predicate bit beyond VQ is ever set.
12780  * Which means that some operations on predicate registers themselves
12781  * may operate on full uint64_t or even unrolled across the maximum
12782  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
12783  * may well be cheaper than conditionals to restrict the operation
12784  * to the relevant portion of a uint16_t[16].
12785  */
12786 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
12787 {
12788     int i, j;
12789     uint64_t pmask;
12790 
12791     assert(vq >= 1 && vq <= ARM_MAX_VQ);
12792     assert(vq <= env_archcpu(env)->sve_max_vq);
12793 
12794     /* Zap the high bits of the zregs.  */
12795     for (i = 0; i < 32; i++) {
12796         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
12797     }
12798 
12799     /* Zap the high bits of the pregs and ffr.  */
12800     pmask = 0;
12801     if (vq & 3) {
12802         pmask = ~(-1ULL << (16 * (vq & 3)));
12803     }
12804     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
12805         for (i = 0; i < 17; ++i) {
12806             env->vfp.pregs[i].p[j] &= pmask;
12807         }
12808         pmask = 0;
12809     }
12810 }
12811 
12812 /*
12813  * Notice a change in SVE vector size when changing EL.
12814  */
12815 void aarch64_sve_change_el(CPUARMState *env, int old_el,
12816                            int new_el, bool el0_a64)
12817 {
12818     ARMCPU *cpu = env_archcpu(env);
12819     int old_len, new_len;
12820     bool old_a64, new_a64;
12821 
12822     /* Nothing to do if no SVE.  */
12823     if (!cpu_isar_feature(aa64_sve, cpu)) {
12824         return;
12825     }
12826 
12827     /* Nothing to do if FP is disabled in either EL.  */
12828     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
12829         return;
12830     }
12831 
12832     /*
12833      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
12834      * at ELx, or not available because the EL is in AArch32 state, then
12835      * for all purposes other than a direct read, the ZCR_ELx.LEN field
12836      * has an effective value of 0".
12837      *
12838      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
12839      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
12840      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
12841      * we already have the correct register contents when encountering the
12842      * vq0->vq0 transition between EL0->EL1.
12843      */
12844     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
12845     old_len = (old_a64 && !sve_exception_el(env, old_el)
12846                ? sve_zcr_len_for_el(env, old_el) : 0);
12847     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
12848     new_len = (new_a64 && !sve_exception_el(env, new_el)
12849                ? sve_zcr_len_for_el(env, new_el) : 0);
12850 
12851     /* When changing vector length, clear inaccessible state.  */
12852     if (new_len < old_len) {
12853         aarch64_sve_narrow_vq(env, new_len + 1);
12854     }
12855 }
12856 #endif
12857