xref: /openbmc/qemu/target/arm/helper.c (revision fc59d2d8)
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 "qemu/range.h"
29 #include "qapi/qapi-commands-machine-target.h"
30 #include "qapi/error.h"
31 #include "qemu/guest-random.h"
32 #ifdef CONFIG_TCG
33 #include "arm_ldst.h"
34 #include "exec/cpu_ldst.h"
35 #endif
36 
37 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
38 
39 #ifndef CONFIG_USER_ONLY
40 
41 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
42                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
43                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
44                                target_ulong *page_size_ptr,
45                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
46 #endif
47 
48 static void switch_mode(CPUARMState *env, int mode);
49 
50 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
51 {
52     int nregs;
53 
54     /* VFP data registers are always little-endian.  */
55     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
56     if (reg < nregs) {
57         stq_le_p(buf, *aa32_vfp_dreg(env, reg));
58         return 8;
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             stq_le_p(buf, q[0]);
66             stq_le_p(buf + 8, q[1]);
67             return 16;
68         }
69     }
70     switch (reg - nregs) {
71     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
72     case 1: stl_p(buf, vfp_get_fpscr(env)); return 4;
73     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
74     }
75     return 0;
76 }
77 
78 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
79 {
80     int nregs;
81 
82     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
83     if (reg < nregs) {
84         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
85         return 8;
86     }
87     if (arm_feature(env, ARM_FEATURE_NEON)) {
88         nregs += 16;
89         if (reg < nregs) {
90             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
91             q[0] = ldq_le_p(buf);
92             q[1] = ldq_le_p(buf + 8);
93             return 16;
94         }
95     }
96     switch (reg - nregs) {
97     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
98     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
99     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
100     }
101     return 0;
102 }
103 
104 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
105 {
106     switch (reg) {
107     case 0 ... 31:
108         /* 128 bit FP register */
109         {
110             uint64_t *q = aa64_vfp_qreg(env, reg);
111             stq_le_p(buf, q[0]);
112             stq_le_p(buf + 8, q[1]);
113             return 16;
114         }
115     case 32:
116         /* FPSR */
117         stl_p(buf, vfp_get_fpsr(env));
118         return 4;
119     case 33:
120         /* FPCR */
121         stl_p(buf, vfp_get_fpcr(env));
122         return 4;
123     default:
124         return 0;
125     }
126 }
127 
128 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
129 {
130     switch (reg) {
131     case 0 ... 31:
132         /* 128 bit FP register */
133         {
134             uint64_t *q = aa64_vfp_qreg(env, reg);
135             q[0] = ldq_le_p(buf);
136             q[1] = ldq_le_p(buf + 8);
137             return 16;
138         }
139     case 32:
140         /* FPSR */
141         vfp_set_fpsr(env, ldl_p(buf));
142         return 4;
143     case 33:
144         /* FPCR */
145         vfp_set_fpcr(env, ldl_p(buf));
146         return 4;
147     default:
148         return 0;
149     }
150 }
151 
152 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
153 {
154     assert(ri->fieldoffset);
155     if (cpreg_field_is_64bit(ri)) {
156         return CPREG_FIELD64(env, ri);
157     } else {
158         return CPREG_FIELD32(env, ri);
159     }
160 }
161 
162 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
163                       uint64_t value)
164 {
165     assert(ri->fieldoffset);
166     if (cpreg_field_is_64bit(ri)) {
167         CPREG_FIELD64(env, ri) = value;
168     } else {
169         CPREG_FIELD32(env, ri) = value;
170     }
171 }
172 
173 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
174 {
175     return (char *)env + ri->fieldoffset;
176 }
177 
178 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
179 {
180     /* Raw read of a coprocessor register (as needed for migration, etc). */
181     if (ri->type & ARM_CP_CONST) {
182         return ri->resetvalue;
183     } else if (ri->raw_readfn) {
184         return ri->raw_readfn(env, ri);
185     } else if (ri->readfn) {
186         return ri->readfn(env, ri);
187     } else {
188         return raw_read(env, ri);
189     }
190 }
191 
192 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
193                              uint64_t v)
194 {
195     /* Raw write of a coprocessor register (as needed for migration, etc).
196      * Note that constant registers are treated as write-ignored; the
197      * caller should check for success by whether a readback gives the
198      * value written.
199      */
200     if (ri->type & ARM_CP_CONST) {
201         return;
202     } else if (ri->raw_writefn) {
203         ri->raw_writefn(env, ri, v);
204     } else if (ri->writefn) {
205         ri->writefn(env, ri, v);
206     } else {
207         raw_write(env, ri, v);
208     }
209 }
210 
211 static int arm_gdb_get_sysreg(CPUARMState *env, uint8_t *buf, int reg)
212 {
213     ARMCPU *cpu = env_archcpu(env);
214     const ARMCPRegInfo *ri;
215     uint32_t key;
216 
217     key = cpu->dyn_xml.cpregs_keys[reg];
218     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
219     if (ri) {
220         if (cpreg_field_is_64bit(ri)) {
221             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
222         } else {
223             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
224         }
225     }
226     return 0;
227 }
228 
229 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
230 {
231     return 0;
232 }
233 
234 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
235 {
236    /* Return true if the regdef would cause an assertion if you called
237     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
238     * program bug for it not to have the NO_RAW flag).
239     * NB that returning false here doesn't necessarily mean that calling
240     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
241     * read/write access functions which are safe for raw use" from "has
242     * read/write access functions which have side effects but has forgotten
243     * to provide raw access functions".
244     * The tests here line up with the conditions in read/write_raw_cp_reg()
245     * and assertions in raw_read()/raw_write().
246     */
247     if ((ri->type & ARM_CP_CONST) ||
248         ri->fieldoffset ||
249         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
250         return false;
251     }
252     return true;
253 }
254 
255 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
256 {
257     /* Write the coprocessor state from cpu->env to the (index,value) list. */
258     int i;
259     bool ok = true;
260 
261     for (i = 0; i < cpu->cpreg_array_len; i++) {
262         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
263         const ARMCPRegInfo *ri;
264         uint64_t newval;
265 
266         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
267         if (!ri) {
268             ok = false;
269             continue;
270         }
271         if (ri->type & ARM_CP_NO_RAW) {
272             continue;
273         }
274 
275         newval = read_raw_cp_reg(&cpu->env, ri);
276         if (kvm_sync) {
277             /*
278              * Only sync if the previous list->cpustate sync succeeded.
279              * Rather than tracking the success/failure state for every
280              * item in the list, we just recheck "does the raw write we must
281              * have made in write_list_to_cpustate() read back OK" here.
282              */
283             uint64_t oldval = cpu->cpreg_values[i];
284 
285             if (oldval == newval) {
286                 continue;
287             }
288 
289             write_raw_cp_reg(&cpu->env, ri, oldval);
290             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
291                 continue;
292             }
293 
294             write_raw_cp_reg(&cpu->env, ri, newval);
295         }
296         cpu->cpreg_values[i] = newval;
297     }
298     return ok;
299 }
300 
301 bool write_list_to_cpustate(ARMCPU *cpu)
302 {
303     int i;
304     bool ok = true;
305 
306     for (i = 0; i < cpu->cpreg_array_len; i++) {
307         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
308         uint64_t v = cpu->cpreg_values[i];
309         const ARMCPRegInfo *ri;
310 
311         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
312         if (!ri) {
313             ok = false;
314             continue;
315         }
316         if (ri->type & ARM_CP_NO_RAW) {
317             continue;
318         }
319         /* Write value and confirm it reads back as written
320          * (to catch read-only registers and partially read-only
321          * registers where the incoming migration value doesn't match)
322          */
323         write_raw_cp_reg(&cpu->env, ri, v);
324         if (read_raw_cp_reg(&cpu->env, ri) != v) {
325             ok = false;
326         }
327     }
328     return ok;
329 }
330 
331 static void add_cpreg_to_list(gpointer key, gpointer opaque)
332 {
333     ARMCPU *cpu = opaque;
334     uint64_t regidx;
335     const ARMCPRegInfo *ri;
336 
337     regidx = *(uint32_t *)key;
338     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
339 
340     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
341         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
342         /* The value array need not be initialized at this point */
343         cpu->cpreg_array_len++;
344     }
345 }
346 
347 static void count_cpreg(gpointer key, gpointer opaque)
348 {
349     ARMCPU *cpu = opaque;
350     uint64_t regidx;
351     const ARMCPRegInfo *ri;
352 
353     regidx = *(uint32_t *)key;
354     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
355 
356     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
357         cpu->cpreg_array_len++;
358     }
359 }
360 
361 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
362 {
363     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
364     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
365 
366     if (aidx > bidx) {
367         return 1;
368     }
369     if (aidx < bidx) {
370         return -1;
371     }
372     return 0;
373 }
374 
375 void init_cpreg_list(ARMCPU *cpu)
376 {
377     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
378      * Note that we require cpreg_tuples[] to be sorted by key ID.
379      */
380     GList *keys;
381     int arraylen;
382 
383     keys = g_hash_table_get_keys(cpu->cp_regs);
384     keys = g_list_sort(keys, cpreg_key_compare);
385 
386     cpu->cpreg_array_len = 0;
387 
388     g_list_foreach(keys, count_cpreg, cpu);
389 
390     arraylen = cpu->cpreg_array_len;
391     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
392     cpu->cpreg_values = g_new(uint64_t, arraylen);
393     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
394     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
395     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
396     cpu->cpreg_array_len = 0;
397 
398     g_list_foreach(keys, add_cpreg_to_list, cpu);
399 
400     assert(cpu->cpreg_array_len == arraylen);
401 
402     g_list_free(keys);
403 }
404 
405 /*
406  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
407  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
408  *
409  * access_el3_aa32ns: Used to check AArch32 register views.
410  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
411  */
412 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
413                                         const ARMCPRegInfo *ri,
414                                         bool isread)
415 {
416     bool secure = arm_is_secure_below_el3(env);
417 
418     assert(!arm_el_is_aa64(env, 3));
419     if (secure) {
420         return CP_ACCESS_TRAP_UNCATEGORIZED;
421     }
422     return CP_ACCESS_OK;
423 }
424 
425 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
426                                                 const ARMCPRegInfo *ri,
427                                                 bool isread)
428 {
429     if (!arm_el_is_aa64(env, 3)) {
430         return access_el3_aa32ns(env, ri, isread);
431     }
432     return CP_ACCESS_OK;
433 }
434 
435 /* Some secure-only AArch32 registers trap to EL3 if used from
436  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
437  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
438  * We assume that the .access field is set to PL1_RW.
439  */
440 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
441                                             const ARMCPRegInfo *ri,
442                                             bool isread)
443 {
444     if (arm_current_el(env) == 3) {
445         return CP_ACCESS_OK;
446     }
447     if (arm_is_secure_below_el3(env)) {
448         return CP_ACCESS_TRAP_EL3;
449     }
450     /* This will be EL1 NS and EL2 NS, which just UNDEF */
451     return CP_ACCESS_TRAP_UNCATEGORIZED;
452 }
453 
454 /* Check for traps to "powerdown debug" registers, which are controlled
455  * by MDCR.TDOSA
456  */
457 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
458                                    bool isread)
459 {
460     int el = arm_current_el(env);
461     bool mdcr_el2_tdosa = (env->cp15.mdcr_el2 & MDCR_TDOSA) ||
462         (env->cp15.mdcr_el2 & MDCR_TDE) ||
463         (arm_hcr_el2_eff(env) & HCR_TGE);
464 
465     if (el < 2 && mdcr_el2_tdosa && !arm_is_secure_below_el3(env)) {
466         return CP_ACCESS_TRAP_EL2;
467     }
468     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
469         return CP_ACCESS_TRAP_EL3;
470     }
471     return CP_ACCESS_OK;
472 }
473 
474 /* Check for traps to "debug ROM" registers, which are controlled
475  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
476  */
477 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
478                                   bool isread)
479 {
480     int el = arm_current_el(env);
481     bool mdcr_el2_tdra = (env->cp15.mdcr_el2 & MDCR_TDRA) ||
482         (env->cp15.mdcr_el2 & MDCR_TDE) ||
483         (arm_hcr_el2_eff(env) & HCR_TGE);
484 
485     if (el < 2 && mdcr_el2_tdra && !arm_is_secure_below_el3(env)) {
486         return CP_ACCESS_TRAP_EL2;
487     }
488     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
489         return CP_ACCESS_TRAP_EL3;
490     }
491     return CP_ACCESS_OK;
492 }
493 
494 /* Check for traps to general debug registers, which are controlled
495  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
496  */
497 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
498                                   bool isread)
499 {
500     int el = arm_current_el(env);
501     bool mdcr_el2_tda = (env->cp15.mdcr_el2 & MDCR_TDA) ||
502         (env->cp15.mdcr_el2 & MDCR_TDE) ||
503         (arm_hcr_el2_eff(env) & HCR_TGE);
504 
505     if (el < 2 && mdcr_el2_tda && !arm_is_secure_below_el3(env)) {
506         return CP_ACCESS_TRAP_EL2;
507     }
508     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
509         return CP_ACCESS_TRAP_EL3;
510     }
511     return CP_ACCESS_OK;
512 }
513 
514 /* Check for traps to performance monitor registers, which are controlled
515  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
516  */
517 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
518                                  bool isread)
519 {
520     int el = arm_current_el(env);
521 
522     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
523         && !arm_is_secure_below_el3(env)) {
524         return CP_ACCESS_TRAP_EL2;
525     }
526     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
527         return CP_ACCESS_TRAP_EL3;
528     }
529     return CP_ACCESS_OK;
530 }
531 
532 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
533 {
534     ARMCPU *cpu = env_archcpu(env);
535 
536     raw_write(env, ri, value);
537     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
538 }
539 
540 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
541 {
542     ARMCPU *cpu = env_archcpu(env);
543 
544     if (raw_read(env, ri) != value) {
545         /* Unlike real hardware the qemu TLB uses virtual addresses,
546          * not modified virtual addresses, so this causes a TLB flush.
547          */
548         tlb_flush(CPU(cpu));
549         raw_write(env, ri, value);
550     }
551 }
552 
553 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
554                              uint64_t value)
555 {
556     ARMCPU *cpu = env_archcpu(env);
557 
558     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
559         && !extended_addresses_enabled(env)) {
560         /* For VMSA (when not using the LPAE long descriptor page table
561          * format) this register includes the ASID, so do a TLB flush.
562          * For PMSA it is purely a process ID and no action is needed.
563          */
564         tlb_flush(CPU(cpu));
565     }
566     raw_write(env, ri, value);
567 }
568 
569 /* IS variants of TLB operations must affect all cores */
570 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
571                              uint64_t value)
572 {
573     CPUState *cs = env_cpu(env);
574 
575     tlb_flush_all_cpus_synced(cs);
576 }
577 
578 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
579                              uint64_t value)
580 {
581     CPUState *cs = env_cpu(env);
582 
583     tlb_flush_all_cpus_synced(cs);
584 }
585 
586 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
587                              uint64_t value)
588 {
589     CPUState *cs = env_cpu(env);
590 
591     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
592 }
593 
594 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
595                              uint64_t value)
596 {
597     CPUState *cs = env_cpu(env);
598 
599     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
600 }
601 
602 /*
603  * Non-IS variants of TLB operations are upgraded to
604  * IS versions if we are at NS EL1 and HCR_EL2.FB is set to
605  * force broadcast of these operations.
606  */
607 static bool tlb_force_broadcast(CPUARMState *env)
608 {
609     return (env->cp15.hcr_el2 & HCR_FB) &&
610         arm_current_el(env) == 1 && arm_is_secure_below_el3(env);
611 }
612 
613 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
614                           uint64_t value)
615 {
616     /* Invalidate all (TLBIALL) */
617     ARMCPU *cpu = env_archcpu(env);
618 
619     if (tlb_force_broadcast(env)) {
620         tlbiall_is_write(env, NULL, value);
621         return;
622     }
623 
624     tlb_flush(CPU(cpu));
625 }
626 
627 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
628                           uint64_t value)
629 {
630     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
631     ARMCPU *cpu = env_archcpu(env);
632 
633     if (tlb_force_broadcast(env)) {
634         tlbimva_is_write(env, NULL, value);
635         return;
636     }
637 
638     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
639 }
640 
641 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
642                            uint64_t value)
643 {
644     /* Invalidate by ASID (TLBIASID) */
645     ARMCPU *cpu = env_archcpu(env);
646 
647     if (tlb_force_broadcast(env)) {
648         tlbiasid_is_write(env, NULL, value);
649         return;
650     }
651 
652     tlb_flush(CPU(cpu));
653 }
654 
655 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
656                            uint64_t value)
657 {
658     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
659     ARMCPU *cpu = env_archcpu(env);
660 
661     if (tlb_force_broadcast(env)) {
662         tlbimvaa_is_write(env, NULL, value);
663         return;
664     }
665 
666     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
667 }
668 
669 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
670                                uint64_t value)
671 {
672     CPUState *cs = env_cpu(env);
673 
674     tlb_flush_by_mmuidx(cs,
675                         ARMMMUIdxBit_S12NSE1 |
676                         ARMMMUIdxBit_S12NSE0 |
677                         ARMMMUIdxBit_S2NS);
678 }
679 
680 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
681                                   uint64_t value)
682 {
683     CPUState *cs = env_cpu(env);
684 
685     tlb_flush_by_mmuidx_all_cpus_synced(cs,
686                                         ARMMMUIdxBit_S12NSE1 |
687                                         ARMMMUIdxBit_S12NSE0 |
688                                         ARMMMUIdxBit_S2NS);
689 }
690 
691 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
692                             uint64_t value)
693 {
694     /* Invalidate by IPA. This has to invalidate any structures that
695      * contain only stage 2 translation information, but does not need
696      * to apply to structures that contain combined stage 1 and stage 2
697      * translation information.
698      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
699      */
700     CPUState *cs = env_cpu(env);
701     uint64_t pageaddr;
702 
703     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
704         return;
705     }
706 
707     pageaddr = sextract64(value << 12, 0, 40);
708 
709     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
710 }
711 
712 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
713                                uint64_t value)
714 {
715     CPUState *cs = env_cpu(env);
716     uint64_t pageaddr;
717 
718     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
719         return;
720     }
721 
722     pageaddr = sextract64(value << 12, 0, 40);
723 
724     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
725                                              ARMMMUIdxBit_S2NS);
726 }
727 
728 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
729                               uint64_t value)
730 {
731     CPUState *cs = env_cpu(env);
732 
733     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
734 }
735 
736 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
737                                  uint64_t value)
738 {
739     CPUState *cs = env_cpu(env);
740 
741     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
742 }
743 
744 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
745                               uint64_t value)
746 {
747     CPUState *cs = env_cpu(env);
748     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
749 
750     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
751 }
752 
753 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
754                                  uint64_t value)
755 {
756     CPUState *cs = env_cpu(env);
757     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
758 
759     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
760                                              ARMMMUIdxBit_S1E2);
761 }
762 
763 static const ARMCPRegInfo cp_reginfo[] = {
764     /* Define the secure and non-secure FCSE identifier CP registers
765      * separately because there is no secure bank in V8 (no _EL3).  This allows
766      * the secure register to be properly reset and migrated. There is also no
767      * v8 EL1 version of the register so the non-secure instance stands alone.
768      */
769     { .name = "FCSEIDR",
770       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
771       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
772       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
773       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
774     { .name = "FCSEIDR_S",
775       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
776       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
777       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
778       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
779     /* Define the secure and non-secure context identifier CP registers
780      * separately because there is no secure bank in V8 (no _EL3).  This allows
781      * the secure register to be properly reset and migrated.  In the
782      * non-secure case, the 32-bit register will have reset and migration
783      * disabled during registration as it is handled by the 64-bit instance.
784      */
785     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
786       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
787       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
788       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
789       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
790     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
791       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
792       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
793       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
794       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
795     REGINFO_SENTINEL
796 };
797 
798 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
799     /* NB: Some of these registers exist in v8 but with more precise
800      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
801      */
802     /* MMU Domain access control / MPU write buffer control */
803     { .name = "DACR",
804       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
805       .access = PL1_RW, .resetvalue = 0,
806       .writefn = dacr_write, .raw_writefn = raw_write,
807       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
808                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
809     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
810      * For v6 and v5, these mappings are overly broad.
811      */
812     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
813       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
814     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
815       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
816     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
817       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
818     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
819       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
820     /* Cache maintenance ops; some of this space may be overridden later. */
821     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
822       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
823       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
824     REGINFO_SENTINEL
825 };
826 
827 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
828     /* Not all pre-v6 cores implemented this WFI, so this is slightly
829      * over-broad.
830      */
831     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
832       .access = PL1_W, .type = ARM_CP_WFI },
833     REGINFO_SENTINEL
834 };
835 
836 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
837     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
838      * is UNPREDICTABLE; we choose to NOP as most implementations do).
839      */
840     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
841       .access = PL1_W, .type = ARM_CP_WFI },
842     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
843      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
844      * OMAPCP will override this space.
845      */
846     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
847       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
848       .resetvalue = 0 },
849     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
850       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
851       .resetvalue = 0 },
852     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
853     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
854       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
855       .resetvalue = 0 },
856     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
857      * implementing it as RAZ means the "debug architecture version" bits
858      * will read as a reserved value, which should cause Linux to not try
859      * to use the debug hardware.
860      */
861     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
862       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
863     /* MMU TLB control. Note that the wildcarding means we cover not just
864      * the unified TLB ops but also the dside/iside/inner-shareable variants.
865      */
866     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
867       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
868       .type = ARM_CP_NO_RAW },
869     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
870       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
871       .type = ARM_CP_NO_RAW },
872     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
873       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
874       .type = ARM_CP_NO_RAW },
875     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
876       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
877       .type = ARM_CP_NO_RAW },
878     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
879       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
880     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
881       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
882     REGINFO_SENTINEL
883 };
884 
885 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
886                         uint64_t value)
887 {
888     uint32_t mask = 0;
889 
890     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
891     if (!arm_feature(env, ARM_FEATURE_V8)) {
892         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
893          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
894          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
895          */
896         if (arm_feature(env, ARM_FEATURE_VFP)) {
897             /* VFP coprocessor: cp10 & cp11 [23:20] */
898             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
899 
900             if (!arm_feature(env, ARM_FEATURE_NEON)) {
901                 /* ASEDIS [31] bit is RAO/WI */
902                 value |= (1 << 31);
903             }
904 
905             /* VFPv3 and upwards with NEON implement 32 double precision
906              * registers (D0-D31).
907              */
908             if (!arm_feature(env, ARM_FEATURE_NEON) ||
909                     !arm_feature(env, ARM_FEATURE_VFP3)) {
910                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
911                 value |= (1 << 30);
912             }
913         }
914         value &= mask;
915     }
916 
917     /*
918      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
919      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
920      */
921     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
922         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
923         value &= ~(0xf << 20);
924         value |= env->cp15.cpacr_el1 & (0xf << 20);
925     }
926 
927     env->cp15.cpacr_el1 = value;
928 }
929 
930 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
931 {
932     /*
933      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
934      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
935      */
936     uint64_t value = env->cp15.cpacr_el1;
937 
938     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
939         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
940         value &= ~(0xf << 20);
941     }
942     return value;
943 }
944 
945 
946 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
947 {
948     /* Call cpacr_write() so that we reset with the correct RAO bits set
949      * for our CPU features.
950      */
951     cpacr_write(env, ri, 0);
952 }
953 
954 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
955                                    bool isread)
956 {
957     if (arm_feature(env, ARM_FEATURE_V8)) {
958         /* Check if CPACR accesses are to be trapped to EL2 */
959         if (arm_current_el(env) == 1 &&
960             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
961             return CP_ACCESS_TRAP_EL2;
962         /* Check if CPACR accesses are to be trapped to EL3 */
963         } else if (arm_current_el(env) < 3 &&
964                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
965             return CP_ACCESS_TRAP_EL3;
966         }
967     }
968 
969     return CP_ACCESS_OK;
970 }
971 
972 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
973                                   bool isread)
974 {
975     /* Check if CPTR accesses are set to trap to EL3 */
976     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
977         return CP_ACCESS_TRAP_EL3;
978     }
979 
980     return CP_ACCESS_OK;
981 }
982 
983 static const ARMCPRegInfo v6_cp_reginfo[] = {
984     /* prefetch by MVA in v6, NOP in v7 */
985     { .name = "MVA_prefetch",
986       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
987       .access = PL1_W, .type = ARM_CP_NOP },
988     /* We need to break the TB after ISB to execute self-modifying code
989      * correctly and also to take any pending interrupts immediately.
990      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
991      */
992     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
993       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
994     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
995       .access = PL0_W, .type = ARM_CP_NOP },
996     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
997       .access = PL0_W, .type = ARM_CP_NOP },
998     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
999       .access = PL1_RW,
1000       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
1001                              offsetof(CPUARMState, cp15.ifar_ns) },
1002       .resetvalue = 0, },
1003     /* Watchpoint Fault Address Register : should actually only be present
1004      * for 1136, 1176, 11MPCore.
1005      */
1006     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
1007       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
1008     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
1009       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
1010       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
1011       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
1012     REGINFO_SENTINEL
1013 };
1014 
1015 /* Definitions for the PMU registers */
1016 #define PMCRN_MASK  0xf800
1017 #define PMCRN_SHIFT 11
1018 #define PMCRLC  0x40
1019 #define PMCRDP  0x10
1020 #define PMCRD   0x8
1021 #define PMCRC   0x4
1022 #define PMCRP   0x2
1023 #define PMCRE   0x1
1024 
1025 #define PMXEVTYPER_P          0x80000000
1026 #define PMXEVTYPER_U          0x40000000
1027 #define PMXEVTYPER_NSK        0x20000000
1028 #define PMXEVTYPER_NSU        0x10000000
1029 #define PMXEVTYPER_NSH        0x08000000
1030 #define PMXEVTYPER_M          0x04000000
1031 #define PMXEVTYPER_MT         0x02000000
1032 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1033 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1034                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1035                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1036                                PMXEVTYPER_EVTCOUNT)
1037 
1038 #define PMCCFILTR             0xf8000000
1039 #define PMCCFILTR_M           PMXEVTYPER_M
1040 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1041 
1042 static inline uint32_t pmu_num_counters(CPUARMState *env)
1043 {
1044   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1045 }
1046 
1047 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1048 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1049 {
1050   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1051 }
1052 
1053 typedef struct pm_event {
1054     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1055     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1056     bool (*supported)(CPUARMState *);
1057     /*
1058      * Retrieve the current count of the underlying event. The programmed
1059      * counters hold a difference from the return value from this function
1060      */
1061     uint64_t (*get_count)(CPUARMState *);
1062     /*
1063      * Return how many nanoseconds it will take (at a minimum) for count events
1064      * to occur. A negative value indicates the counter will never overflow, or
1065      * that the counter has otherwise arranged for the overflow bit to be set
1066      * and the PMU interrupt to be raised on overflow.
1067      */
1068     int64_t (*ns_per_count)(uint64_t);
1069 } pm_event;
1070 
1071 static bool event_always_supported(CPUARMState *env)
1072 {
1073     return true;
1074 }
1075 
1076 static uint64_t swinc_get_count(CPUARMState *env)
1077 {
1078     /*
1079      * SW_INCR events are written directly to the pmevcntr's by writes to
1080      * PMSWINC, so there is no underlying count maintained by the PMU itself
1081      */
1082     return 0;
1083 }
1084 
1085 static int64_t swinc_ns_per(uint64_t ignored)
1086 {
1087     return -1;
1088 }
1089 
1090 /*
1091  * Return the underlying cycle count for the PMU cycle counters. If we're in
1092  * usermode, simply return 0.
1093  */
1094 static uint64_t cycles_get_count(CPUARMState *env)
1095 {
1096 #ifndef CONFIG_USER_ONLY
1097     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1098                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1099 #else
1100     return cpu_get_host_ticks();
1101 #endif
1102 }
1103 
1104 #ifndef CONFIG_USER_ONLY
1105 static int64_t cycles_ns_per(uint64_t cycles)
1106 {
1107     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1108 }
1109 
1110 static bool instructions_supported(CPUARMState *env)
1111 {
1112     return use_icount == 1 /* Precise instruction counting */;
1113 }
1114 
1115 static uint64_t instructions_get_count(CPUARMState *env)
1116 {
1117     return (uint64_t)cpu_get_icount_raw();
1118 }
1119 
1120 static int64_t instructions_ns_per(uint64_t icount)
1121 {
1122     return cpu_icount_to_ns((int64_t)icount);
1123 }
1124 #endif
1125 
1126 static const pm_event pm_events[] = {
1127     { .number = 0x000, /* SW_INCR */
1128       .supported = event_always_supported,
1129       .get_count = swinc_get_count,
1130       .ns_per_count = swinc_ns_per,
1131     },
1132 #ifndef CONFIG_USER_ONLY
1133     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1134       .supported = instructions_supported,
1135       .get_count = instructions_get_count,
1136       .ns_per_count = instructions_ns_per,
1137     },
1138     { .number = 0x011, /* CPU_CYCLES, Cycle */
1139       .supported = event_always_supported,
1140       .get_count = cycles_get_count,
1141       .ns_per_count = cycles_ns_per,
1142     }
1143 #endif
1144 };
1145 
1146 /*
1147  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1148  * events (i.e. the statistical profiling extension), this implementation
1149  * should first be updated to something sparse instead of the current
1150  * supported_event_map[] array.
1151  */
1152 #define MAX_EVENT_ID 0x11
1153 #define UNSUPPORTED_EVENT UINT16_MAX
1154 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1155 
1156 /*
1157  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1158  * of ARM event numbers to indices in our pm_events array.
1159  *
1160  * Note: Events in the 0x40XX range are not currently supported.
1161  */
1162 void pmu_init(ARMCPU *cpu)
1163 {
1164     unsigned int i;
1165 
1166     /*
1167      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1168      * events to them
1169      */
1170     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1171         supported_event_map[i] = UNSUPPORTED_EVENT;
1172     }
1173     cpu->pmceid0 = 0;
1174     cpu->pmceid1 = 0;
1175 
1176     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1177         const pm_event *cnt = &pm_events[i];
1178         assert(cnt->number <= MAX_EVENT_ID);
1179         /* We do not currently support events in the 0x40xx range */
1180         assert(cnt->number <= 0x3f);
1181 
1182         if (cnt->supported(&cpu->env)) {
1183             supported_event_map[cnt->number] = i;
1184             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1185             if (cnt->number & 0x20) {
1186                 cpu->pmceid1 |= event_mask;
1187             } else {
1188                 cpu->pmceid0 |= event_mask;
1189             }
1190         }
1191     }
1192 }
1193 
1194 /*
1195  * Check at runtime whether a PMU event is supported for the current machine
1196  */
1197 static bool event_supported(uint16_t number)
1198 {
1199     if (number > MAX_EVENT_ID) {
1200         return false;
1201     }
1202     return supported_event_map[number] != UNSUPPORTED_EVENT;
1203 }
1204 
1205 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1206                                    bool isread)
1207 {
1208     /* Performance monitor registers user accessibility is controlled
1209      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1210      * trapping to EL2 or EL3 for other accesses.
1211      */
1212     int el = arm_current_el(env);
1213 
1214     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1215         return CP_ACCESS_TRAP;
1216     }
1217     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
1218         && !arm_is_secure_below_el3(env)) {
1219         return CP_ACCESS_TRAP_EL2;
1220     }
1221     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1222         return CP_ACCESS_TRAP_EL3;
1223     }
1224 
1225     return CP_ACCESS_OK;
1226 }
1227 
1228 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1229                                            const ARMCPRegInfo *ri,
1230                                            bool isread)
1231 {
1232     /* ER: event counter read trap control */
1233     if (arm_feature(env, ARM_FEATURE_V8)
1234         && arm_current_el(env) == 0
1235         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1236         && isread) {
1237         return CP_ACCESS_OK;
1238     }
1239 
1240     return pmreg_access(env, ri, isread);
1241 }
1242 
1243 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1244                                          const ARMCPRegInfo *ri,
1245                                          bool isread)
1246 {
1247     /* SW: software increment write trap control */
1248     if (arm_feature(env, ARM_FEATURE_V8)
1249         && arm_current_el(env) == 0
1250         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1251         && !isread) {
1252         return CP_ACCESS_OK;
1253     }
1254 
1255     return pmreg_access(env, ri, isread);
1256 }
1257 
1258 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1259                                         const ARMCPRegInfo *ri,
1260                                         bool isread)
1261 {
1262     /* ER: event counter read trap control */
1263     if (arm_feature(env, ARM_FEATURE_V8)
1264         && arm_current_el(env) == 0
1265         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1266         return CP_ACCESS_OK;
1267     }
1268 
1269     return pmreg_access(env, ri, isread);
1270 }
1271 
1272 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1273                                          const ARMCPRegInfo *ri,
1274                                          bool isread)
1275 {
1276     /* CR: cycle counter read trap control */
1277     if (arm_feature(env, ARM_FEATURE_V8)
1278         && arm_current_el(env) == 0
1279         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1280         && isread) {
1281         return CP_ACCESS_OK;
1282     }
1283 
1284     return pmreg_access(env, ri, isread);
1285 }
1286 
1287 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1288  * the current EL, security state, and register configuration.
1289  */
1290 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1291 {
1292     uint64_t filter;
1293     bool e, p, u, nsk, nsu, nsh, m;
1294     bool enabled, prohibited, filtered;
1295     bool secure = arm_is_secure(env);
1296     int el = arm_current_el(env);
1297     uint8_t hpmn = env->cp15.mdcr_el2 & MDCR_HPMN;
1298 
1299     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1300         return false;
1301     }
1302 
1303     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1304             (counter < hpmn || counter == 31)) {
1305         e = env->cp15.c9_pmcr & PMCRE;
1306     } else {
1307         e = env->cp15.mdcr_el2 & MDCR_HPME;
1308     }
1309     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1310 
1311     if (!secure) {
1312         if (el == 2 && (counter < hpmn || counter == 31)) {
1313             prohibited = env->cp15.mdcr_el2 & MDCR_HPMD;
1314         } else {
1315             prohibited = false;
1316         }
1317     } else {
1318         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1319            (env->cp15.mdcr_el3 & MDCR_SPME);
1320     }
1321 
1322     if (prohibited && counter == 31) {
1323         prohibited = env->cp15.c9_pmcr & PMCRDP;
1324     }
1325 
1326     if (counter == 31) {
1327         filter = env->cp15.pmccfiltr_el0;
1328     } else {
1329         filter = env->cp15.c14_pmevtyper[counter];
1330     }
1331 
1332     p   = filter & PMXEVTYPER_P;
1333     u   = filter & PMXEVTYPER_U;
1334     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1335     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1336     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1337     m   = arm_el_is_aa64(env, 1) &&
1338               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1339 
1340     if (el == 0) {
1341         filtered = secure ? u : u != nsu;
1342     } else if (el == 1) {
1343         filtered = secure ? p : p != nsk;
1344     } else if (el == 2) {
1345         filtered = !nsh;
1346     } else { /* EL3 */
1347         filtered = m != p;
1348     }
1349 
1350     if (counter != 31) {
1351         /*
1352          * If not checking PMCCNTR, ensure the counter is setup to an event we
1353          * support
1354          */
1355         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1356         if (!event_supported(event)) {
1357             return false;
1358         }
1359     }
1360 
1361     return enabled && !prohibited && !filtered;
1362 }
1363 
1364 static void pmu_update_irq(CPUARMState *env)
1365 {
1366     ARMCPU *cpu = env_archcpu(env);
1367     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1368             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1369 }
1370 
1371 /*
1372  * Ensure c15_ccnt is the guest-visible count so that operations such as
1373  * enabling/disabling the counter or filtering, modifying the count itself,
1374  * etc. can be done logically. This is essentially a no-op if the counter is
1375  * not enabled at the time of the call.
1376  */
1377 static void pmccntr_op_start(CPUARMState *env)
1378 {
1379     uint64_t cycles = cycles_get_count(env);
1380 
1381     if (pmu_counter_enabled(env, 31)) {
1382         uint64_t eff_cycles = cycles;
1383         if (env->cp15.c9_pmcr & PMCRD) {
1384             /* Increment once every 64 processor clock cycles */
1385             eff_cycles /= 64;
1386         }
1387 
1388         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1389 
1390         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1391                                  1ull << 63 : 1ull << 31;
1392         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1393             env->cp15.c9_pmovsr |= (1 << 31);
1394             pmu_update_irq(env);
1395         }
1396 
1397         env->cp15.c15_ccnt = new_pmccntr;
1398     }
1399     env->cp15.c15_ccnt_delta = cycles;
1400 }
1401 
1402 /*
1403  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1404  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1405  * pmccntr_op_start.
1406  */
1407 static void pmccntr_op_finish(CPUARMState *env)
1408 {
1409     if (pmu_counter_enabled(env, 31)) {
1410 #ifndef CONFIG_USER_ONLY
1411         /* Calculate when the counter will next overflow */
1412         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1413         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1414             remaining_cycles = (uint32_t)remaining_cycles;
1415         }
1416         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1417 
1418         if (overflow_in > 0) {
1419             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1420                 overflow_in;
1421             ARMCPU *cpu = env_archcpu(env);
1422             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1423         }
1424 #endif
1425 
1426         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1427         if (env->cp15.c9_pmcr & PMCRD) {
1428             /* Increment once every 64 processor clock cycles */
1429             prev_cycles /= 64;
1430         }
1431         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1432     }
1433 }
1434 
1435 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1436 {
1437 
1438     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1439     uint64_t count = 0;
1440     if (event_supported(event)) {
1441         uint16_t event_idx = supported_event_map[event];
1442         count = pm_events[event_idx].get_count(env);
1443     }
1444 
1445     if (pmu_counter_enabled(env, counter)) {
1446         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1447 
1448         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1449             env->cp15.c9_pmovsr |= (1 << counter);
1450             pmu_update_irq(env);
1451         }
1452         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1453     }
1454     env->cp15.c14_pmevcntr_delta[counter] = count;
1455 }
1456 
1457 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1458 {
1459     if (pmu_counter_enabled(env, counter)) {
1460 #ifndef CONFIG_USER_ONLY
1461         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1462         uint16_t event_idx = supported_event_map[event];
1463         uint64_t delta = UINT32_MAX -
1464             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1465         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1466 
1467         if (overflow_in > 0) {
1468             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1469                 overflow_in;
1470             ARMCPU *cpu = env_archcpu(env);
1471             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1472         }
1473 #endif
1474 
1475         env->cp15.c14_pmevcntr_delta[counter] -=
1476             env->cp15.c14_pmevcntr[counter];
1477     }
1478 }
1479 
1480 void pmu_op_start(CPUARMState *env)
1481 {
1482     unsigned int i;
1483     pmccntr_op_start(env);
1484     for (i = 0; i < pmu_num_counters(env); i++) {
1485         pmevcntr_op_start(env, i);
1486     }
1487 }
1488 
1489 void pmu_op_finish(CPUARMState *env)
1490 {
1491     unsigned int i;
1492     pmccntr_op_finish(env);
1493     for (i = 0; i < pmu_num_counters(env); i++) {
1494         pmevcntr_op_finish(env, i);
1495     }
1496 }
1497 
1498 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1499 {
1500     pmu_op_start(&cpu->env);
1501 }
1502 
1503 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1504 {
1505     pmu_op_finish(&cpu->env);
1506 }
1507 
1508 void arm_pmu_timer_cb(void *opaque)
1509 {
1510     ARMCPU *cpu = opaque;
1511 
1512     /*
1513      * Update all the counter values based on the current underlying counts,
1514      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1515      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1516      * counter may expire.
1517      */
1518     pmu_op_start(&cpu->env);
1519     pmu_op_finish(&cpu->env);
1520 }
1521 
1522 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1523                        uint64_t value)
1524 {
1525     pmu_op_start(env);
1526 
1527     if (value & PMCRC) {
1528         /* The counter has been reset */
1529         env->cp15.c15_ccnt = 0;
1530     }
1531 
1532     if (value & PMCRP) {
1533         unsigned int i;
1534         for (i = 0; i < pmu_num_counters(env); i++) {
1535             env->cp15.c14_pmevcntr[i] = 0;
1536         }
1537     }
1538 
1539     /* only the DP, X, D and E bits are writable */
1540     env->cp15.c9_pmcr &= ~0x39;
1541     env->cp15.c9_pmcr |= (value & 0x39);
1542 
1543     pmu_op_finish(env);
1544 }
1545 
1546 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1547                           uint64_t value)
1548 {
1549     unsigned int i;
1550     for (i = 0; i < pmu_num_counters(env); i++) {
1551         /* Increment a counter's count iff: */
1552         if ((value & (1 << i)) && /* counter's bit is set */
1553                 /* counter is enabled and not filtered */
1554                 pmu_counter_enabled(env, i) &&
1555                 /* counter is SW_INCR */
1556                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1557             pmevcntr_op_start(env, i);
1558 
1559             /*
1560              * Detect if this write causes an overflow since we can't predict
1561              * PMSWINC overflows like we can for other events
1562              */
1563             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1564 
1565             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1566                 env->cp15.c9_pmovsr |= (1 << i);
1567                 pmu_update_irq(env);
1568             }
1569 
1570             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1571 
1572             pmevcntr_op_finish(env, i);
1573         }
1574     }
1575 }
1576 
1577 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1578 {
1579     uint64_t ret;
1580     pmccntr_op_start(env);
1581     ret = env->cp15.c15_ccnt;
1582     pmccntr_op_finish(env);
1583     return ret;
1584 }
1585 
1586 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1587                          uint64_t value)
1588 {
1589     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1590      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1591      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1592      * accessed.
1593      */
1594     env->cp15.c9_pmselr = value & 0x1f;
1595 }
1596 
1597 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1598                         uint64_t value)
1599 {
1600     pmccntr_op_start(env);
1601     env->cp15.c15_ccnt = value;
1602     pmccntr_op_finish(env);
1603 }
1604 
1605 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1606                             uint64_t value)
1607 {
1608     uint64_t cur_val = pmccntr_read(env, NULL);
1609 
1610     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1611 }
1612 
1613 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1614                             uint64_t value)
1615 {
1616     pmccntr_op_start(env);
1617     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1618     pmccntr_op_finish(env);
1619 }
1620 
1621 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1622                             uint64_t value)
1623 {
1624     pmccntr_op_start(env);
1625     /* M is not accessible from AArch32 */
1626     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1627         (value & PMCCFILTR);
1628     pmccntr_op_finish(env);
1629 }
1630 
1631 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1632 {
1633     /* M is not visible in AArch32 */
1634     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1635 }
1636 
1637 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1638                             uint64_t value)
1639 {
1640     value &= pmu_counter_mask(env);
1641     env->cp15.c9_pmcnten |= value;
1642 }
1643 
1644 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1645                              uint64_t value)
1646 {
1647     value &= pmu_counter_mask(env);
1648     env->cp15.c9_pmcnten &= ~value;
1649 }
1650 
1651 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1652                          uint64_t value)
1653 {
1654     value &= pmu_counter_mask(env);
1655     env->cp15.c9_pmovsr &= ~value;
1656     pmu_update_irq(env);
1657 }
1658 
1659 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1660                          uint64_t value)
1661 {
1662     value &= pmu_counter_mask(env);
1663     env->cp15.c9_pmovsr |= value;
1664     pmu_update_irq(env);
1665 }
1666 
1667 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1668                              uint64_t value, const uint8_t counter)
1669 {
1670     if (counter == 31) {
1671         pmccfiltr_write(env, ri, value);
1672     } else if (counter < pmu_num_counters(env)) {
1673         pmevcntr_op_start(env, counter);
1674 
1675         /*
1676          * If this counter's event type is changing, store the current
1677          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1678          * pmevcntr_op_finish has the correct baseline when it converts back to
1679          * a delta.
1680          */
1681         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1682             PMXEVTYPER_EVTCOUNT;
1683         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1684         if (old_event != new_event) {
1685             uint64_t count = 0;
1686             if (event_supported(new_event)) {
1687                 uint16_t event_idx = supported_event_map[new_event];
1688                 count = pm_events[event_idx].get_count(env);
1689             }
1690             env->cp15.c14_pmevcntr_delta[counter] = count;
1691         }
1692 
1693         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1694         pmevcntr_op_finish(env, counter);
1695     }
1696     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1697      * PMSELR value is equal to or greater than the number of implemented
1698      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1699      */
1700 }
1701 
1702 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1703                                const uint8_t counter)
1704 {
1705     if (counter == 31) {
1706         return env->cp15.pmccfiltr_el0;
1707     } else if (counter < pmu_num_counters(env)) {
1708         return env->cp15.c14_pmevtyper[counter];
1709     } else {
1710       /*
1711        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1712        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1713        */
1714         return 0;
1715     }
1716 }
1717 
1718 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1719                               uint64_t value)
1720 {
1721     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1722     pmevtyper_write(env, ri, value, counter);
1723 }
1724 
1725 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1726                                uint64_t value)
1727 {
1728     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1729     env->cp15.c14_pmevtyper[counter] = value;
1730 
1731     /*
1732      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1733      * pmu_op_finish calls when loading saved state for a migration. Because
1734      * we're potentially updating the type of event here, the value written to
1735      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1736      * different counter type. Therefore, we need to set this value to the
1737      * current count for the counter type we're writing so that pmu_op_finish
1738      * has the correct count for its calculation.
1739      */
1740     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1741     if (event_supported(event)) {
1742         uint16_t event_idx = supported_event_map[event];
1743         env->cp15.c14_pmevcntr_delta[counter] =
1744             pm_events[event_idx].get_count(env);
1745     }
1746 }
1747 
1748 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1749 {
1750     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1751     return pmevtyper_read(env, ri, counter);
1752 }
1753 
1754 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1755                              uint64_t value)
1756 {
1757     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1758 }
1759 
1760 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1761 {
1762     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1763 }
1764 
1765 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1766                              uint64_t value, uint8_t counter)
1767 {
1768     if (counter < pmu_num_counters(env)) {
1769         pmevcntr_op_start(env, counter);
1770         env->cp15.c14_pmevcntr[counter] = value;
1771         pmevcntr_op_finish(env, counter);
1772     }
1773     /*
1774      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1775      * are CONSTRAINED UNPREDICTABLE.
1776      */
1777 }
1778 
1779 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1780                               uint8_t counter)
1781 {
1782     if (counter < pmu_num_counters(env)) {
1783         uint64_t ret;
1784         pmevcntr_op_start(env, counter);
1785         ret = env->cp15.c14_pmevcntr[counter];
1786         pmevcntr_op_finish(env, counter);
1787         return ret;
1788     } else {
1789       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1790        * are CONSTRAINED UNPREDICTABLE. */
1791         return 0;
1792     }
1793 }
1794 
1795 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1796                              uint64_t value)
1797 {
1798     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1799     pmevcntr_write(env, ri, value, counter);
1800 }
1801 
1802 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1803 {
1804     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1805     return pmevcntr_read(env, ri, counter);
1806 }
1807 
1808 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1809                              uint64_t value)
1810 {
1811     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1812     assert(counter < pmu_num_counters(env));
1813     env->cp15.c14_pmevcntr[counter] = value;
1814     pmevcntr_write(env, ri, value, counter);
1815 }
1816 
1817 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1818 {
1819     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1820     assert(counter < pmu_num_counters(env));
1821     return env->cp15.c14_pmevcntr[counter];
1822 }
1823 
1824 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1825                              uint64_t value)
1826 {
1827     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1828 }
1829 
1830 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1831 {
1832     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1833 }
1834 
1835 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1836                             uint64_t value)
1837 {
1838     if (arm_feature(env, ARM_FEATURE_V8)) {
1839         env->cp15.c9_pmuserenr = value & 0xf;
1840     } else {
1841         env->cp15.c9_pmuserenr = value & 1;
1842     }
1843 }
1844 
1845 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1846                              uint64_t value)
1847 {
1848     /* We have no event counters so only the C bit can be changed */
1849     value &= pmu_counter_mask(env);
1850     env->cp15.c9_pminten |= value;
1851     pmu_update_irq(env);
1852 }
1853 
1854 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1855                              uint64_t value)
1856 {
1857     value &= pmu_counter_mask(env);
1858     env->cp15.c9_pminten &= ~value;
1859     pmu_update_irq(env);
1860 }
1861 
1862 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1863                        uint64_t value)
1864 {
1865     /* Note that even though the AArch64 view of this register has bits
1866      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1867      * architectural requirements for bits which are RES0 only in some
1868      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1869      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1870      */
1871     raw_write(env, ri, value & ~0x1FULL);
1872 }
1873 
1874 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1875 {
1876     /* Begin with base v8.0 state.  */
1877     uint32_t valid_mask = 0x3fff;
1878     ARMCPU *cpu = env_archcpu(env);
1879 
1880     if (arm_el_is_aa64(env, 3)) {
1881         value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1882         valid_mask &= ~SCR_NET;
1883     } else {
1884         valid_mask &= ~(SCR_RW | SCR_ST);
1885     }
1886 
1887     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1888         valid_mask &= ~SCR_HCE;
1889 
1890         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1891          * supported if EL2 exists. The bit is UNK/SBZP when
1892          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1893          * when EL2 is unavailable.
1894          * On ARMv8, this bit is always available.
1895          */
1896         if (arm_feature(env, ARM_FEATURE_V7) &&
1897             !arm_feature(env, ARM_FEATURE_V8)) {
1898             valid_mask &= ~SCR_SMD;
1899         }
1900     }
1901     if (cpu_isar_feature(aa64_lor, cpu)) {
1902         valid_mask |= SCR_TLOR;
1903     }
1904     if (cpu_isar_feature(aa64_pauth, cpu)) {
1905         valid_mask |= SCR_API | SCR_APK;
1906     }
1907 
1908     /* Clear all-context RES0 bits.  */
1909     value &= valid_mask;
1910     raw_write(env, ri, value);
1911 }
1912 
1913 static CPAccessResult access_aa64_tid2(CPUARMState *env,
1914                                        const ARMCPRegInfo *ri,
1915                                        bool isread)
1916 {
1917     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
1918         return CP_ACCESS_TRAP_EL2;
1919     }
1920 
1921     return CP_ACCESS_OK;
1922 }
1923 
1924 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1925 {
1926     ARMCPU *cpu = env_archcpu(env);
1927 
1928     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1929      * bank
1930      */
1931     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1932                                         ri->secure & ARM_CP_SECSTATE_S);
1933 
1934     return cpu->ccsidr[index];
1935 }
1936 
1937 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1938                          uint64_t value)
1939 {
1940     raw_write(env, ri, value & 0xf);
1941 }
1942 
1943 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1944 {
1945     CPUState *cs = env_cpu(env);
1946     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
1947     uint64_t ret = 0;
1948     bool allow_virt = (arm_current_el(env) == 1 &&
1949                        (!arm_is_secure_below_el3(env) ||
1950                         (env->cp15.scr_el3 & SCR_EEL2)));
1951 
1952     if (allow_virt && (hcr_el2 & HCR_IMO)) {
1953         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1954             ret |= CPSR_I;
1955         }
1956     } else {
1957         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1958             ret |= CPSR_I;
1959         }
1960     }
1961 
1962     if (allow_virt && (hcr_el2 & HCR_FMO)) {
1963         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1964             ret |= CPSR_F;
1965         }
1966     } else {
1967         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1968             ret |= CPSR_F;
1969         }
1970     }
1971 
1972     /* External aborts are not possible in QEMU so A bit is always clear */
1973     return ret;
1974 }
1975 
1976 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1977                                        bool isread)
1978 {
1979     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
1980         return CP_ACCESS_TRAP_EL2;
1981     }
1982 
1983     return CP_ACCESS_OK;
1984 }
1985 
1986 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1987                                        bool isread)
1988 {
1989     if (arm_feature(env, ARM_FEATURE_V8)) {
1990         return access_aa64_tid1(env, ri, isread);
1991     }
1992 
1993     return CP_ACCESS_OK;
1994 }
1995 
1996 static const ARMCPRegInfo v7_cp_reginfo[] = {
1997     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1998     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1999       .access = PL1_W, .type = ARM_CP_NOP },
2000     /* Performance monitors are implementation defined in v7,
2001      * but with an ARM recommended set of registers, which we
2002      * follow.
2003      *
2004      * Performance registers fall into three categories:
2005      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
2006      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
2007      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
2008      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
2009      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
2010      */
2011     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
2012       .access = PL0_RW, .type = ARM_CP_ALIAS,
2013       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2014       .writefn = pmcntenset_write,
2015       .accessfn = pmreg_access,
2016       .raw_writefn = raw_write },
2017     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
2018       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
2019       .access = PL0_RW, .accessfn = pmreg_access,
2020       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
2021       .writefn = pmcntenset_write, .raw_writefn = raw_write },
2022     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
2023       .access = PL0_RW,
2024       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2025       .accessfn = pmreg_access,
2026       .writefn = pmcntenclr_write,
2027       .type = ARM_CP_ALIAS },
2028     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
2029       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
2030       .access = PL0_RW, .accessfn = pmreg_access,
2031       .type = ARM_CP_ALIAS,
2032       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
2033       .writefn = pmcntenclr_write },
2034     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2035       .access = PL0_RW, .type = ARM_CP_IO,
2036       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2037       .accessfn = pmreg_access,
2038       .writefn = pmovsr_write,
2039       .raw_writefn = raw_write },
2040     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2041       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2042       .access = PL0_RW, .accessfn = pmreg_access,
2043       .type = ARM_CP_ALIAS | ARM_CP_IO,
2044       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2045       .writefn = pmovsr_write,
2046       .raw_writefn = raw_write },
2047     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2048       .access = PL0_W, .accessfn = pmreg_access_swinc,
2049       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2050       .writefn = pmswinc_write },
2051     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2052       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2053       .access = PL0_W, .accessfn = pmreg_access_swinc,
2054       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2055       .writefn = pmswinc_write },
2056     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2057       .access = PL0_RW, .type = ARM_CP_ALIAS,
2058       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2059       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2060       .raw_writefn = raw_write},
2061     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2062       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2063       .access = PL0_RW, .accessfn = pmreg_access_selr,
2064       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2065       .writefn = pmselr_write, .raw_writefn = raw_write, },
2066     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2067       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2068       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2069       .accessfn = pmreg_access_ccntr },
2070     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2071       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2072       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2073       .type = ARM_CP_IO,
2074       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2075       .readfn = pmccntr_read, .writefn = pmccntr_write,
2076       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2077     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2078       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2079       .access = PL0_RW, .accessfn = pmreg_access,
2080       .type = ARM_CP_ALIAS | ARM_CP_IO,
2081       .resetvalue = 0, },
2082     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2083       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2084       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2085       .access = PL0_RW, .accessfn = pmreg_access,
2086       .type = ARM_CP_IO,
2087       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2088       .resetvalue = 0, },
2089     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2090       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2091       .accessfn = pmreg_access,
2092       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2093     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2094       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2095       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2096       .accessfn = pmreg_access,
2097       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2098     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2099       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2100       .accessfn = pmreg_access_xevcntr,
2101       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2102     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2103       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2104       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2105       .accessfn = pmreg_access_xevcntr,
2106       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2107     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2108       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2109       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2110       .resetvalue = 0,
2111       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2112     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2113       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2114       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2115       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2116       .resetvalue = 0,
2117       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2118     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2119       .access = PL1_RW, .accessfn = access_tpm,
2120       .type = ARM_CP_ALIAS | ARM_CP_IO,
2121       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2122       .resetvalue = 0,
2123       .writefn = pmintenset_write, .raw_writefn = raw_write },
2124     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2125       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2126       .access = PL1_RW, .accessfn = access_tpm,
2127       .type = ARM_CP_IO,
2128       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2129       .writefn = pmintenset_write, .raw_writefn = raw_write,
2130       .resetvalue = 0x0 },
2131     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2132       .access = PL1_RW, .accessfn = access_tpm,
2133       .type = ARM_CP_ALIAS | ARM_CP_IO,
2134       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2135       .writefn = pmintenclr_write, },
2136     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2137       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2138       .access = PL1_RW, .accessfn = access_tpm,
2139       .type = ARM_CP_ALIAS | ARM_CP_IO,
2140       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2141       .writefn = pmintenclr_write },
2142     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2143       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2144       .access = PL1_R,
2145       .accessfn = access_aa64_tid2,
2146       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2147     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2148       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2149       .access = PL1_RW,
2150       .accessfn = access_aa64_tid2,
2151       .writefn = csselr_write, .resetvalue = 0,
2152       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2153                              offsetof(CPUARMState, cp15.csselr_ns) } },
2154     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2155      * just RAZ for all cores:
2156      */
2157     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2158       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2159       .access = PL1_R, .type = ARM_CP_CONST,
2160       .accessfn = access_aa64_tid1,
2161       .resetvalue = 0 },
2162     /* Auxiliary fault status registers: these also are IMPDEF, and we
2163      * choose to RAZ/WI for all cores.
2164      */
2165     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2166       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2167       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2168     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2169       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2170       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2171     /* MAIR can just read-as-written because we don't implement caches
2172      * and so don't need to care about memory attributes.
2173      */
2174     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2175       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2176       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2177       .resetvalue = 0 },
2178     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2179       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2180       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2181       .resetvalue = 0 },
2182     /* For non-long-descriptor page tables these are PRRR and NMRR;
2183      * regardless they still act as reads-as-written for QEMU.
2184      */
2185      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2186       * allows them to assign the correct fieldoffset based on the endianness
2187       * handled in the field definitions.
2188       */
2189     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2190       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
2191       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2192                              offsetof(CPUARMState, cp15.mair0_ns) },
2193       .resetfn = arm_cp_reset_ignore },
2194     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2195       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
2196       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2197                              offsetof(CPUARMState, cp15.mair1_ns) },
2198       .resetfn = arm_cp_reset_ignore },
2199     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2200       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2201       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2202     /* 32 bit ITLB invalidates */
2203     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2204       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2205     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2206       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2207     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2208       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2209     /* 32 bit DTLB invalidates */
2210     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2211       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2212     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2213       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2214     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2215       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2216     /* 32 bit TLB invalidates */
2217     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2218       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2219     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2220       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2221     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2222       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2223     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2224       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
2225     REGINFO_SENTINEL
2226 };
2227 
2228 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2229     /* 32 bit TLB invalidates, Inner Shareable */
2230     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2231       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
2232     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2233       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
2234     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2235       .type = ARM_CP_NO_RAW, .access = PL1_W,
2236       .writefn = tlbiasid_is_write },
2237     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2238       .type = ARM_CP_NO_RAW, .access = PL1_W,
2239       .writefn = tlbimvaa_is_write },
2240     REGINFO_SENTINEL
2241 };
2242 
2243 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2244     /* PMOVSSET is not implemented in v7 before v7ve */
2245     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2246       .access = PL0_RW, .accessfn = pmreg_access,
2247       .type = ARM_CP_ALIAS | ARM_CP_IO,
2248       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2249       .writefn = pmovsset_write,
2250       .raw_writefn = raw_write },
2251     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2252       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2253       .access = PL0_RW, .accessfn = pmreg_access,
2254       .type = ARM_CP_ALIAS | ARM_CP_IO,
2255       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2256       .writefn = pmovsset_write,
2257       .raw_writefn = raw_write },
2258     REGINFO_SENTINEL
2259 };
2260 
2261 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2262                         uint64_t value)
2263 {
2264     value &= 1;
2265     env->teecr = value;
2266 }
2267 
2268 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2269                                     bool isread)
2270 {
2271     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2272         return CP_ACCESS_TRAP;
2273     }
2274     return CP_ACCESS_OK;
2275 }
2276 
2277 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2278     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2279       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2280       .resetvalue = 0,
2281       .writefn = teecr_write },
2282     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2283       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2284       .accessfn = teehbr_access, .resetvalue = 0 },
2285     REGINFO_SENTINEL
2286 };
2287 
2288 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2289     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2290       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2291       .access = PL0_RW,
2292       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2293     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2294       .access = PL0_RW,
2295       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2296                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2297       .resetfn = arm_cp_reset_ignore },
2298     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2299       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2300       .access = PL0_R|PL1_W,
2301       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2302       .resetvalue = 0},
2303     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2304       .access = PL0_R|PL1_W,
2305       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2306                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2307       .resetfn = arm_cp_reset_ignore },
2308     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2309       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2310       .access = PL1_RW,
2311       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2312     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2313       .access = PL1_RW,
2314       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2315                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2316       .resetvalue = 0 },
2317     REGINFO_SENTINEL
2318 };
2319 
2320 #ifndef CONFIG_USER_ONLY
2321 
2322 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2323                                        bool isread)
2324 {
2325     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2326      * Writable only at the highest implemented exception level.
2327      */
2328     int el = arm_current_el(env);
2329 
2330     switch (el) {
2331     case 0:
2332         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
2333             return CP_ACCESS_TRAP;
2334         }
2335         break;
2336     case 1:
2337         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2338             arm_is_secure_below_el3(env)) {
2339             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2340             return CP_ACCESS_TRAP_UNCATEGORIZED;
2341         }
2342         break;
2343     case 2:
2344     case 3:
2345         break;
2346     }
2347 
2348     if (!isread && el < arm_highest_el(env)) {
2349         return CP_ACCESS_TRAP_UNCATEGORIZED;
2350     }
2351 
2352     return CP_ACCESS_OK;
2353 }
2354 
2355 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2356                                         bool isread)
2357 {
2358     unsigned int cur_el = arm_current_el(env);
2359     bool secure = arm_is_secure(env);
2360 
2361     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
2362     if (cur_el == 0 &&
2363         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2364         return CP_ACCESS_TRAP;
2365     }
2366 
2367     if (arm_feature(env, ARM_FEATURE_EL2) &&
2368         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2369         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
2370         return CP_ACCESS_TRAP_EL2;
2371     }
2372     return CP_ACCESS_OK;
2373 }
2374 
2375 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2376                                       bool isread)
2377 {
2378     unsigned int cur_el = arm_current_el(env);
2379     bool secure = arm_is_secure(env);
2380 
2381     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
2382      * EL0[PV]TEN is zero.
2383      */
2384     if (cur_el == 0 &&
2385         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2386         return CP_ACCESS_TRAP;
2387     }
2388 
2389     if (arm_feature(env, ARM_FEATURE_EL2) &&
2390         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2391         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2392         return CP_ACCESS_TRAP_EL2;
2393     }
2394     return CP_ACCESS_OK;
2395 }
2396 
2397 static CPAccessResult gt_pct_access(CPUARMState *env,
2398                                     const ARMCPRegInfo *ri,
2399                                     bool isread)
2400 {
2401     return gt_counter_access(env, GTIMER_PHYS, isread);
2402 }
2403 
2404 static CPAccessResult gt_vct_access(CPUARMState *env,
2405                                     const ARMCPRegInfo *ri,
2406                                     bool isread)
2407 {
2408     return gt_counter_access(env, GTIMER_VIRT, isread);
2409 }
2410 
2411 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2412                                        bool isread)
2413 {
2414     return gt_timer_access(env, GTIMER_PHYS, isread);
2415 }
2416 
2417 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2418                                        bool isread)
2419 {
2420     return gt_timer_access(env, GTIMER_VIRT, isread);
2421 }
2422 
2423 static CPAccessResult gt_stimer_access(CPUARMState *env,
2424                                        const ARMCPRegInfo *ri,
2425                                        bool isread)
2426 {
2427     /* The AArch64 register view of the secure physical timer is
2428      * always accessible from EL3, and configurably accessible from
2429      * Secure EL1.
2430      */
2431     switch (arm_current_el(env)) {
2432     case 1:
2433         if (!arm_is_secure(env)) {
2434             return CP_ACCESS_TRAP;
2435         }
2436         if (!(env->cp15.scr_el3 & SCR_ST)) {
2437             return CP_ACCESS_TRAP_EL3;
2438         }
2439         return CP_ACCESS_OK;
2440     case 0:
2441     case 2:
2442         return CP_ACCESS_TRAP;
2443     case 3:
2444         return CP_ACCESS_OK;
2445     default:
2446         g_assert_not_reached();
2447     }
2448 }
2449 
2450 static uint64_t gt_get_countervalue(CPUARMState *env)
2451 {
2452     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
2453 }
2454 
2455 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2456 {
2457     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2458 
2459     if (gt->ctl & 1) {
2460         /* Timer enabled: calculate and set current ISTATUS, irq, and
2461          * reset timer to when ISTATUS next has to change
2462          */
2463         uint64_t offset = timeridx == GTIMER_VIRT ?
2464                                       cpu->env.cp15.cntvoff_el2 : 0;
2465         uint64_t count = gt_get_countervalue(&cpu->env);
2466         /* Note that this must be unsigned 64 bit arithmetic: */
2467         int istatus = count - offset >= gt->cval;
2468         uint64_t nexttick;
2469         int irqstate;
2470 
2471         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2472 
2473         irqstate = (istatus && !(gt->ctl & 2));
2474         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2475 
2476         if (istatus) {
2477             /* Next transition is when count rolls back over to zero */
2478             nexttick = UINT64_MAX;
2479         } else {
2480             /* Next transition is when we hit cval */
2481             nexttick = gt->cval + offset;
2482         }
2483         /* Note that the desired next expiry time might be beyond the
2484          * signed-64-bit range of a QEMUTimer -- in this case we just
2485          * set the timer for as far in the future as possible. When the
2486          * timer expires we will reset the timer for any remaining period.
2487          */
2488         if (nexttick > INT64_MAX / GTIMER_SCALE) {
2489             nexttick = INT64_MAX / GTIMER_SCALE;
2490         }
2491         timer_mod(cpu->gt_timer[timeridx], nexttick);
2492         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2493     } else {
2494         /* Timer disabled: ISTATUS and timer output always clear */
2495         gt->ctl &= ~4;
2496         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2497         timer_del(cpu->gt_timer[timeridx]);
2498         trace_arm_gt_recalc_disabled(timeridx);
2499     }
2500 }
2501 
2502 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2503                            int timeridx)
2504 {
2505     ARMCPU *cpu = env_archcpu(env);
2506 
2507     timer_del(cpu->gt_timer[timeridx]);
2508 }
2509 
2510 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2511 {
2512     return gt_get_countervalue(env);
2513 }
2514 
2515 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2516 {
2517     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
2518 }
2519 
2520 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2521                           int timeridx,
2522                           uint64_t value)
2523 {
2524     trace_arm_gt_cval_write(timeridx, value);
2525     env->cp15.c14_timer[timeridx].cval = value;
2526     gt_recalc_timer(env_archcpu(env), timeridx);
2527 }
2528 
2529 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2530                              int timeridx)
2531 {
2532     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2533 
2534     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2535                       (gt_get_countervalue(env) - offset));
2536 }
2537 
2538 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2539                           int timeridx,
2540                           uint64_t value)
2541 {
2542     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2543 
2544     trace_arm_gt_tval_write(timeridx, value);
2545     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2546                                          sextract64(value, 0, 32);
2547     gt_recalc_timer(env_archcpu(env), timeridx);
2548 }
2549 
2550 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2551                          int timeridx,
2552                          uint64_t value)
2553 {
2554     ARMCPU *cpu = env_archcpu(env);
2555     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2556 
2557     trace_arm_gt_ctl_write(timeridx, value);
2558     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2559     if ((oldval ^ value) & 1) {
2560         /* Enable toggled */
2561         gt_recalc_timer(cpu, timeridx);
2562     } else if ((oldval ^ value) & 2) {
2563         /* IMASK toggled: don't need to recalculate,
2564          * just set the interrupt line based on ISTATUS
2565          */
2566         int irqstate = (oldval & 4) && !(value & 2);
2567 
2568         trace_arm_gt_imask_toggle(timeridx, irqstate);
2569         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2570     }
2571 }
2572 
2573 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2574 {
2575     gt_timer_reset(env, ri, GTIMER_PHYS);
2576 }
2577 
2578 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2579                                uint64_t value)
2580 {
2581     gt_cval_write(env, ri, GTIMER_PHYS, value);
2582 }
2583 
2584 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2585 {
2586     return gt_tval_read(env, ri, GTIMER_PHYS);
2587 }
2588 
2589 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2590                                uint64_t value)
2591 {
2592     gt_tval_write(env, ri, GTIMER_PHYS, value);
2593 }
2594 
2595 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2596                               uint64_t value)
2597 {
2598     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2599 }
2600 
2601 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2602 {
2603     gt_timer_reset(env, ri, GTIMER_VIRT);
2604 }
2605 
2606 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2607                                uint64_t value)
2608 {
2609     gt_cval_write(env, ri, GTIMER_VIRT, value);
2610 }
2611 
2612 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2613 {
2614     return gt_tval_read(env, ri, GTIMER_VIRT);
2615 }
2616 
2617 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2618                                uint64_t value)
2619 {
2620     gt_tval_write(env, ri, GTIMER_VIRT, value);
2621 }
2622 
2623 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2624                               uint64_t value)
2625 {
2626     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2627 }
2628 
2629 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2630                               uint64_t value)
2631 {
2632     ARMCPU *cpu = env_archcpu(env);
2633 
2634     trace_arm_gt_cntvoff_write(value);
2635     raw_write(env, ri, value);
2636     gt_recalc_timer(cpu, GTIMER_VIRT);
2637 }
2638 
2639 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2640 {
2641     gt_timer_reset(env, ri, GTIMER_HYP);
2642 }
2643 
2644 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2645                               uint64_t value)
2646 {
2647     gt_cval_write(env, ri, GTIMER_HYP, value);
2648 }
2649 
2650 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2651 {
2652     return gt_tval_read(env, ri, GTIMER_HYP);
2653 }
2654 
2655 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2656                               uint64_t value)
2657 {
2658     gt_tval_write(env, ri, GTIMER_HYP, value);
2659 }
2660 
2661 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2662                               uint64_t value)
2663 {
2664     gt_ctl_write(env, ri, GTIMER_HYP, value);
2665 }
2666 
2667 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2668 {
2669     gt_timer_reset(env, ri, GTIMER_SEC);
2670 }
2671 
2672 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2673                               uint64_t value)
2674 {
2675     gt_cval_write(env, ri, GTIMER_SEC, value);
2676 }
2677 
2678 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2679 {
2680     return gt_tval_read(env, ri, GTIMER_SEC);
2681 }
2682 
2683 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2684                               uint64_t value)
2685 {
2686     gt_tval_write(env, ri, GTIMER_SEC, value);
2687 }
2688 
2689 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2690                               uint64_t value)
2691 {
2692     gt_ctl_write(env, ri, GTIMER_SEC, value);
2693 }
2694 
2695 void arm_gt_ptimer_cb(void *opaque)
2696 {
2697     ARMCPU *cpu = opaque;
2698 
2699     gt_recalc_timer(cpu, GTIMER_PHYS);
2700 }
2701 
2702 void arm_gt_vtimer_cb(void *opaque)
2703 {
2704     ARMCPU *cpu = opaque;
2705 
2706     gt_recalc_timer(cpu, GTIMER_VIRT);
2707 }
2708 
2709 void arm_gt_htimer_cb(void *opaque)
2710 {
2711     ARMCPU *cpu = opaque;
2712 
2713     gt_recalc_timer(cpu, GTIMER_HYP);
2714 }
2715 
2716 void arm_gt_stimer_cb(void *opaque)
2717 {
2718     ARMCPU *cpu = opaque;
2719 
2720     gt_recalc_timer(cpu, GTIMER_SEC);
2721 }
2722 
2723 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2724     /* Note that CNTFRQ is purely reads-as-written for the benefit
2725      * of software; writing it doesn't actually change the timer frequency.
2726      * Our reset value matches the fixed frequency we implement the timer at.
2727      */
2728     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2729       .type = ARM_CP_ALIAS,
2730       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2731       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2732     },
2733     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2734       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2735       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2736       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2737       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
2738     },
2739     /* overall control: mostly access permissions */
2740     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2741       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2742       .access = PL1_RW,
2743       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2744       .resetvalue = 0,
2745     },
2746     /* per-timer control */
2747     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2748       .secure = ARM_CP_SECSTATE_NS,
2749       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2750       .accessfn = gt_ptimer_access,
2751       .fieldoffset = offsetoflow32(CPUARMState,
2752                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2753       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2754     },
2755     { .name = "CNTP_CTL_S",
2756       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2757       .secure = ARM_CP_SECSTATE_S,
2758       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2759       .accessfn = gt_ptimer_access,
2760       .fieldoffset = offsetoflow32(CPUARMState,
2761                                    cp15.c14_timer[GTIMER_SEC].ctl),
2762       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2763     },
2764     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2765       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2766       .type = ARM_CP_IO, .access = PL0_RW,
2767       .accessfn = gt_ptimer_access,
2768       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2769       .resetvalue = 0,
2770       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2771     },
2772     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2773       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2774       .accessfn = gt_vtimer_access,
2775       .fieldoffset = offsetoflow32(CPUARMState,
2776                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2777       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2778     },
2779     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2780       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2781       .type = ARM_CP_IO, .access = PL0_RW,
2782       .accessfn = gt_vtimer_access,
2783       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2784       .resetvalue = 0,
2785       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2786     },
2787     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2788     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2789       .secure = ARM_CP_SECSTATE_NS,
2790       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2791       .accessfn = gt_ptimer_access,
2792       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2793     },
2794     { .name = "CNTP_TVAL_S",
2795       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2796       .secure = ARM_CP_SECSTATE_S,
2797       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2798       .accessfn = gt_ptimer_access,
2799       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2800     },
2801     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2802       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2803       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2804       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2805       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2806     },
2807     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2808       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2809       .accessfn = gt_vtimer_access,
2810       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2811     },
2812     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2813       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2814       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2815       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2816       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2817     },
2818     /* The counter itself */
2819     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2820       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2821       .accessfn = gt_pct_access,
2822       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2823     },
2824     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2825       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2826       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2827       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2828     },
2829     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2830       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2831       .accessfn = gt_vct_access,
2832       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2833     },
2834     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2835       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2836       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2837       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2838     },
2839     /* Comparison value, indicating when the timer goes off */
2840     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2841       .secure = ARM_CP_SECSTATE_NS,
2842       .access = PL0_RW,
2843       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2844       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2845       .accessfn = gt_ptimer_access,
2846       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2847     },
2848     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
2849       .secure = ARM_CP_SECSTATE_S,
2850       .access = PL0_RW,
2851       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2852       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2853       .accessfn = gt_ptimer_access,
2854       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2855     },
2856     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2857       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2858       .access = PL0_RW,
2859       .type = ARM_CP_IO,
2860       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2861       .resetvalue = 0, .accessfn = gt_ptimer_access,
2862       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2863     },
2864     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2865       .access = PL0_RW,
2866       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2867       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2868       .accessfn = gt_vtimer_access,
2869       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2870     },
2871     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2872       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2873       .access = PL0_RW,
2874       .type = ARM_CP_IO,
2875       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2876       .resetvalue = 0, .accessfn = gt_vtimer_access,
2877       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2878     },
2879     /* Secure timer -- this is actually restricted to only EL3
2880      * and configurably Secure-EL1 via the accessfn.
2881      */
2882     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2883       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2884       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2885       .accessfn = gt_stimer_access,
2886       .readfn = gt_sec_tval_read,
2887       .writefn = gt_sec_tval_write,
2888       .resetfn = gt_sec_timer_reset,
2889     },
2890     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2891       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2892       .type = ARM_CP_IO, .access = PL1_RW,
2893       .accessfn = gt_stimer_access,
2894       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2895       .resetvalue = 0,
2896       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2897     },
2898     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2899       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2900       .type = ARM_CP_IO, .access = PL1_RW,
2901       .accessfn = gt_stimer_access,
2902       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2903       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2904     },
2905     REGINFO_SENTINEL
2906 };
2907 
2908 #else
2909 
2910 /* In user-mode most of the generic timer registers are inaccessible
2911  * however modern kernels (4.12+) allow access to cntvct_el0
2912  */
2913 
2914 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2915 {
2916     /* Currently we have no support for QEMUTimer in linux-user so we
2917      * can't call gt_get_countervalue(env), instead we directly
2918      * call the lower level functions.
2919      */
2920     return cpu_get_clock() / GTIMER_SCALE;
2921 }
2922 
2923 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2924     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2925       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2926       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
2927       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2928       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
2929     },
2930     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2931       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2932       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2933       .readfn = gt_virt_cnt_read,
2934     },
2935     REGINFO_SENTINEL
2936 };
2937 
2938 #endif
2939 
2940 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2941 {
2942     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2943         raw_write(env, ri, value);
2944     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2945         raw_write(env, ri, value & 0xfffff6ff);
2946     } else {
2947         raw_write(env, ri, value & 0xfffff1ff);
2948     }
2949 }
2950 
2951 #ifndef CONFIG_USER_ONLY
2952 /* get_phys_addr() isn't present for user-mode-only targets */
2953 
2954 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2955                                  bool isread)
2956 {
2957     if (ri->opc2 & 4) {
2958         /* The ATS12NSO* operations must trap to EL3 if executed in
2959          * Secure EL1 (which can only happen if EL3 is AArch64).
2960          * They are simply UNDEF if executed from NS EL1.
2961          * They function normally from EL2 or EL3.
2962          */
2963         if (arm_current_el(env) == 1) {
2964             if (arm_is_secure_below_el3(env)) {
2965                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2966             }
2967             return CP_ACCESS_TRAP_UNCATEGORIZED;
2968         }
2969     }
2970     return CP_ACCESS_OK;
2971 }
2972 
2973 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2974                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2975 {
2976     hwaddr phys_addr;
2977     target_ulong page_size;
2978     int prot;
2979     bool ret;
2980     uint64_t par64;
2981     bool format64 = false;
2982     MemTxAttrs attrs = {};
2983     ARMMMUFaultInfo fi = {};
2984     ARMCacheAttrs cacheattrs = {};
2985 
2986     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2987                         &prot, &page_size, &fi, &cacheattrs);
2988 
2989     if (ret) {
2990         /*
2991          * Some kinds of translation fault must cause exceptions rather
2992          * than being reported in the PAR.
2993          */
2994         int current_el = arm_current_el(env);
2995         int target_el;
2996         uint32_t syn, fsr, fsc;
2997         bool take_exc = false;
2998 
2999         if (fi.s1ptw && current_el == 1 && !arm_is_secure(env)
3000             && (mmu_idx == ARMMMUIdx_S1NSE1 || mmu_idx == ARMMMUIdx_S1NSE0)) {
3001             /*
3002              * Synchronous stage 2 fault on an access made as part of the
3003              * translation table walk for AT S1E0* or AT S1E1* insn
3004              * executed from NS EL1. If this is a synchronous external abort
3005              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3006              * to EL3. Otherwise the fault is taken as an exception to EL2,
3007              * and HPFAR_EL2 holds the faulting IPA.
3008              */
3009             if (fi.type == ARMFault_SyncExternalOnWalk &&
3010                 (env->cp15.scr_el3 & SCR_EA)) {
3011                 target_el = 3;
3012             } else {
3013                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3014                 target_el = 2;
3015             }
3016             take_exc = true;
3017         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3018             /*
3019              * Synchronous external aborts during a translation table walk
3020              * are taken as Data Abort exceptions.
3021              */
3022             if (fi.stage2) {
3023                 if (current_el == 3) {
3024                     target_el = 3;
3025                 } else {
3026                     target_el = 2;
3027                 }
3028             } else {
3029                 target_el = exception_target_el(env);
3030             }
3031             take_exc = true;
3032         }
3033 
3034         if (take_exc) {
3035             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3036             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3037                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3038                 fsr = arm_fi_to_lfsc(&fi);
3039                 fsc = extract32(fsr, 0, 6);
3040             } else {
3041                 fsr = arm_fi_to_sfsc(&fi);
3042                 fsc = 0x3f;
3043             }
3044             /*
3045              * Report exception with ESR indicating a fault due to a
3046              * translation table walk for a cache maintenance instruction.
3047              */
3048             syn = syn_data_abort_no_iss(current_el == target_el,
3049                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3050             env->exception.vaddress = value;
3051             env->exception.fsr = fsr;
3052             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3053         }
3054     }
3055 
3056     if (is_a64(env)) {
3057         format64 = true;
3058     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3059         /*
3060          * ATS1Cxx:
3061          * * TTBCR.EAE determines whether the result is returned using the
3062          *   32-bit or the 64-bit PAR format
3063          * * Instructions executed in Hyp mode always use the 64bit format
3064          *
3065          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3066          * * The Non-secure TTBCR.EAE bit is set to 1
3067          * * The implementation includes EL2, and the value of HCR.VM is 1
3068          *
3069          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3070          *
3071          * ATS1Hx always uses the 64bit format.
3072          */
3073         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3074 
3075         if (arm_feature(env, ARM_FEATURE_EL2)) {
3076             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
3077                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3078             } else {
3079                 format64 |= arm_current_el(env) == 2;
3080             }
3081         }
3082     }
3083 
3084     if (format64) {
3085         /* Create a 64-bit PAR */
3086         par64 = (1 << 11); /* LPAE bit always set */
3087         if (!ret) {
3088             par64 |= phys_addr & ~0xfffULL;
3089             if (!attrs.secure) {
3090                 par64 |= (1 << 9); /* NS */
3091             }
3092             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3093             par64 |= cacheattrs.shareability << 7; /* SH */
3094         } else {
3095             uint32_t fsr = arm_fi_to_lfsc(&fi);
3096 
3097             par64 |= 1; /* F */
3098             par64 |= (fsr & 0x3f) << 1; /* FS */
3099             if (fi.stage2) {
3100                 par64 |= (1 << 9); /* S */
3101             }
3102             if (fi.s1ptw) {
3103                 par64 |= (1 << 8); /* PTW */
3104             }
3105         }
3106     } else {
3107         /* fsr is a DFSR/IFSR value for the short descriptor
3108          * translation table format (with WnR always clear).
3109          * Convert it to a 32-bit PAR.
3110          */
3111         if (!ret) {
3112             /* We do not set any attribute bits in the PAR */
3113             if (page_size == (1 << 24)
3114                 && arm_feature(env, ARM_FEATURE_V7)) {
3115                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3116             } else {
3117                 par64 = phys_addr & 0xfffff000;
3118             }
3119             if (!attrs.secure) {
3120                 par64 |= (1 << 9); /* NS */
3121             }
3122         } else {
3123             uint32_t fsr = arm_fi_to_sfsc(&fi);
3124 
3125             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3126                     ((fsr & 0xf) << 1) | 1;
3127         }
3128     }
3129     return par64;
3130 }
3131 
3132 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3133 {
3134     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3135     uint64_t par64;
3136     ARMMMUIdx mmu_idx;
3137     int el = arm_current_el(env);
3138     bool secure = arm_is_secure_below_el3(env);
3139 
3140     switch (ri->opc2 & 6) {
3141     case 0:
3142         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
3143         switch (el) {
3144         case 3:
3145             mmu_idx = ARMMMUIdx_S1E3;
3146             break;
3147         case 2:
3148             mmu_idx = ARMMMUIdx_S1NSE1;
3149             break;
3150         case 1:
3151             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3152             break;
3153         default:
3154             g_assert_not_reached();
3155         }
3156         break;
3157     case 2:
3158         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3159         switch (el) {
3160         case 3:
3161             mmu_idx = ARMMMUIdx_S1SE0;
3162             break;
3163         case 2:
3164             mmu_idx = ARMMMUIdx_S1NSE0;
3165             break;
3166         case 1:
3167             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3168             break;
3169         default:
3170             g_assert_not_reached();
3171         }
3172         break;
3173     case 4:
3174         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3175         mmu_idx = ARMMMUIdx_S12NSE1;
3176         break;
3177     case 6:
3178         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3179         mmu_idx = ARMMMUIdx_S12NSE0;
3180         break;
3181     default:
3182         g_assert_not_reached();
3183     }
3184 
3185     par64 = do_ats_write(env, value, access_type, mmu_idx);
3186 
3187     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3188 }
3189 
3190 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3191                         uint64_t value)
3192 {
3193     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3194     uint64_t par64;
3195 
3196     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S1E2);
3197 
3198     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3199 }
3200 
3201 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3202                                      bool isread)
3203 {
3204     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
3205         return CP_ACCESS_TRAP;
3206     }
3207     return CP_ACCESS_OK;
3208 }
3209 
3210 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3211                         uint64_t value)
3212 {
3213     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3214     ARMMMUIdx mmu_idx;
3215     int secure = arm_is_secure_below_el3(env);
3216 
3217     switch (ri->opc2 & 6) {
3218     case 0:
3219         switch (ri->opc1) {
3220         case 0: /* AT S1E1R, AT S1E1W */
3221             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3222             break;
3223         case 4: /* AT S1E2R, AT S1E2W */
3224             mmu_idx = ARMMMUIdx_S1E2;
3225             break;
3226         case 6: /* AT S1E3R, AT S1E3W */
3227             mmu_idx = ARMMMUIdx_S1E3;
3228             break;
3229         default:
3230             g_assert_not_reached();
3231         }
3232         break;
3233     case 2: /* AT S1E0R, AT S1E0W */
3234         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3235         break;
3236     case 4: /* AT S12E1R, AT S12E1W */
3237         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
3238         break;
3239     case 6: /* AT S12E0R, AT S12E0W */
3240         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
3241         break;
3242     default:
3243         g_assert_not_reached();
3244     }
3245 
3246     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3247 }
3248 #endif
3249 
3250 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3251     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3252       .access = PL1_RW, .resetvalue = 0,
3253       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3254                              offsetoflow32(CPUARMState, cp15.par_ns) },
3255       .writefn = par_write },
3256 #ifndef CONFIG_USER_ONLY
3257     /* This underdecoding is safe because the reginfo is NO_RAW. */
3258     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3259       .access = PL1_W, .accessfn = ats_access,
3260       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3261 #endif
3262     REGINFO_SENTINEL
3263 };
3264 
3265 /* Return basic MPU access permission bits.  */
3266 static uint32_t simple_mpu_ap_bits(uint32_t val)
3267 {
3268     uint32_t ret;
3269     uint32_t mask;
3270     int i;
3271     ret = 0;
3272     mask = 3;
3273     for (i = 0; i < 16; i += 2) {
3274         ret |= (val >> i) & mask;
3275         mask <<= 2;
3276     }
3277     return ret;
3278 }
3279 
3280 /* Pad basic MPU access permission bits to extended format.  */
3281 static uint32_t extended_mpu_ap_bits(uint32_t val)
3282 {
3283     uint32_t ret;
3284     uint32_t mask;
3285     int i;
3286     ret = 0;
3287     mask = 3;
3288     for (i = 0; i < 16; i += 2) {
3289         ret |= (val & mask) << i;
3290         mask <<= 2;
3291     }
3292     return ret;
3293 }
3294 
3295 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3296                                  uint64_t value)
3297 {
3298     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3299 }
3300 
3301 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3302 {
3303     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3304 }
3305 
3306 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3307                                  uint64_t value)
3308 {
3309     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3310 }
3311 
3312 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3313 {
3314     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3315 }
3316 
3317 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3318 {
3319     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3320 
3321     if (!u32p) {
3322         return 0;
3323     }
3324 
3325     u32p += env->pmsav7.rnr[M_REG_NS];
3326     return *u32p;
3327 }
3328 
3329 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3330                          uint64_t value)
3331 {
3332     ARMCPU *cpu = env_archcpu(env);
3333     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3334 
3335     if (!u32p) {
3336         return;
3337     }
3338 
3339     u32p += env->pmsav7.rnr[M_REG_NS];
3340     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3341     *u32p = value;
3342 }
3343 
3344 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3345                               uint64_t value)
3346 {
3347     ARMCPU *cpu = env_archcpu(env);
3348     uint32_t nrgs = cpu->pmsav7_dregion;
3349 
3350     if (value >= nrgs) {
3351         qemu_log_mask(LOG_GUEST_ERROR,
3352                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3353                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3354         return;
3355     }
3356 
3357     raw_write(env, ri, value);
3358 }
3359 
3360 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3361     /* Reset for all these registers is handled in arm_cpu_reset(),
3362      * because the PMSAv7 is also used by M-profile CPUs, which do
3363      * not register cpregs but still need the state to be reset.
3364      */
3365     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3366       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3367       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3368       .readfn = pmsav7_read, .writefn = pmsav7_write,
3369       .resetfn = arm_cp_reset_ignore },
3370     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3371       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3372       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3373       .readfn = pmsav7_read, .writefn = pmsav7_write,
3374       .resetfn = arm_cp_reset_ignore },
3375     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3376       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3377       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3378       .readfn = pmsav7_read, .writefn = pmsav7_write,
3379       .resetfn = arm_cp_reset_ignore },
3380     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3381       .access = PL1_RW,
3382       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3383       .writefn = pmsav7_rgnr_write,
3384       .resetfn = arm_cp_reset_ignore },
3385     REGINFO_SENTINEL
3386 };
3387 
3388 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3389     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3390       .access = PL1_RW, .type = ARM_CP_ALIAS,
3391       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3392       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3393     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3394       .access = PL1_RW, .type = ARM_CP_ALIAS,
3395       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3396       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3397     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3398       .access = PL1_RW,
3399       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3400       .resetvalue = 0, },
3401     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3402       .access = PL1_RW,
3403       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3404       .resetvalue = 0, },
3405     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3406       .access = PL1_RW,
3407       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3408     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3409       .access = PL1_RW,
3410       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3411     /* Protection region base and size registers */
3412     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3413       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3414       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3415     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3416       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3417       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3418     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3419       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3420       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3421     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3422       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3423       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3424     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3425       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3426       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3427     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3428       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3429       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3430     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3431       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3432       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3433     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3434       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3435       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3436     REGINFO_SENTINEL
3437 };
3438 
3439 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3440                                  uint64_t value)
3441 {
3442     TCR *tcr = raw_ptr(env, ri);
3443     int maskshift = extract32(value, 0, 3);
3444 
3445     if (!arm_feature(env, ARM_FEATURE_V8)) {
3446         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3447             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3448              * using Long-desciptor translation table format */
3449             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3450         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3451             /* In an implementation that includes the Security Extensions
3452              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3453              * Short-descriptor translation table format.
3454              */
3455             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3456         } else {
3457             value &= TTBCR_N;
3458         }
3459     }
3460 
3461     /* Update the masks corresponding to the TCR bank being written
3462      * Note that we always calculate mask and base_mask, but
3463      * they are only used for short-descriptor tables (ie if EAE is 0);
3464      * for long-descriptor tables the TCR fields are used differently
3465      * and the mask and base_mask values are meaningless.
3466      */
3467     tcr->raw_tcr = value;
3468     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3469     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3470 }
3471 
3472 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3473                              uint64_t value)
3474 {
3475     ARMCPU *cpu = env_archcpu(env);
3476     TCR *tcr = raw_ptr(env, ri);
3477 
3478     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3479         /* With LPAE the TTBCR could result in a change of ASID
3480          * via the TTBCR.A1 bit, so do a TLB flush.
3481          */
3482         tlb_flush(CPU(cpu));
3483     }
3484     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3485     value = deposit64(tcr->raw_tcr, 0, 32, value);
3486     vmsa_ttbcr_raw_write(env, ri, value);
3487 }
3488 
3489 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3490 {
3491     TCR *tcr = raw_ptr(env, ri);
3492 
3493     /* Reset both the TCR as well as the masks corresponding to the bank of
3494      * the TCR being reset.
3495      */
3496     tcr->raw_tcr = 0;
3497     tcr->mask = 0;
3498     tcr->base_mask = 0xffffc000u;
3499 }
3500 
3501 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3502                                uint64_t value)
3503 {
3504     ARMCPU *cpu = env_archcpu(env);
3505     TCR *tcr = raw_ptr(env, ri);
3506 
3507     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3508     tlb_flush(CPU(cpu));
3509     tcr->raw_tcr = value;
3510 }
3511 
3512 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3513                             uint64_t value)
3514 {
3515     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3516     if (cpreg_field_is_64bit(ri) &&
3517         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3518         ARMCPU *cpu = env_archcpu(env);
3519         tlb_flush(CPU(cpu));
3520     }
3521     raw_write(env, ri, value);
3522 }
3523 
3524 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3525                         uint64_t value)
3526 {
3527     ARMCPU *cpu = env_archcpu(env);
3528     CPUState *cs = CPU(cpu);
3529 
3530     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
3531     if (raw_read(env, ri) != value) {
3532         tlb_flush_by_mmuidx(cs,
3533                             ARMMMUIdxBit_S12NSE1 |
3534                             ARMMMUIdxBit_S12NSE0 |
3535                             ARMMMUIdxBit_S2NS);
3536         raw_write(env, ri, value);
3537     }
3538 }
3539 
3540 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3541     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3542       .access = PL1_RW, .type = ARM_CP_ALIAS,
3543       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3544                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3545     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3546       .access = PL1_RW, .resetvalue = 0,
3547       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3548                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3549     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3550       .access = PL1_RW, .resetvalue = 0,
3551       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3552                              offsetof(CPUARMState, cp15.dfar_ns) } },
3553     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3554       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3555       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3556       .resetvalue = 0, },
3557     REGINFO_SENTINEL
3558 };
3559 
3560 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3561     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3562       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3563       .access = PL1_RW,
3564       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3565     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3566       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3567       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3568       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3569                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3570     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3571       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3572       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3573       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3574                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3575     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3576       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3577       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
3578       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3579       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3580     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3581       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3582       .raw_writefn = vmsa_ttbcr_raw_write,
3583       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
3584                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
3585     REGINFO_SENTINEL
3586 };
3587 
3588 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3589  * qemu tlbs nor adjusting cached masks.
3590  */
3591 static const ARMCPRegInfo ttbcr2_reginfo = {
3592     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3593     .access = PL1_RW, .type = ARM_CP_ALIAS,
3594     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
3595                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
3596 };
3597 
3598 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3599                                 uint64_t value)
3600 {
3601     env->cp15.c15_ticonfig = value & 0xe7;
3602     /* The OS_TYPE bit in this register changes the reported CPUID! */
3603     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3604         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3605 }
3606 
3607 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3608                                 uint64_t value)
3609 {
3610     env->cp15.c15_threadid = value & 0xffff;
3611 }
3612 
3613 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3614                            uint64_t value)
3615 {
3616     /* Wait-for-interrupt (deprecated) */
3617     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
3618 }
3619 
3620 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3621                                   uint64_t value)
3622 {
3623     /* On OMAP there are registers indicating the max/min index of dcache lines
3624      * containing a dirty line; cache flush operations have to reset these.
3625      */
3626     env->cp15.c15_i_max = 0x000;
3627     env->cp15.c15_i_min = 0xff0;
3628 }
3629 
3630 static const ARMCPRegInfo omap_cp_reginfo[] = {
3631     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3632       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3633       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3634       .resetvalue = 0, },
3635     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3636       .access = PL1_RW, .type = ARM_CP_NOP },
3637     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3638       .access = PL1_RW,
3639       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3640       .writefn = omap_ticonfig_write },
3641     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3642       .access = PL1_RW,
3643       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3644     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3645       .access = PL1_RW, .resetvalue = 0xff0,
3646       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3647     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3648       .access = PL1_RW,
3649       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3650       .writefn = omap_threadid_write },
3651     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3652       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3653       .type = ARM_CP_NO_RAW,
3654       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3655     /* TODO: Peripheral port remap register:
3656      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3657      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3658      * when MMU is off.
3659      */
3660     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3661       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3662       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3663       .writefn = omap_cachemaint_write },
3664     { .name = "C9", .cp = 15, .crn = 9,
3665       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3666       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3667     REGINFO_SENTINEL
3668 };
3669 
3670 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3671                               uint64_t value)
3672 {
3673     env->cp15.c15_cpar = value & 0x3fff;
3674 }
3675 
3676 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3677     { .name = "XSCALE_CPAR",
3678       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3679       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3680       .writefn = xscale_cpar_write, },
3681     { .name = "XSCALE_AUXCR",
3682       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3683       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3684       .resetvalue = 0, },
3685     /* XScale specific cache-lockdown: since we have no cache we NOP these
3686      * and hope the guest does not really rely on cache behaviour.
3687      */
3688     { .name = "XSCALE_LOCK_ICACHE_LINE",
3689       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3690       .access = PL1_W, .type = ARM_CP_NOP },
3691     { .name = "XSCALE_UNLOCK_ICACHE",
3692       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3693       .access = PL1_W, .type = ARM_CP_NOP },
3694     { .name = "XSCALE_DCACHE_LOCK",
3695       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3696       .access = PL1_RW, .type = ARM_CP_NOP },
3697     { .name = "XSCALE_UNLOCK_DCACHE",
3698       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3699       .access = PL1_W, .type = ARM_CP_NOP },
3700     REGINFO_SENTINEL
3701 };
3702 
3703 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3704     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3705      * implementation of this implementation-defined space.
3706      * Ideally this should eventually disappear in favour of actually
3707      * implementing the correct behaviour for all cores.
3708      */
3709     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3710       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3711       .access = PL1_RW,
3712       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3713       .resetvalue = 0 },
3714     REGINFO_SENTINEL
3715 };
3716 
3717 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3718     /* Cache status: RAZ because we have no cache so it's always clean */
3719     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3720       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3721       .resetvalue = 0 },
3722     REGINFO_SENTINEL
3723 };
3724 
3725 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
3726     /* We never have a a block transfer operation in progress */
3727     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
3728       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3729       .resetvalue = 0 },
3730     /* The cache ops themselves: these all NOP for QEMU */
3731     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
3732       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3733     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
3734       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3735     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
3736       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3737     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
3738       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3739     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
3740       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3741     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
3742       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3743     REGINFO_SENTINEL
3744 };
3745 
3746 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
3747     /* The cache test-and-clean instructions always return (1 << 30)
3748      * to indicate that there are no dirty cache lines.
3749      */
3750     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
3751       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3752       .resetvalue = (1 << 30) },
3753     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
3754       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3755       .resetvalue = (1 << 30) },
3756     REGINFO_SENTINEL
3757 };
3758 
3759 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
3760     /* Ignore ReadBuffer accesses */
3761     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
3762       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3763       .access = PL1_RW, .resetvalue = 0,
3764       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
3765     REGINFO_SENTINEL
3766 };
3767 
3768 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3769 {
3770     ARMCPU *cpu = env_archcpu(env);
3771     unsigned int cur_el = arm_current_el(env);
3772     bool secure = arm_is_secure(env);
3773 
3774     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3775         return env->cp15.vpidr_el2;
3776     }
3777     return raw_read(env, ri);
3778 }
3779 
3780 static uint64_t mpidr_read_val(CPUARMState *env)
3781 {
3782     ARMCPU *cpu = env_archcpu(env);
3783     uint64_t mpidr = cpu->mp_affinity;
3784 
3785     if (arm_feature(env, ARM_FEATURE_V7MP)) {
3786         mpidr |= (1U << 31);
3787         /* Cores which are uniprocessor (non-coherent)
3788          * but still implement the MP extensions set
3789          * bit 30. (For instance, Cortex-R5).
3790          */
3791         if (cpu->mp_is_up) {
3792             mpidr |= (1u << 30);
3793         }
3794     }
3795     return mpidr;
3796 }
3797 
3798 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3799 {
3800     unsigned int cur_el = arm_current_el(env);
3801     bool secure = arm_is_secure(env);
3802 
3803     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3804         return env->cp15.vmpidr_el2;
3805     }
3806     return mpidr_read_val(env);
3807 }
3808 
3809 static const ARMCPRegInfo lpae_cp_reginfo[] = {
3810     /* NOP AMAIR0/1 */
3811     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
3812       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
3813       .access = PL1_RW, .type = ARM_CP_CONST,
3814       .resetvalue = 0 },
3815     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
3816     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
3817       .access = PL1_RW, .type = ARM_CP_CONST,
3818       .resetvalue = 0 },
3819     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
3820       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
3821       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
3822                              offsetof(CPUARMState, cp15.par_ns)} },
3823     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
3824       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3825       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3826                              offsetof(CPUARMState, cp15.ttbr0_ns) },
3827       .writefn = vmsa_ttbr_write, },
3828     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
3829       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3830       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3831                              offsetof(CPUARMState, cp15.ttbr1_ns) },
3832       .writefn = vmsa_ttbr_write, },
3833     REGINFO_SENTINEL
3834 };
3835 
3836 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3837 {
3838     return vfp_get_fpcr(env);
3839 }
3840 
3841 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3842                             uint64_t value)
3843 {
3844     vfp_set_fpcr(env, value);
3845 }
3846 
3847 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3848 {
3849     return vfp_get_fpsr(env);
3850 }
3851 
3852 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3853                             uint64_t value)
3854 {
3855     vfp_set_fpsr(env, value);
3856 }
3857 
3858 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
3859                                        bool isread)
3860 {
3861     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
3862         return CP_ACCESS_TRAP;
3863     }
3864     return CP_ACCESS_OK;
3865 }
3866 
3867 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3868                             uint64_t value)
3869 {
3870     env->daif = value & PSTATE_DAIF;
3871 }
3872 
3873 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3874                                           const ARMCPRegInfo *ri,
3875                                           bool isread)
3876 {
3877     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3878      * SCTLR_EL1.UCI is set.
3879      */
3880     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3881         return CP_ACCESS_TRAP;
3882     }
3883     return CP_ACCESS_OK;
3884 }
3885 
3886 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3887  * Page D4-1736 (DDI0487A.b)
3888  */
3889 
3890 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3891                                       uint64_t value)
3892 {
3893     CPUState *cs = env_cpu(env);
3894     bool sec = arm_is_secure_below_el3(env);
3895 
3896     if (sec) {
3897         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3898                                             ARMMMUIdxBit_S1SE1 |
3899                                             ARMMMUIdxBit_S1SE0);
3900     } else {
3901         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3902                                             ARMMMUIdxBit_S12NSE1 |
3903                                             ARMMMUIdxBit_S12NSE0);
3904     }
3905 }
3906 
3907 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3908                                     uint64_t value)
3909 {
3910     CPUState *cs = env_cpu(env);
3911 
3912     if (tlb_force_broadcast(env)) {
3913         tlbi_aa64_vmalle1is_write(env, NULL, value);
3914         return;
3915     }
3916 
3917     if (arm_is_secure_below_el3(env)) {
3918         tlb_flush_by_mmuidx(cs,
3919                             ARMMMUIdxBit_S1SE1 |
3920                             ARMMMUIdxBit_S1SE0);
3921     } else {
3922         tlb_flush_by_mmuidx(cs,
3923                             ARMMMUIdxBit_S12NSE1 |
3924                             ARMMMUIdxBit_S12NSE0);
3925     }
3926 }
3927 
3928 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3929                                   uint64_t value)
3930 {
3931     /* Note that the 'ALL' scope must invalidate both stage 1 and
3932      * stage 2 translations, whereas most other scopes only invalidate
3933      * stage 1 translations.
3934      */
3935     ARMCPU *cpu = env_archcpu(env);
3936     CPUState *cs = CPU(cpu);
3937 
3938     if (arm_is_secure_below_el3(env)) {
3939         tlb_flush_by_mmuidx(cs,
3940                             ARMMMUIdxBit_S1SE1 |
3941                             ARMMMUIdxBit_S1SE0);
3942     } else {
3943         if (arm_feature(env, ARM_FEATURE_EL2)) {
3944             tlb_flush_by_mmuidx(cs,
3945                                 ARMMMUIdxBit_S12NSE1 |
3946                                 ARMMMUIdxBit_S12NSE0 |
3947                                 ARMMMUIdxBit_S2NS);
3948         } else {
3949             tlb_flush_by_mmuidx(cs,
3950                                 ARMMMUIdxBit_S12NSE1 |
3951                                 ARMMMUIdxBit_S12NSE0);
3952         }
3953     }
3954 }
3955 
3956 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3957                                   uint64_t value)
3958 {
3959     ARMCPU *cpu = env_archcpu(env);
3960     CPUState *cs = CPU(cpu);
3961 
3962     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3963 }
3964 
3965 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3966                                   uint64_t value)
3967 {
3968     ARMCPU *cpu = env_archcpu(env);
3969     CPUState *cs = CPU(cpu);
3970 
3971     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3972 }
3973 
3974 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3975                                     uint64_t value)
3976 {
3977     /* Note that the 'ALL' scope must invalidate both stage 1 and
3978      * stage 2 translations, whereas most other scopes only invalidate
3979      * stage 1 translations.
3980      */
3981     CPUState *cs = env_cpu(env);
3982     bool sec = arm_is_secure_below_el3(env);
3983     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3984 
3985     if (sec) {
3986         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3987                                             ARMMMUIdxBit_S1SE1 |
3988                                             ARMMMUIdxBit_S1SE0);
3989     } else if (has_el2) {
3990         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3991                                             ARMMMUIdxBit_S12NSE1 |
3992                                             ARMMMUIdxBit_S12NSE0 |
3993                                             ARMMMUIdxBit_S2NS);
3994     } else {
3995           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3996                                               ARMMMUIdxBit_S12NSE1 |
3997                                               ARMMMUIdxBit_S12NSE0);
3998     }
3999 }
4000 
4001 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4002                                     uint64_t value)
4003 {
4004     CPUState *cs = env_cpu(env);
4005 
4006     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
4007 }
4008 
4009 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4010                                     uint64_t value)
4011 {
4012     CPUState *cs = env_cpu(env);
4013 
4014     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
4015 }
4016 
4017 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4018                                  uint64_t value)
4019 {
4020     /* Invalidate by VA, EL2
4021      * Currently handles both VAE2 and VALE2, since we don't support
4022      * flush-last-level-only.
4023      */
4024     ARMCPU *cpu = env_archcpu(env);
4025     CPUState *cs = CPU(cpu);
4026     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4027 
4028     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
4029 }
4030 
4031 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4032                                  uint64_t value)
4033 {
4034     /* Invalidate by VA, EL3
4035      * Currently handles both VAE3 and VALE3, since we don't support
4036      * flush-last-level-only.
4037      */
4038     ARMCPU *cpu = env_archcpu(env);
4039     CPUState *cs = CPU(cpu);
4040     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4041 
4042     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
4043 }
4044 
4045 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4046                                    uint64_t value)
4047 {
4048     ARMCPU *cpu = env_archcpu(env);
4049     CPUState *cs = CPU(cpu);
4050     bool sec = arm_is_secure_below_el3(env);
4051     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4052 
4053     if (sec) {
4054         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4055                                                  ARMMMUIdxBit_S1SE1 |
4056                                                  ARMMMUIdxBit_S1SE0);
4057     } else {
4058         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4059                                                  ARMMMUIdxBit_S12NSE1 |
4060                                                  ARMMMUIdxBit_S12NSE0);
4061     }
4062 }
4063 
4064 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4065                                  uint64_t value)
4066 {
4067     /* Invalidate by VA, EL1&0 (AArch64 version).
4068      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4069      * since we don't support flush-for-specific-ASID-only or
4070      * flush-last-level-only.
4071      */
4072     ARMCPU *cpu = env_archcpu(env);
4073     CPUState *cs = CPU(cpu);
4074     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4075 
4076     if (tlb_force_broadcast(env)) {
4077         tlbi_aa64_vae1is_write(env, NULL, value);
4078         return;
4079     }
4080 
4081     if (arm_is_secure_below_el3(env)) {
4082         tlb_flush_page_by_mmuidx(cs, pageaddr,
4083                                  ARMMMUIdxBit_S1SE1 |
4084                                  ARMMMUIdxBit_S1SE0);
4085     } else {
4086         tlb_flush_page_by_mmuidx(cs, pageaddr,
4087                                  ARMMMUIdxBit_S12NSE1 |
4088                                  ARMMMUIdxBit_S12NSE0);
4089     }
4090 }
4091 
4092 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4093                                    uint64_t value)
4094 {
4095     CPUState *cs = env_cpu(env);
4096     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4097 
4098     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4099                                              ARMMMUIdxBit_S1E2);
4100 }
4101 
4102 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4103                                    uint64_t value)
4104 {
4105     CPUState *cs = env_cpu(env);
4106     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4107 
4108     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4109                                              ARMMMUIdxBit_S1E3);
4110 }
4111 
4112 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4113                                     uint64_t value)
4114 {
4115     /* Invalidate by IPA. This has to invalidate any structures that
4116      * contain only stage 2 translation information, but does not need
4117      * to apply to structures that contain combined stage 1 and stage 2
4118      * translation information.
4119      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
4120      */
4121     ARMCPU *cpu = env_archcpu(env);
4122     CPUState *cs = CPU(cpu);
4123     uint64_t pageaddr;
4124 
4125     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4126         return;
4127     }
4128 
4129     pageaddr = sextract64(value << 12, 0, 48);
4130 
4131     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
4132 }
4133 
4134 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4135                                       uint64_t value)
4136 {
4137     CPUState *cs = env_cpu(env);
4138     uint64_t pageaddr;
4139 
4140     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4141         return;
4142     }
4143 
4144     pageaddr = sextract64(value << 12, 0, 48);
4145 
4146     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4147                                              ARMMMUIdxBit_S2NS);
4148 }
4149 
4150 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4151                                       bool isread)
4152 {
4153     /* We don't implement EL2, so the only control on DC ZVA is the
4154      * bit in the SCTLR which can prohibit access for EL0.
4155      */
4156     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4157         return CP_ACCESS_TRAP;
4158     }
4159     return CP_ACCESS_OK;
4160 }
4161 
4162 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4163 {
4164     ARMCPU *cpu = env_archcpu(env);
4165     int dzp_bit = 1 << 4;
4166 
4167     /* DZP indicates whether DC ZVA access is allowed */
4168     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4169         dzp_bit = 0;
4170     }
4171     return cpu->dcz_blocksize | dzp_bit;
4172 }
4173 
4174 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4175                                     bool isread)
4176 {
4177     if (!(env->pstate & PSTATE_SP)) {
4178         /* Access to SP_EL0 is undefined if it's being used as
4179          * the stack pointer.
4180          */
4181         return CP_ACCESS_TRAP_UNCATEGORIZED;
4182     }
4183     return CP_ACCESS_OK;
4184 }
4185 
4186 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4187 {
4188     return env->pstate & PSTATE_SP;
4189 }
4190 
4191 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4192 {
4193     update_spsel(env, val);
4194 }
4195 
4196 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4197                         uint64_t value)
4198 {
4199     ARMCPU *cpu = env_archcpu(env);
4200 
4201     if (raw_read(env, ri) == value) {
4202         /* Skip the TLB flush if nothing actually changed; Linux likes
4203          * to do a lot of pointless SCTLR writes.
4204          */
4205         return;
4206     }
4207 
4208     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4209         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4210         value &= ~SCTLR_M;
4211     }
4212 
4213     raw_write(env, ri, value);
4214     /* ??? Lots of these bits are not implemented.  */
4215     /* This may enable/disable the MMU, so do a TLB flush.  */
4216     tlb_flush(CPU(cpu));
4217 
4218     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4219         /*
4220          * Normally we would always end the TB on an SCTLR write; see the
4221          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4222          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4223          * of hflags from the translator, so do it here.
4224          */
4225         arm_rebuild_hflags(env);
4226     }
4227 }
4228 
4229 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4230                                      bool isread)
4231 {
4232     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4233         return CP_ACCESS_TRAP_FP_EL2;
4234     }
4235     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4236         return CP_ACCESS_TRAP_FP_EL3;
4237     }
4238     return CP_ACCESS_OK;
4239 }
4240 
4241 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4242                        uint64_t value)
4243 {
4244     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4245 }
4246 
4247 static const ARMCPRegInfo v8_cp_reginfo[] = {
4248     /* Minimal set of EL0-visible registers. This will need to be expanded
4249      * significantly for system emulation of AArch64 CPUs.
4250      */
4251     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4252       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4253       .access = PL0_RW, .type = ARM_CP_NZCV },
4254     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4255       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4256       .type = ARM_CP_NO_RAW,
4257       .access = PL0_RW, .accessfn = aa64_daif_access,
4258       .fieldoffset = offsetof(CPUARMState, daif),
4259       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4260     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4261       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4262       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4263       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4264     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4265       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4266       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4267       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4268     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4269       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4270       .access = PL0_R, .type = ARM_CP_NO_RAW,
4271       .readfn = aa64_dczid_read },
4272     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4273       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4274       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4275 #ifndef CONFIG_USER_ONLY
4276       /* Avoid overhead of an access check that always passes in user-mode */
4277       .accessfn = aa64_zva_access,
4278 #endif
4279     },
4280     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4281       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4282       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4283     /* Cache ops: all NOPs since we don't emulate caches */
4284     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4285       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4286       .access = PL1_W, .type = ARM_CP_NOP },
4287     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4288       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4289       .access = PL1_W, .type = ARM_CP_NOP },
4290     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4291       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4292       .access = PL0_W, .type = ARM_CP_NOP,
4293       .accessfn = aa64_cacheop_access },
4294     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4295       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4296       .access = PL1_W, .type = ARM_CP_NOP },
4297     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4298       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4299       .access = PL1_W, .type = ARM_CP_NOP },
4300     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4301       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4302       .access = PL0_W, .type = ARM_CP_NOP,
4303       .accessfn = aa64_cacheop_access },
4304     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4305       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4306       .access = PL1_W, .type = ARM_CP_NOP },
4307     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4308       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4309       .access = PL0_W, .type = ARM_CP_NOP,
4310       .accessfn = aa64_cacheop_access },
4311     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4312       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4313       .access = PL0_W, .type = ARM_CP_NOP,
4314       .accessfn = aa64_cacheop_access },
4315     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4316       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4317       .access = PL1_W, .type = ARM_CP_NOP },
4318     /* TLBI operations */
4319     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4320       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4321       .access = PL1_W, .type = ARM_CP_NO_RAW,
4322       .writefn = tlbi_aa64_vmalle1is_write },
4323     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4324       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4325       .access = PL1_W, .type = ARM_CP_NO_RAW,
4326       .writefn = tlbi_aa64_vae1is_write },
4327     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4328       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4329       .access = PL1_W, .type = ARM_CP_NO_RAW,
4330       .writefn = tlbi_aa64_vmalle1is_write },
4331     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4332       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4333       .access = PL1_W, .type = ARM_CP_NO_RAW,
4334       .writefn = tlbi_aa64_vae1is_write },
4335     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4336       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4337       .access = PL1_W, .type = ARM_CP_NO_RAW,
4338       .writefn = tlbi_aa64_vae1is_write },
4339     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4340       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4341       .access = PL1_W, .type = ARM_CP_NO_RAW,
4342       .writefn = tlbi_aa64_vae1is_write },
4343     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4344       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4345       .access = PL1_W, .type = ARM_CP_NO_RAW,
4346       .writefn = tlbi_aa64_vmalle1_write },
4347     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4348       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4349       .access = PL1_W, .type = ARM_CP_NO_RAW,
4350       .writefn = tlbi_aa64_vae1_write },
4351     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4352       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4353       .access = PL1_W, .type = ARM_CP_NO_RAW,
4354       .writefn = tlbi_aa64_vmalle1_write },
4355     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4356       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4357       .access = PL1_W, .type = ARM_CP_NO_RAW,
4358       .writefn = tlbi_aa64_vae1_write },
4359     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4360       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4361       .access = PL1_W, .type = ARM_CP_NO_RAW,
4362       .writefn = tlbi_aa64_vae1_write },
4363     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4364       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4365       .access = PL1_W, .type = ARM_CP_NO_RAW,
4366       .writefn = tlbi_aa64_vae1_write },
4367     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4368       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4369       .access = PL2_W, .type = ARM_CP_NO_RAW,
4370       .writefn = tlbi_aa64_ipas2e1is_write },
4371     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4372       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4373       .access = PL2_W, .type = ARM_CP_NO_RAW,
4374       .writefn = tlbi_aa64_ipas2e1is_write },
4375     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4376       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4377       .access = PL2_W, .type = ARM_CP_NO_RAW,
4378       .writefn = tlbi_aa64_alle1is_write },
4379     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4380       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4381       .access = PL2_W, .type = ARM_CP_NO_RAW,
4382       .writefn = tlbi_aa64_alle1is_write },
4383     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4384       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4385       .access = PL2_W, .type = ARM_CP_NO_RAW,
4386       .writefn = tlbi_aa64_ipas2e1_write },
4387     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4388       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4389       .access = PL2_W, .type = ARM_CP_NO_RAW,
4390       .writefn = tlbi_aa64_ipas2e1_write },
4391     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4392       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4393       .access = PL2_W, .type = ARM_CP_NO_RAW,
4394       .writefn = tlbi_aa64_alle1_write },
4395     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4396       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4397       .access = PL2_W, .type = ARM_CP_NO_RAW,
4398       .writefn = tlbi_aa64_alle1is_write },
4399 #ifndef CONFIG_USER_ONLY
4400     /* 64 bit address translation operations */
4401     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4402       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4403       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4404       .writefn = ats_write64 },
4405     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4406       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4407       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4408       .writefn = ats_write64 },
4409     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4410       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4411       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4412       .writefn = ats_write64 },
4413     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4414       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4415       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4416       .writefn = ats_write64 },
4417     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4418       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4419       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4420       .writefn = ats_write64 },
4421     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4422       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4423       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4424       .writefn = ats_write64 },
4425     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4426       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4427       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4428       .writefn = ats_write64 },
4429     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4430       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4431       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4432       .writefn = ats_write64 },
4433     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4434     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4435       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4436       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4437       .writefn = ats_write64 },
4438     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4439       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4440       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4441       .writefn = ats_write64 },
4442     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4443       .type = ARM_CP_ALIAS,
4444       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4445       .access = PL1_RW, .resetvalue = 0,
4446       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4447       .writefn = par_write },
4448 #endif
4449     /* TLB invalidate last level of translation table walk */
4450     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4451       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
4452     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4453       .type = ARM_CP_NO_RAW, .access = PL1_W,
4454       .writefn = tlbimvaa_is_write },
4455     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4456       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
4457     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4458       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
4459     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4460       .type = ARM_CP_NO_RAW, .access = PL2_W,
4461       .writefn = tlbimva_hyp_write },
4462     { .name = "TLBIMVALHIS",
4463       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4464       .type = ARM_CP_NO_RAW, .access = PL2_W,
4465       .writefn = tlbimva_hyp_is_write },
4466     { .name = "TLBIIPAS2",
4467       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4468       .type = ARM_CP_NO_RAW, .access = PL2_W,
4469       .writefn = tlbiipas2_write },
4470     { .name = "TLBIIPAS2IS",
4471       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4472       .type = ARM_CP_NO_RAW, .access = PL2_W,
4473       .writefn = tlbiipas2_is_write },
4474     { .name = "TLBIIPAS2L",
4475       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4476       .type = ARM_CP_NO_RAW, .access = PL2_W,
4477       .writefn = tlbiipas2_write },
4478     { .name = "TLBIIPAS2LIS",
4479       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4480       .type = ARM_CP_NO_RAW, .access = PL2_W,
4481       .writefn = tlbiipas2_is_write },
4482     /* 32 bit cache operations */
4483     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4484       .type = ARM_CP_NOP, .access = PL1_W },
4485     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
4486       .type = ARM_CP_NOP, .access = PL1_W },
4487     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4488       .type = ARM_CP_NOP, .access = PL1_W },
4489     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
4490       .type = ARM_CP_NOP, .access = PL1_W },
4491     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
4492       .type = ARM_CP_NOP, .access = PL1_W },
4493     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
4494       .type = ARM_CP_NOP, .access = PL1_W },
4495     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4496       .type = ARM_CP_NOP, .access = PL1_W },
4497     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4498       .type = ARM_CP_NOP, .access = PL1_W },
4499     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
4500       .type = ARM_CP_NOP, .access = PL1_W },
4501     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4502       .type = ARM_CP_NOP, .access = PL1_W },
4503     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
4504       .type = ARM_CP_NOP, .access = PL1_W },
4505     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
4506       .type = ARM_CP_NOP, .access = PL1_W },
4507     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4508       .type = ARM_CP_NOP, .access = PL1_W },
4509     /* MMU Domain access control / MPU write buffer control */
4510     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
4511       .access = PL1_RW, .resetvalue = 0,
4512       .writefn = dacr_write, .raw_writefn = raw_write,
4513       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
4514                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
4515     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
4516       .type = ARM_CP_ALIAS,
4517       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
4518       .access = PL1_RW,
4519       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
4520     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
4521       .type = ARM_CP_ALIAS,
4522       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
4523       .access = PL1_RW,
4524       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
4525     /* We rely on the access checks not allowing the guest to write to the
4526      * state field when SPSel indicates that it's being used as the stack
4527      * pointer.
4528      */
4529     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
4530       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
4531       .access = PL1_RW, .accessfn = sp_el0_access,
4532       .type = ARM_CP_ALIAS,
4533       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
4534     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
4535       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
4536       .access = PL2_RW, .type = ARM_CP_ALIAS,
4537       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
4538     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
4539       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
4540       .type = ARM_CP_NO_RAW,
4541       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
4542     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
4543       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
4544       .type = ARM_CP_ALIAS,
4545       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
4546       .access = PL2_RW, .accessfn = fpexc32_access },
4547     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
4548       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
4549       .access = PL2_RW, .resetvalue = 0,
4550       .writefn = dacr_write, .raw_writefn = raw_write,
4551       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
4552     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
4553       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
4554       .access = PL2_RW, .resetvalue = 0,
4555       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
4556     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
4557       .type = ARM_CP_ALIAS,
4558       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
4559       .access = PL2_RW,
4560       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
4561     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
4562       .type = ARM_CP_ALIAS,
4563       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
4564       .access = PL2_RW,
4565       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
4566     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
4567       .type = ARM_CP_ALIAS,
4568       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
4569       .access = PL2_RW,
4570       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
4571     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
4572       .type = ARM_CP_ALIAS,
4573       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
4574       .access = PL2_RW,
4575       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
4576     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
4577       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
4578       .resetvalue = 0,
4579       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
4580     { .name = "SDCR", .type = ARM_CP_ALIAS,
4581       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
4582       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4583       .writefn = sdcr_write,
4584       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
4585     REGINFO_SENTINEL
4586 };
4587 
4588 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
4589 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
4590     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4591       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4592       .access = PL2_RW,
4593       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
4594     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
4595       .type = ARM_CP_NO_RAW,
4596       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4597       .access = PL2_RW,
4598       .type = ARM_CP_CONST, .resetvalue = 0 },
4599     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4600       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4601       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4602     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4603       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4604       .access = PL2_RW,
4605       .type = ARM_CP_CONST, .resetvalue = 0 },
4606     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4607       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4608       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4609     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4610       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4611       .access = PL2_RW, .type = ARM_CP_CONST,
4612       .resetvalue = 0 },
4613     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4614       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4615       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4616     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4617       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4618       .access = PL2_RW, .type = ARM_CP_CONST,
4619       .resetvalue = 0 },
4620     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4621       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4622       .access = PL2_RW, .type = ARM_CP_CONST,
4623       .resetvalue = 0 },
4624     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4625       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4626       .access = PL2_RW, .type = ARM_CP_CONST,
4627       .resetvalue = 0 },
4628     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4629       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4630       .access = PL2_RW, .type = ARM_CP_CONST,
4631       .resetvalue = 0 },
4632     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4633       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4634       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4635     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
4636       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4637       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4638       .type = ARM_CP_CONST, .resetvalue = 0 },
4639     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4640       .cp = 15, .opc1 = 6, .crm = 2,
4641       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4642       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
4643     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4644       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4645       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4646     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4647       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4648       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4649     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4650       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4651       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4652     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4653       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4654       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4655     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4656       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4657       .resetvalue = 0 },
4658     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4659       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4660       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4661     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4662       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4663       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4664     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4665       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4666       .resetvalue = 0 },
4667     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4668       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4669       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4670     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4671       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4672       .resetvalue = 0 },
4673     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4674       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4675       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4676     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4677       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4678       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4679     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4680       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4681       .access = PL2_RW, .accessfn = access_tda,
4682       .type = ARM_CP_CONST, .resetvalue = 0 },
4683     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
4684       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4685       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4686       .type = ARM_CP_CONST, .resetvalue = 0 },
4687     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4688       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4689       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4690     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4691       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4692       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4693     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4694       .type = ARM_CP_CONST,
4695       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4696       .access = PL2_RW, .resetvalue = 0 },
4697     REGINFO_SENTINEL
4698 };
4699 
4700 /* Ditto, but for registers which exist in ARMv8 but not v7 */
4701 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
4702     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4703       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4704       .access = PL2_RW,
4705       .type = ARM_CP_CONST, .resetvalue = 0 },
4706     REGINFO_SENTINEL
4707 };
4708 
4709 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
4710 {
4711     ARMCPU *cpu = env_archcpu(env);
4712     uint64_t valid_mask = HCR_MASK;
4713 
4714     if (arm_feature(env, ARM_FEATURE_EL3)) {
4715         valid_mask &= ~HCR_HCD;
4716     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
4717         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
4718          * However, if we're using the SMC PSCI conduit then QEMU is
4719          * effectively acting like EL3 firmware and so the guest at
4720          * EL2 should retain the ability to prevent EL1 from being
4721          * able to make SMC calls into the ersatz firmware, so in
4722          * that case HCR.TSC should be read/write.
4723          */
4724         valid_mask &= ~HCR_TSC;
4725     }
4726     if (cpu_isar_feature(aa64_lor, cpu)) {
4727         valid_mask |= HCR_TLOR;
4728     }
4729     if (cpu_isar_feature(aa64_pauth, cpu)) {
4730         valid_mask |= HCR_API | HCR_APK;
4731     }
4732 
4733     /* Clear RES0 bits.  */
4734     value &= valid_mask;
4735 
4736     /* These bits change the MMU setup:
4737      * HCR_VM enables stage 2 translation
4738      * HCR_PTW forbids certain page-table setups
4739      * HCR_DC Disables stage1 and enables stage2 translation
4740      */
4741     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
4742         tlb_flush(CPU(cpu));
4743     }
4744     env->cp15.hcr_el2 = value;
4745 
4746     /*
4747      * Updates to VI and VF require us to update the status of
4748      * virtual interrupts, which are the logical OR of these bits
4749      * and the state of the input lines from the GIC. (This requires
4750      * that we have the iothread lock, which is done by marking the
4751      * reginfo structs as ARM_CP_IO.)
4752      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
4753      * possible for it to be taken immediately, because VIRQ and
4754      * VFIQ are masked unless running at EL0 or EL1, and HCR
4755      * can only be written at EL2.
4756      */
4757     g_assert(qemu_mutex_iothread_locked());
4758     arm_cpu_update_virq(cpu);
4759     arm_cpu_update_vfiq(cpu);
4760 }
4761 
4762 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
4763                           uint64_t value)
4764 {
4765     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
4766     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
4767     hcr_write(env, NULL, value);
4768 }
4769 
4770 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
4771                          uint64_t value)
4772 {
4773     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
4774     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
4775     hcr_write(env, NULL, value);
4776 }
4777 
4778 /*
4779  * Return the effective value of HCR_EL2.
4780  * Bits that are not included here:
4781  * RW       (read from SCR_EL3.RW as needed)
4782  */
4783 uint64_t arm_hcr_el2_eff(CPUARMState *env)
4784 {
4785     uint64_t ret = env->cp15.hcr_el2;
4786 
4787     if (arm_is_secure_below_el3(env)) {
4788         /*
4789          * "This register has no effect if EL2 is not enabled in the
4790          * current Security state".  This is ARMv8.4-SecEL2 speak for
4791          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
4792          *
4793          * Prior to that, the language was "In an implementation that
4794          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
4795          * as if this field is 0 for all purposes other than a direct
4796          * read or write access of HCR_EL2".  With lots of enumeration
4797          * on a per-field basis.  In current QEMU, this is condition
4798          * is arm_is_secure_below_el3.
4799          *
4800          * Since the v8.4 language applies to the entire register, and
4801          * appears to be backward compatible, use that.
4802          */
4803         ret = 0;
4804     } else if (ret & HCR_TGE) {
4805         /* These bits are up-to-date as of ARMv8.4.  */
4806         if (ret & HCR_E2H) {
4807             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
4808                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
4809                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
4810                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE);
4811         } else {
4812             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
4813         }
4814         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
4815                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
4816                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
4817                  HCR_TLOR);
4818     }
4819 
4820     return ret;
4821 }
4822 
4823 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4824                            uint64_t value)
4825 {
4826     /*
4827      * For A-profile AArch32 EL3, if NSACR.CP10
4828      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
4829      */
4830     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
4831         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
4832         value &= ~(0x3 << 10);
4833         value |= env->cp15.cptr_el[2] & (0x3 << 10);
4834     }
4835     env->cp15.cptr_el[2] = value;
4836 }
4837 
4838 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
4839 {
4840     /*
4841      * For A-profile AArch32 EL3, if NSACR.CP10
4842      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
4843      */
4844     uint64_t value = env->cp15.cptr_el[2];
4845 
4846     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
4847         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
4848         value |= 0x3 << 10;
4849     }
4850     return value;
4851 }
4852 
4853 static const ARMCPRegInfo el2_cp_reginfo[] = {
4854     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
4855       .type = ARM_CP_IO,
4856       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4857       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4858       .writefn = hcr_write },
4859     { .name = "HCR", .state = ARM_CP_STATE_AA32,
4860       .type = ARM_CP_ALIAS | ARM_CP_IO,
4861       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4862       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4863       .writefn = hcr_writelow },
4864     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4865       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4866       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4867     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
4868       .type = ARM_CP_ALIAS,
4869       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
4870       .access = PL2_RW,
4871       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
4872     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4873       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4874       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
4875     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4876       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4877       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
4878     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4879       .type = ARM_CP_ALIAS,
4880       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4881       .access = PL2_RW,
4882       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
4883     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
4884       .type = ARM_CP_ALIAS,
4885       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
4886       .access = PL2_RW,
4887       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
4888     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4889       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4890       .access = PL2_RW, .writefn = vbar_write,
4891       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
4892       .resetvalue = 0 },
4893     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
4894       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
4895       .access = PL3_RW, .type = ARM_CP_ALIAS,
4896       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
4897     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4898       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4899       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
4900       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
4901       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
4902     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4903       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4904       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
4905       .resetvalue = 0 },
4906     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4907       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4908       .access = PL2_RW, .type = ARM_CP_ALIAS,
4909       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
4910     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4911       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4912       .access = PL2_RW, .type = ARM_CP_CONST,
4913       .resetvalue = 0 },
4914     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
4915     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4916       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4917       .access = PL2_RW, .type = ARM_CP_CONST,
4918       .resetvalue = 0 },
4919     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4920       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4921       .access = PL2_RW, .type = ARM_CP_CONST,
4922       .resetvalue = 0 },
4923     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4924       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4925       .access = PL2_RW, .type = ARM_CP_CONST,
4926       .resetvalue = 0 },
4927     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4928       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4929       .access = PL2_RW,
4930       /* no .writefn needed as this can't cause an ASID change;
4931        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4932        */
4933       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
4934     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
4935       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4936       .type = ARM_CP_ALIAS,
4937       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4938       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4939     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
4940       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4941       .access = PL2_RW,
4942       /* no .writefn needed as this can't cause an ASID change;
4943        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4944        */
4945       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4946     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4947       .cp = 15, .opc1 = 6, .crm = 2,
4948       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4949       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4950       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
4951       .writefn = vttbr_write },
4952     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4953       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4954       .access = PL2_RW, .writefn = vttbr_write,
4955       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
4956     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4957       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4958       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
4959       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
4960     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4961       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4962       .access = PL2_RW, .resetvalue = 0,
4963       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
4964     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4965       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4966       .access = PL2_RW, .resetvalue = 0,
4967       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4968     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4969       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4970       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4971     { .name = "TLBIALLNSNH",
4972       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4973       .type = ARM_CP_NO_RAW, .access = PL2_W,
4974       .writefn = tlbiall_nsnh_write },
4975     { .name = "TLBIALLNSNHIS",
4976       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4977       .type = ARM_CP_NO_RAW, .access = PL2_W,
4978       .writefn = tlbiall_nsnh_is_write },
4979     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4980       .type = ARM_CP_NO_RAW, .access = PL2_W,
4981       .writefn = tlbiall_hyp_write },
4982     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4983       .type = ARM_CP_NO_RAW, .access = PL2_W,
4984       .writefn = tlbiall_hyp_is_write },
4985     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4986       .type = ARM_CP_NO_RAW, .access = PL2_W,
4987       .writefn = tlbimva_hyp_write },
4988     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4989       .type = ARM_CP_NO_RAW, .access = PL2_W,
4990       .writefn = tlbimva_hyp_is_write },
4991     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
4992       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4993       .type = ARM_CP_NO_RAW, .access = PL2_W,
4994       .writefn = tlbi_aa64_alle2_write },
4995     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
4996       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4997       .type = ARM_CP_NO_RAW, .access = PL2_W,
4998       .writefn = tlbi_aa64_vae2_write },
4999     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5000       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5001       .access = PL2_W, .type = ARM_CP_NO_RAW,
5002       .writefn = tlbi_aa64_vae2_write },
5003     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5004       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5005       .access = PL2_W, .type = ARM_CP_NO_RAW,
5006       .writefn = tlbi_aa64_alle2is_write },
5007     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5008       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5009       .type = ARM_CP_NO_RAW, .access = PL2_W,
5010       .writefn = tlbi_aa64_vae2is_write },
5011     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5012       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5013       .access = PL2_W, .type = ARM_CP_NO_RAW,
5014       .writefn = tlbi_aa64_vae2is_write },
5015 #ifndef CONFIG_USER_ONLY
5016     /* Unlike the other EL2-related AT operations, these must
5017      * UNDEF from EL3 if EL2 is not implemented, which is why we
5018      * define them here rather than with the rest of the AT ops.
5019      */
5020     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5021       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5022       .access = PL2_W, .accessfn = at_s1e2_access,
5023       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5024     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5025       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5026       .access = PL2_W, .accessfn = at_s1e2_access,
5027       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5028     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5029      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5030      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5031      * to behave as if SCR.NS was 1.
5032      */
5033     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5034       .access = PL2_W,
5035       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5036     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5037       .access = PL2_W,
5038       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5039     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5040       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5041       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5042        * reset values as IMPDEF. We choose to reset to 3 to comply with
5043        * both ARMv7 and ARMv8.
5044        */
5045       .access = PL2_RW, .resetvalue = 3,
5046       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5047     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5048       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5049       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5050       .writefn = gt_cntvoff_write,
5051       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5052     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5053       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5054       .writefn = gt_cntvoff_write,
5055       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5056     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5057       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5058       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5059       .type = ARM_CP_IO, .access = PL2_RW,
5060       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5061     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5062       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5063       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5064       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5065     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5066       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5067       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5068       .resetfn = gt_hyp_timer_reset,
5069       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5070     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5071       .type = ARM_CP_IO,
5072       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5073       .access = PL2_RW,
5074       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5075       .resetvalue = 0,
5076       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5077 #endif
5078     /* The only field of MDCR_EL2 that has a defined architectural reset value
5079      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
5080      * don't implement any PMU event counters, so using zero as a reset
5081      * value for MDCR_EL2 is okay
5082      */
5083     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5084       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5085       .access = PL2_RW, .resetvalue = 0,
5086       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5087     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5088       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5089       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5090       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5091     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5092       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5093       .access = PL2_RW,
5094       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5095     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5096       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5097       .access = PL2_RW,
5098       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5099     REGINFO_SENTINEL
5100 };
5101 
5102 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5103     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5104       .type = ARM_CP_ALIAS | ARM_CP_IO,
5105       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5106       .access = PL2_RW,
5107       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5108       .writefn = hcr_writehigh },
5109     REGINFO_SENTINEL
5110 };
5111 
5112 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5113                                    bool isread)
5114 {
5115     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5116      * At Secure EL1 it traps to EL3.
5117      */
5118     if (arm_current_el(env) == 3) {
5119         return CP_ACCESS_OK;
5120     }
5121     if (arm_is_secure_below_el3(env)) {
5122         return CP_ACCESS_TRAP_EL3;
5123     }
5124     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5125     if (isread) {
5126         return CP_ACCESS_OK;
5127     }
5128     return CP_ACCESS_TRAP_UNCATEGORIZED;
5129 }
5130 
5131 static const ARMCPRegInfo el3_cp_reginfo[] = {
5132     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5133       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5134       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5135       .resetvalue = 0, .writefn = scr_write },
5136     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5137       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5138       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5139       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5140       .writefn = scr_write },
5141     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5142       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5143       .access = PL3_RW, .resetvalue = 0,
5144       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5145     { .name = "SDER",
5146       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5147       .access = PL3_RW, .resetvalue = 0,
5148       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5149     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5150       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5151       .writefn = vbar_write, .resetvalue = 0,
5152       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5153     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5154       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5155       .access = PL3_RW, .resetvalue = 0,
5156       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5157     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5158       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5159       .access = PL3_RW,
5160       /* no .writefn needed as this can't cause an ASID change;
5161        * we must provide a .raw_writefn and .resetfn because we handle
5162        * reset and migration for the AArch32 TTBCR(S), which might be
5163        * using mask and base_mask.
5164        */
5165       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5166       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5167     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5168       .type = ARM_CP_ALIAS,
5169       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5170       .access = PL3_RW,
5171       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5172     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5173       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5174       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5175     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5176       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5177       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5178     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5179       .type = ARM_CP_ALIAS,
5180       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5181       .access = PL3_RW,
5182       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5183     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5184       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5185       .access = PL3_RW, .writefn = vbar_write,
5186       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5187       .resetvalue = 0 },
5188     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5189       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5190       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5191       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5192     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5193       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5194       .access = PL3_RW, .resetvalue = 0,
5195       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5196     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5197       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5198       .access = PL3_RW, .type = ARM_CP_CONST,
5199       .resetvalue = 0 },
5200     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5201       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5202       .access = PL3_RW, .type = ARM_CP_CONST,
5203       .resetvalue = 0 },
5204     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5205       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5206       .access = PL3_RW, .type = ARM_CP_CONST,
5207       .resetvalue = 0 },
5208     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5209       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5210       .access = PL3_W, .type = ARM_CP_NO_RAW,
5211       .writefn = tlbi_aa64_alle3is_write },
5212     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5213       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5214       .access = PL3_W, .type = ARM_CP_NO_RAW,
5215       .writefn = tlbi_aa64_vae3is_write },
5216     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5217       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5218       .access = PL3_W, .type = ARM_CP_NO_RAW,
5219       .writefn = tlbi_aa64_vae3is_write },
5220     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5221       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5222       .access = PL3_W, .type = ARM_CP_NO_RAW,
5223       .writefn = tlbi_aa64_alle3_write },
5224     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5225       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5226       .access = PL3_W, .type = ARM_CP_NO_RAW,
5227       .writefn = tlbi_aa64_vae3_write },
5228     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5229       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5230       .access = PL3_W, .type = ARM_CP_NO_RAW,
5231       .writefn = tlbi_aa64_vae3_write },
5232     REGINFO_SENTINEL
5233 };
5234 
5235 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5236                                      bool isread)
5237 {
5238     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
5239      * but the AArch32 CTR has its own reginfo struct)
5240      */
5241     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5242         return CP_ACCESS_TRAP;
5243     }
5244 
5245     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
5246         return CP_ACCESS_TRAP_EL2;
5247     }
5248 
5249     return CP_ACCESS_OK;
5250 }
5251 
5252 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5253                         uint64_t value)
5254 {
5255     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5256      * read via a bit in OSLSR_EL1.
5257      */
5258     int oslock;
5259 
5260     if (ri->state == ARM_CP_STATE_AA32) {
5261         oslock = (value == 0xC5ACCE55);
5262     } else {
5263         oslock = value & 1;
5264     }
5265 
5266     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5267 }
5268 
5269 static const ARMCPRegInfo debug_cp_reginfo[] = {
5270     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5271      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5272      * unlike DBGDRAR it is never accessible from EL0.
5273      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5274      * accessor.
5275      */
5276     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5277       .access = PL0_R, .accessfn = access_tdra,
5278       .type = ARM_CP_CONST, .resetvalue = 0 },
5279     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5280       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5281       .access = PL1_R, .accessfn = access_tdra,
5282       .type = ARM_CP_CONST, .resetvalue = 0 },
5283     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5284       .access = PL0_R, .accessfn = access_tdra,
5285       .type = ARM_CP_CONST, .resetvalue = 0 },
5286     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5287     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5288       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5289       .access = PL1_RW, .accessfn = access_tda,
5290       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5291       .resetvalue = 0 },
5292     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
5293      * We don't implement the configurable EL0 access.
5294      */
5295     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
5296       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5297       .type = ARM_CP_ALIAS,
5298       .access = PL1_R, .accessfn = access_tda,
5299       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
5300     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
5301       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
5302       .access = PL1_W, .type = ARM_CP_NO_RAW,
5303       .accessfn = access_tdosa,
5304       .writefn = oslar_write },
5305     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
5306       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
5307       .access = PL1_R, .resetvalue = 10,
5308       .accessfn = access_tdosa,
5309       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
5310     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
5311     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
5312       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
5313       .access = PL1_RW, .accessfn = access_tdosa,
5314       .type = ARM_CP_NOP },
5315     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
5316      * implement vector catch debug events yet.
5317      */
5318     { .name = "DBGVCR",
5319       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5320       .access = PL1_RW, .accessfn = access_tda,
5321       .type = ARM_CP_NOP },
5322     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
5323      * to save and restore a 32-bit guest's DBGVCR)
5324      */
5325     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
5326       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
5327       .access = PL2_RW, .accessfn = access_tda,
5328       .type = ARM_CP_NOP },
5329     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
5330      * Channel but Linux may try to access this register. The 32-bit
5331      * alias is DBGDCCINT.
5332      */
5333     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
5334       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5335       .access = PL1_RW, .accessfn = access_tda,
5336       .type = ARM_CP_NOP },
5337     REGINFO_SENTINEL
5338 };
5339 
5340 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
5341     /* 64 bit access versions of the (dummy) debug registers */
5342     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
5343       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5344     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
5345       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5346     REGINFO_SENTINEL
5347 };
5348 
5349 /* Return the exception level to which exceptions should be taken
5350  * via SVEAccessTrap.  If an exception should be routed through
5351  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
5352  * take care of raising that exception.
5353  * C.f. the ARM pseudocode function CheckSVEEnabled.
5354  */
5355 int sve_exception_el(CPUARMState *env, int el)
5356 {
5357 #ifndef CONFIG_USER_ONLY
5358     if (el <= 1) {
5359         bool disabled = false;
5360 
5361         /* The CPACR.ZEN controls traps to EL1:
5362          * 0, 2 : trap EL0 and EL1 accesses
5363          * 1    : trap only EL0 accesses
5364          * 3    : trap no accesses
5365          */
5366         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
5367             disabled = true;
5368         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
5369             disabled = el == 0;
5370         }
5371         if (disabled) {
5372             /* route_to_el2 */
5373             return (arm_feature(env, ARM_FEATURE_EL2)
5374                     && (arm_hcr_el2_eff(env) & HCR_TGE) ? 2 : 1);
5375         }
5376 
5377         /* Check CPACR.FPEN.  */
5378         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
5379             disabled = true;
5380         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
5381             disabled = el == 0;
5382         }
5383         if (disabled) {
5384             return 0;
5385         }
5386     }
5387 
5388     /* CPTR_EL2.  Since TZ and TFP are positive,
5389      * they will be zero when EL2 is not present.
5390      */
5391     if (el <= 2 && !arm_is_secure_below_el3(env)) {
5392         if (env->cp15.cptr_el[2] & CPTR_TZ) {
5393             return 2;
5394         }
5395         if (env->cp15.cptr_el[2] & CPTR_TFP) {
5396             return 0;
5397         }
5398     }
5399 
5400     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
5401     if (arm_feature(env, ARM_FEATURE_EL3)
5402         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
5403         return 3;
5404     }
5405 #endif
5406     return 0;
5407 }
5408 
5409 static uint32_t sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
5410 {
5411     uint32_t end_len;
5412 
5413     end_len = start_len &= 0xf;
5414     if (!test_bit(start_len, cpu->sve_vq_map)) {
5415         end_len = find_last_bit(cpu->sve_vq_map, start_len);
5416         assert(end_len < start_len);
5417     }
5418     return end_len;
5419 }
5420 
5421 /*
5422  * Given that SVE is enabled, return the vector length for EL.
5423  */
5424 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
5425 {
5426     ARMCPU *cpu = env_archcpu(env);
5427     uint32_t zcr_len = cpu->sve_max_vq - 1;
5428 
5429     if (el <= 1) {
5430         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
5431     }
5432     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
5433         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
5434     }
5435     if (arm_feature(env, ARM_FEATURE_EL3)) {
5436         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
5437     }
5438 
5439     return sve_zcr_get_valid_len(cpu, zcr_len);
5440 }
5441 
5442 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5443                       uint64_t value)
5444 {
5445     int cur_el = arm_current_el(env);
5446     int old_len = sve_zcr_len_for_el(env, cur_el);
5447     int new_len;
5448 
5449     /* Bits other than [3:0] are RAZ/WI.  */
5450     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
5451     raw_write(env, ri, value & 0xf);
5452 
5453     /*
5454      * Because we arrived here, we know both FP and SVE are enabled;
5455      * otherwise we would have trapped access to the ZCR_ELn register.
5456      */
5457     new_len = sve_zcr_len_for_el(env, cur_el);
5458     if (new_len < old_len) {
5459         aarch64_sve_narrow_vq(env, new_len + 1);
5460     }
5461 }
5462 
5463 static const ARMCPRegInfo zcr_el1_reginfo = {
5464     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
5465     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
5466     .access = PL1_RW, .type = ARM_CP_SVE,
5467     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
5468     .writefn = zcr_write, .raw_writefn = raw_write
5469 };
5470 
5471 static const ARMCPRegInfo zcr_el2_reginfo = {
5472     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5473     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5474     .access = PL2_RW, .type = ARM_CP_SVE,
5475     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
5476     .writefn = zcr_write, .raw_writefn = raw_write
5477 };
5478 
5479 static const ARMCPRegInfo zcr_no_el2_reginfo = {
5480     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5481     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5482     .access = PL2_RW, .type = ARM_CP_SVE,
5483     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
5484 };
5485 
5486 static const ARMCPRegInfo zcr_el3_reginfo = {
5487     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
5488     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
5489     .access = PL3_RW, .type = ARM_CP_SVE,
5490     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
5491     .writefn = zcr_write, .raw_writefn = raw_write
5492 };
5493 
5494 void hw_watchpoint_update(ARMCPU *cpu, int n)
5495 {
5496     CPUARMState *env = &cpu->env;
5497     vaddr len = 0;
5498     vaddr wvr = env->cp15.dbgwvr[n];
5499     uint64_t wcr = env->cp15.dbgwcr[n];
5500     int mask;
5501     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
5502 
5503     if (env->cpu_watchpoint[n]) {
5504         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
5505         env->cpu_watchpoint[n] = NULL;
5506     }
5507 
5508     if (!extract64(wcr, 0, 1)) {
5509         /* E bit clear : watchpoint disabled */
5510         return;
5511     }
5512 
5513     switch (extract64(wcr, 3, 2)) {
5514     case 0:
5515         /* LSC 00 is reserved and must behave as if the wp is disabled */
5516         return;
5517     case 1:
5518         flags |= BP_MEM_READ;
5519         break;
5520     case 2:
5521         flags |= BP_MEM_WRITE;
5522         break;
5523     case 3:
5524         flags |= BP_MEM_ACCESS;
5525         break;
5526     }
5527 
5528     /* Attempts to use both MASK and BAS fields simultaneously are
5529      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
5530      * thus generating a watchpoint for every byte in the masked region.
5531      */
5532     mask = extract64(wcr, 24, 4);
5533     if (mask == 1 || mask == 2) {
5534         /* Reserved values of MASK; we must act as if the mask value was
5535          * some non-reserved value, or as if the watchpoint were disabled.
5536          * We choose the latter.
5537          */
5538         return;
5539     } else if (mask) {
5540         /* Watchpoint covers an aligned area up to 2GB in size */
5541         len = 1ULL << mask;
5542         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
5543          * whether the watchpoint fires when the unmasked bits match; we opt
5544          * to generate the exceptions.
5545          */
5546         wvr &= ~(len - 1);
5547     } else {
5548         /* Watchpoint covers bytes defined by the byte address select bits */
5549         int bas = extract64(wcr, 5, 8);
5550         int basstart;
5551 
5552         if (bas == 0) {
5553             /* This must act as if the watchpoint is disabled */
5554             return;
5555         }
5556 
5557         if (extract64(wvr, 2, 1)) {
5558             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
5559              * ignored, and BAS[3:0] define which bytes to watch.
5560              */
5561             bas &= 0xf;
5562         }
5563         /* The BAS bits are supposed to be programmed to indicate a contiguous
5564          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
5565          * we fire for each byte in the word/doubleword addressed by the WVR.
5566          * We choose to ignore any non-zero bits after the first range of 1s.
5567          */
5568         basstart = ctz32(bas);
5569         len = cto32(bas >> basstart);
5570         wvr += basstart;
5571     }
5572 
5573     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
5574                           &env->cpu_watchpoint[n]);
5575 }
5576 
5577 void hw_watchpoint_update_all(ARMCPU *cpu)
5578 {
5579     int i;
5580     CPUARMState *env = &cpu->env;
5581 
5582     /* Completely clear out existing QEMU watchpoints and our array, to
5583      * avoid possible stale entries following migration load.
5584      */
5585     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
5586     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
5587 
5588     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
5589         hw_watchpoint_update(cpu, i);
5590     }
5591 }
5592 
5593 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5594                          uint64_t value)
5595 {
5596     ARMCPU *cpu = env_archcpu(env);
5597     int i = ri->crm;
5598 
5599     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
5600      * register reads and behaves as if values written are sign extended.
5601      * Bits [1:0] are RES0.
5602      */
5603     value = sextract64(value, 0, 49) & ~3ULL;
5604 
5605     raw_write(env, ri, value);
5606     hw_watchpoint_update(cpu, i);
5607 }
5608 
5609 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5610                          uint64_t value)
5611 {
5612     ARMCPU *cpu = env_archcpu(env);
5613     int i = ri->crm;
5614 
5615     raw_write(env, ri, value);
5616     hw_watchpoint_update(cpu, i);
5617 }
5618 
5619 void hw_breakpoint_update(ARMCPU *cpu, int n)
5620 {
5621     CPUARMState *env = &cpu->env;
5622     uint64_t bvr = env->cp15.dbgbvr[n];
5623     uint64_t bcr = env->cp15.dbgbcr[n];
5624     vaddr addr;
5625     int bt;
5626     int flags = BP_CPU;
5627 
5628     if (env->cpu_breakpoint[n]) {
5629         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
5630         env->cpu_breakpoint[n] = NULL;
5631     }
5632 
5633     if (!extract64(bcr, 0, 1)) {
5634         /* E bit clear : watchpoint disabled */
5635         return;
5636     }
5637 
5638     bt = extract64(bcr, 20, 4);
5639 
5640     switch (bt) {
5641     case 4: /* unlinked address mismatch (reserved if AArch64) */
5642     case 5: /* linked address mismatch (reserved if AArch64) */
5643         qemu_log_mask(LOG_UNIMP,
5644                       "arm: address mismatch breakpoint types not implemented\n");
5645         return;
5646     case 0: /* unlinked address match */
5647     case 1: /* linked address match */
5648     {
5649         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
5650          * we behave as if the register was sign extended. Bits [1:0] are
5651          * RES0. The BAS field is used to allow setting breakpoints on 16
5652          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
5653          * a bp will fire if the addresses covered by the bp and the addresses
5654          * covered by the insn overlap but the insn doesn't start at the
5655          * start of the bp address range. We choose to require the insn and
5656          * the bp to have the same address. The constraints on writing to
5657          * BAS enforced in dbgbcr_write mean we have only four cases:
5658          *  0b0000  => no breakpoint
5659          *  0b0011  => breakpoint on addr
5660          *  0b1100  => breakpoint on addr + 2
5661          *  0b1111  => breakpoint on addr
5662          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
5663          */
5664         int bas = extract64(bcr, 5, 4);
5665         addr = sextract64(bvr, 0, 49) & ~3ULL;
5666         if (bas == 0) {
5667             return;
5668         }
5669         if (bas == 0xc) {
5670             addr += 2;
5671         }
5672         break;
5673     }
5674     case 2: /* unlinked context ID match */
5675     case 8: /* unlinked VMID match (reserved if no EL2) */
5676     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
5677         qemu_log_mask(LOG_UNIMP,
5678                       "arm: unlinked context breakpoint types not implemented\n");
5679         return;
5680     case 9: /* linked VMID match (reserved if no EL2) */
5681     case 11: /* linked context ID and VMID match (reserved if no EL2) */
5682     case 3: /* linked context ID match */
5683     default:
5684         /* We must generate no events for Linked context matches (unless
5685          * they are linked to by some other bp/wp, which is handled in
5686          * updates for the linking bp/wp). We choose to also generate no events
5687          * for reserved values.
5688          */
5689         return;
5690     }
5691 
5692     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
5693 }
5694 
5695 void hw_breakpoint_update_all(ARMCPU *cpu)
5696 {
5697     int i;
5698     CPUARMState *env = &cpu->env;
5699 
5700     /* Completely clear out existing QEMU breakpoints and our array, to
5701      * avoid possible stale entries following migration load.
5702      */
5703     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
5704     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
5705 
5706     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
5707         hw_breakpoint_update(cpu, i);
5708     }
5709 }
5710 
5711 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5712                          uint64_t value)
5713 {
5714     ARMCPU *cpu = env_archcpu(env);
5715     int i = ri->crm;
5716 
5717     raw_write(env, ri, value);
5718     hw_breakpoint_update(cpu, i);
5719 }
5720 
5721 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5722                          uint64_t value)
5723 {
5724     ARMCPU *cpu = env_archcpu(env);
5725     int i = ri->crm;
5726 
5727     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
5728      * copy of BAS[0].
5729      */
5730     value = deposit64(value, 6, 1, extract64(value, 5, 1));
5731     value = deposit64(value, 8, 1, extract64(value, 7, 1));
5732 
5733     raw_write(env, ri, value);
5734     hw_breakpoint_update(cpu, i);
5735 }
5736 
5737 static void define_debug_regs(ARMCPU *cpu)
5738 {
5739     /* Define v7 and v8 architectural debug registers.
5740      * These are just dummy implementations for now.
5741      */
5742     int i;
5743     int wrps, brps, ctx_cmps;
5744     ARMCPRegInfo dbgdidr = {
5745         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
5746         .access = PL0_R, .accessfn = access_tda,
5747         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
5748     };
5749 
5750     /* Note that all these register fields hold "number of Xs minus 1". */
5751     brps = extract32(cpu->dbgdidr, 24, 4);
5752     wrps = extract32(cpu->dbgdidr, 28, 4);
5753     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
5754 
5755     assert(ctx_cmps <= brps);
5756 
5757     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
5758      * of the debug registers such as number of breakpoints;
5759      * check that if they both exist then they agree.
5760      */
5761     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
5762         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
5763         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
5764         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
5765     }
5766 
5767     define_one_arm_cp_reg(cpu, &dbgdidr);
5768     define_arm_cp_regs(cpu, debug_cp_reginfo);
5769 
5770     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
5771         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
5772     }
5773 
5774     for (i = 0; i < brps + 1; i++) {
5775         ARMCPRegInfo dbgregs[] = {
5776             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
5777               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
5778               .access = PL1_RW, .accessfn = access_tda,
5779               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
5780               .writefn = dbgbvr_write, .raw_writefn = raw_write
5781             },
5782             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
5783               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
5784               .access = PL1_RW, .accessfn = access_tda,
5785               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
5786               .writefn = dbgbcr_write, .raw_writefn = raw_write
5787             },
5788             REGINFO_SENTINEL
5789         };
5790         define_arm_cp_regs(cpu, dbgregs);
5791     }
5792 
5793     for (i = 0; i < wrps + 1; i++) {
5794         ARMCPRegInfo dbgregs[] = {
5795             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
5796               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
5797               .access = PL1_RW, .accessfn = access_tda,
5798               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
5799               .writefn = dbgwvr_write, .raw_writefn = raw_write
5800             },
5801             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
5802               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
5803               .access = PL1_RW, .accessfn = access_tda,
5804               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
5805               .writefn = dbgwcr_write, .raw_writefn = raw_write
5806             },
5807             REGINFO_SENTINEL
5808         };
5809         define_arm_cp_regs(cpu, dbgregs);
5810     }
5811 }
5812 
5813 /* We don't know until after realize whether there's a GICv3
5814  * attached, and that is what registers the gicv3 sysregs.
5815  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
5816  * at runtime.
5817  */
5818 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
5819 {
5820     ARMCPU *cpu = env_archcpu(env);
5821     uint64_t pfr1 = cpu->id_pfr1;
5822 
5823     if (env->gicv3state) {
5824         pfr1 |= 1 << 28;
5825     }
5826     return pfr1;
5827 }
5828 
5829 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
5830 {
5831     ARMCPU *cpu = env_archcpu(env);
5832     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
5833 
5834     if (env->gicv3state) {
5835         pfr0 |= 1 << 24;
5836     }
5837     return pfr0;
5838 }
5839 
5840 /* Shared logic between LORID and the rest of the LOR* registers.
5841  * Secure state has already been delt with.
5842  */
5843 static CPAccessResult access_lor_ns(CPUARMState *env)
5844 {
5845     int el = arm_current_el(env);
5846 
5847     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
5848         return CP_ACCESS_TRAP_EL2;
5849     }
5850     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
5851         return CP_ACCESS_TRAP_EL3;
5852     }
5853     return CP_ACCESS_OK;
5854 }
5855 
5856 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
5857                                    bool isread)
5858 {
5859     if (arm_is_secure_below_el3(env)) {
5860         /* Access ok in secure mode.  */
5861         return CP_ACCESS_OK;
5862     }
5863     return access_lor_ns(env);
5864 }
5865 
5866 static CPAccessResult access_lor_other(CPUARMState *env,
5867                                        const ARMCPRegInfo *ri, bool isread)
5868 {
5869     if (arm_is_secure_below_el3(env)) {
5870         /* Access denied in secure mode.  */
5871         return CP_ACCESS_TRAP;
5872     }
5873     return access_lor_ns(env);
5874 }
5875 
5876 #ifdef TARGET_AARCH64
5877 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
5878                                    bool isread)
5879 {
5880     int el = arm_current_el(env);
5881 
5882     if (el < 2 &&
5883         arm_feature(env, ARM_FEATURE_EL2) &&
5884         !(arm_hcr_el2_eff(env) & HCR_APK)) {
5885         return CP_ACCESS_TRAP_EL2;
5886     }
5887     if (el < 3 &&
5888         arm_feature(env, ARM_FEATURE_EL3) &&
5889         !(env->cp15.scr_el3 & SCR_APK)) {
5890         return CP_ACCESS_TRAP_EL3;
5891     }
5892     return CP_ACCESS_OK;
5893 }
5894 
5895 static const ARMCPRegInfo pauth_reginfo[] = {
5896     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5897       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
5898       .access = PL1_RW, .accessfn = access_pauth,
5899       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
5900     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5901       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
5902       .access = PL1_RW, .accessfn = access_pauth,
5903       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
5904     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5905       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
5906       .access = PL1_RW, .accessfn = access_pauth,
5907       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
5908     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5909       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
5910       .access = PL1_RW, .accessfn = access_pauth,
5911       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
5912     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5913       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
5914       .access = PL1_RW, .accessfn = access_pauth,
5915       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
5916     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5917       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
5918       .access = PL1_RW, .accessfn = access_pauth,
5919       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
5920     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5921       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
5922       .access = PL1_RW, .accessfn = access_pauth,
5923       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
5924     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5925       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
5926       .access = PL1_RW, .accessfn = access_pauth,
5927       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
5928     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5929       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
5930       .access = PL1_RW, .accessfn = access_pauth,
5931       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
5932     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5933       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
5934       .access = PL1_RW, .accessfn = access_pauth,
5935       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
5936     REGINFO_SENTINEL
5937 };
5938 
5939 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
5940 {
5941     Error *err = NULL;
5942     uint64_t ret;
5943 
5944     /* Success sets NZCV = 0000.  */
5945     env->NF = env->CF = env->VF = 0, env->ZF = 1;
5946 
5947     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
5948         /*
5949          * ??? Failed, for unknown reasons in the crypto subsystem.
5950          * The best we can do is log the reason and return the
5951          * timed-out indication to the guest.  There is no reason
5952          * we know to expect this failure to be transitory, so the
5953          * guest may well hang retrying the operation.
5954          */
5955         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
5956                       ri->name, error_get_pretty(err));
5957         error_free(err);
5958 
5959         env->ZF = 0; /* NZCF = 0100 */
5960         return 0;
5961     }
5962     return ret;
5963 }
5964 
5965 /* We do not support re-seeding, so the two registers operate the same.  */
5966 static const ARMCPRegInfo rndr_reginfo[] = {
5967     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
5968       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5969       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
5970       .access = PL0_R, .readfn = rndr_readfn },
5971     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
5972       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5973       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
5974       .access = PL0_R, .readfn = rndr_readfn },
5975     REGINFO_SENTINEL
5976 };
5977 
5978 #ifndef CONFIG_USER_ONLY
5979 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
5980                           uint64_t value)
5981 {
5982     ARMCPU *cpu = env_archcpu(env);
5983     /* CTR_EL0 System register -> DminLine, bits [19:16] */
5984     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
5985     uint64_t vaddr_in = (uint64_t) value;
5986     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
5987     void *haddr;
5988     int mem_idx = cpu_mmu_index(env, false);
5989 
5990     /* This won't be crossing page boundaries */
5991     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
5992     if (haddr) {
5993 
5994         ram_addr_t offset;
5995         MemoryRegion *mr;
5996 
5997         /* RCU lock is already being held */
5998         mr = memory_region_from_host(haddr, &offset);
5999 
6000         if (mr) {
6001             memory_region_do_writeback(mr, offset, dline_size);
6002         }
6003     }
6004 }
6005 
6006 static const ARMCPRegInfo dcpop_reg[] = {
6007     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
6008       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
6009       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6010       .accessfn = aa64_cacheop_access, .writefn = dccvap_writefn },
6011     REGINFO_SENTINEL
6012 };
6013 
6014 static const ARMCPRegInfo dcpodp_reg[] = {
6015     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
6016       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
6017       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6018       .accessfn = aa64_cacheop_access, .writefn = dccvap_writefn },
6019     REGINFO_SENTINEL
6020 };
6021 #endif /*CONFIG_USER_ONLY*/
6022 
6023 #endif
6024 
6025 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
6026                                      bool isread)
6027 {
6028     int el = arm_current_el(env);
6029 
6030     if (el == 0) {
6031         uint64_t sctlr = arm_sctlr(env, el);
6032         if (!(sctlr & SCTLR_EnRCTX)) {
6033             return CP_ACCESS_TRAP;
6034         }
6035     } else if (el == 1) {
6036         uint64_t hcr = arm_hcr_el2_eff(env);
6037         if (hcr & HCR_NV) {
6038             return CP_ACCESS_TRAP_EL2;
6039         }
6040     }
6041     return CP_ACCESS_OK;
6042 }
6043 
6044 static const ARMCPRegInfo predinv_reginfo[] = {
6045     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
6046       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
6047       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6048     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
6049       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
6050       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6051     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
6052       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
6053       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6054     /*
6055      * Note the AArch32 opcodes have a different OPC1.
6056      */
6057     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
6058       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
6059       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6060     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
6061       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
6062       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6063     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
6064       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
6065       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6066     REGINFO_SENTINEL
6067 };
6068 
6069 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
6070                                        bool isread)
6071 {
6072     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
6073         return CP_ACCESS_TRAP_EL2;
6074     }
6075 
6076     return CP_ACCESS_OK;
6077 }
6078 
6079 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
6080                                        bool isread)
6081 {
6082     if (arm_feature(env, ARM_FEATURE_V8)) {
6083         return access_aa64_tid3(env, ri, isread);
6084     }
6085 
6086     return CP_ACCESS_OK;
6087 }
6088 
6089 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
6090                                      bool isread)
6091 {
6092     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
6093         return CP_ACCESS_TRAP_EL2;
6094     }
6095 
6096     return CP_ACCESS_OK;
6097 }
6098 
6099 static const ARMCPRegInfo jazelle_regs[] = {
6100     { .name = "JIDR",
6101       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
6102       .access = PL1_R, .accessfn = access_jazelle,
6103       .type = ARM_CP_CONST, .resetvalue = 0 },
6104     { .name = "JOSCR",
6105       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
6106       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
6107     { .name = "JMCR",
6108       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
6109       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
6110     REGINFO_SENTINEL
6111 };
6112 
6113 void register_cp_regs_for_features(ARMCPU *cpu)
6114 {
6115     /* Register all the coprocessor registers based on feature bits */
6116     CPUARMState *env = &cpu->env;
6117     if (arm_feature(env, ARM_FEATURE_M)) {
6118         /* M profile has no coprocessor registers */
6119         return;
6120     }
6121 
6122     define_arm_cp_regs(cpu, cp_reginfo);
6123     if (!arm_feature(env, ARM_FEATURE_V8)) {
6124         /* Must go early as it is full of wildcards that may be
6125          * overridden by later definitions.
6126          */
6127         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
6128     }
6129 
6130     if (arm_feature(env, ARM_FEATURE_V6)) {
6131         /* The ID registers all have impdef reset values */
6132         ARMCPRegInfo v6_idregs[] = {
6133             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
6134               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6135               .access = PL1_R, .type = ARM_CP_CONST,
6136               .accessfn = access_aa32_tid3,
6137               .resetvalue = cpu->id_pfr0 },
6138             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
6139              * the value of the GIC field until after we define these regs.
6140              */
6141             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
6142               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
6143               .access = PL1_R, .type = ARM_CP_NO_RAW,
6144               .accessfn = access_aa32_tid3,
6145               .readfn = id_pfr1_read,
6146               .writefn = arm_cp_write_ignore },
6147             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
6148               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
6149               .access = PL1_R, .type = ARM_CP_CONST,
6150               .accessfn = access_aa32_tid3,
6151               .resetvalue = cpu->id_dfr0 },
6152             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
6153               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
6154               .access = PL1_R, .type = ARM_CP_CONST,
6155               .accessfn = access_aa32_tid3,
6156               .resetvalue = cpu->id_afr0 },
6157             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
6158               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
6159               .access = PL1_R, .type = ARM_CP_CONST,
6160               .accessfn = access_aa32_tid3,
6161               .resetvalue = cpu->id_mmfr0 },
6162             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
6163               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
6164               .access = PL1_R, .type = ARM_CP_CONST,
6165               .accessfn = access_aa32_tid3,
6166               .resetvalue = cpu->id_mmfr1 },
6167             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
6168               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
6169               .access = PL1_R, .type = ARM_CP_CONST,
6170               .accessfn = access_aa32_tid3,
6171               .resetvalue = cpu->id_mmfr2 },
6172             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
6173               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
6174               .access = PL1_R, .type = ARM_CP_CONST,
6175               .accessfn = access_aa32_tid3,
6176               .resetvalue = cpu->id_mmfr3 },
6177             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
6178               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6179               .access = PL1_R, .type = ARM_CP_CONST,
6180               .accessfn = access_aa32_tid3,
6181               .resetvalue = cpu->isar.id_isar0 },
6182             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
6183               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
6184               .access = PL1_R, .type = ARM_CP_CONST,
6185               .accessfn = access_aa32_tid3,
6186               .resetvalue = cpu->isar.id_isar1 },
6187             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
6188               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6189               .access = PL1_R, .type = ARM_CP_CONST,
6190               .accessfn = access_aa32_tid3,
6191               .resetvalue = cpu->isar.id_isar2 },
6192             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
6193               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
6194               .access = PL1_R, .type = ARM_CP_CONST,
6195               .accessfn = access_aa32_tid3,
6196               .resetvalue = cpu->isar.id_isar3 },
6197             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
6198               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
6199               .access = PL1_R, .type = ARM_CP_CONST,
6200               .accessfn = access_aa32_tid3,
6201               .resetvalue = cpu->isar.id_isar4 },
6202             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
6203               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
6204               .access = PL1_R, .type = ARM_CP_CONST,
6205               .accessfn = access_aa32_tid3,
6206               .resetvalue = cpu->isar.id_isar5 },
6207             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
6208               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
6209               .access = PL1_R, .type = ARM_CP_CONST,
6210               .accessfn = access_aa32_tid3,
6211               .resetvalue = cpu->id_mmfr4 },
6212             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
6213               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
6214               .access = PL1_R, .type = ARM_CP_CONST,
6215               .accessfn = access_aa32_tid3,
6216               .resetvalue = cpu->isar.id_isar6 },
6217             REGINFO_SENTINEL
6218         };
6219         define_arm_cp_regs(cpu, v6_idregs);
6220         define_arm_cp_regs(cpu, v6_cp_reginfo);
6221     } else {
6222         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
6223     }
6224     if (arm_feature(env, ARM_FEATURE_V6K)) {
6225         define_arm_cp_regs(cpu, v6k_cp_reginfo);
6226     }
6227     if (arm_feature(env, ARM_FEATURE_V7MP) &&
6228         !arm_feature(env, ARM_FEATURE_PMSA)) {
6229         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
6230     }
6231     if (arm_feature(env, ARM_FEATURE_V7VE)) {
6232         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
6233     }
6234     if (arm_feature(env, ARM_FEATURE_V7)) {
6235         /* v7 performance monitor control register: same implementor
6236          * field as main ID register, and we implement four counters in
6237          * addition to the cycle count register.
6238          */
6239         unsigned int i, pmcrn = 4;
6240         ARMCPRegInfo pmcr = {
6241             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6242             .access = PL0_RW,
6243             .type = ARM_CP_IO | ARM_CP_ALIAS,
6244             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6245             .accessfn = pmreg_access, .writefn = pmcr_write,
6246             .raw_writefn = raw_write,
6247         };
6248         ARMCPRegInfo pmcr64 = {
6249             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6250             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6251             .access = PL0_RW, .accessfn = pmreg_access,
6252             .type = ARM_CP_IO,
6253             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6254             .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT),
6255             .writefn = pmcr_write, .raw_writefn = raw_write,
6256         };
6257         define_one_arm_cp_reg(cpu, &pmcr);
6258         define_one_arm_cp_reg(cpu, &pmcr64);
6259         for (i = 0; i < pmcrn; i++) {
6260             char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6261             char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6262             char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6263             char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6264             ARMCPRegInfo pmev_regs[] = {
6265                 { .name = pmevcntr_name, .cp = 15, .crn = 14,
6266                   .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6267                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6268                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6269                   .accessfn = pmreg_access },
6270                 { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6271                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6272                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6273                   .type = ARM_CP_IO,
6274                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6275                   .raw_readfn = pmevcntr_rawread,
6276                   .raw_writefn = pmevcntr_rawwrite },
6277                 { .name = pmevtyper_name, .cp = 15, .crn = 14,
6278                   .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6279                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6280                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6281                   .accessfn = pmreg_access },
6282                 { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6283                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6284                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6285                   .type = ARM_CP_IO,
6286                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6287                   .raw_writefn = pmevtyper_rawwrite },
6288                 REGINFO_SENTINEL
6289             };
6290             define_arm_cp_regs(cpu, pmev_regs);
6291             g_free(pmevcntr_name);
6292             g_free(pmevcntr_el0_name);
6293             g_free(pmevtyper_name);
6294             g_free(pmevtyper_el0_name);
6295         }
6296         ARMCPRegInfo clidr = {
6297             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
6298             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
6299             .access = PL1_R, .type = ARM_CP_CONST,
6300             .accessfn = access_aa64_tid2,
6301             .resetvalue = cpu->clidr
6302         };
6303         define_one_arm_cp_reg(cpu, &clidr);
6304         define_arm_cp_regs(cpu, v7_cp_reginfo);
6305         define_debug_regs(cpu);
6306     } else {
6307         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
6308     }
6309     if (FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) >= 4 &&
6310             FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) != 0xf) {
6311         ARMCPRegInfo v81_pmu_regs[] = {
6312             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6313               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6314               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6315               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6316             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6317               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6318               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6319               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6320             REGINFO_SENTINEL
6321         };
6322         define_arm_cp_regs(cpu, v81_pmu_regs);
6323     }
6324     if (arm_feature(env, ARM_FEATURE_V8)) {
6325         /* AArch64 ID registers, which all have impdef reset values.
6326          * Note that within the ID register ranges the unused slots
6327          * must all RAZ, not UNDEF; future architecture versions may
6328          * define new registers here.
6329          */
6330         ARMCPRegInfo v8_idregs[] = {
6331             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
6332              * know the right value for the GIC field until after we
6333              * define these regs.
6334              */
6335             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
6336               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
6337               .access = PL1_R, .type = ARM_CP_NO_RAW,
6338               .accessfn = access_aa64_tid3,
6339               .readfn = id_aa64pfr0_read,
6340               .writefn = arm_cp_write_ignore },
6341             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
6342               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
6343               .access = PL1_R, .type = ARM_CP_CONST,
6344               .accessfn = access_aa64_tid3,
6345               .resetvalue = cpu->isar.id_aa64pfr1},
6346             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6347               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
6348               .access = PL1_R, .type = ARM_CP_CONST,
6349               .accessfn = access_aa64_tid3,
6350               .resetvalue = 0 },
6351             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6352               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
6353               .access = PL1_R, .type = ARM_CP_CONST,
6354               .accessfn = access_aa64_tid3,
6355               .resetvalue = 0 },
6356             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
6357               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
6358               .access = PL1_R, .type = ARM_CP_CONST,
6359               .accessfn = access_aa64_tid3,
6360               /* At present, only SVEver == 0 is defined anyway.  */
6361               .resetvalue = 0 },
6362             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6363               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
6364               .access = PL1_R, .type = ARM_CP_CONST,
6365               .accessfn = access_aa64_tid3,
6366               .resetvalue = 0 },
6367             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6368               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
6369               .access = PL1_R, .type = ARM_CP_CONST,
6370               .accessfn = access_aa64_tid3,
6371               .resetvalue = 0 },
6372             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6373               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
6374               .access = PL1_R, .type = ARM_CP_CONST,
6375               .accessfn = access_aa64_tid3,
6376               .resetvalue = 0 },
6377             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
6378               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
6379               .access = PL1_R, .type = ARM_CP_CONST,
6380               .accessfn = access_aa64_tid3,
6381               .resetvalue = cpu->id_aa64dfr0 },
6382             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
6383               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
6384               .access = PL1_R, .type = ARM_CP_CONST,
6385               .accessfn = access_aa64_tid3,
6386               .resetvalue = cpu->id_aa64dfr1 },
6387             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6388               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
6389               .access = PL1_R, .type = ARM_CP_CONST,
6390               .accessfn = access_aa64_tid3,
6391               .resetvalue = 0 },
6392             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6393               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
6394               .access = PL1_R, .type = ARM_CP_CONST,
6395               .accessfn = access_aa64_tid3,
6396               .resetvalue = 0 },
6397             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
6398               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
6399               .access = PL1_R, .type = ARM_CP_CONST,
6400               .accessfn = access_aa64_tid3,
6401               .resetvalue = cpu->id_aa64afr0 },
6402             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
6403               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
6404               .access = PL1_R, .type = ARM_CP_CONST,
6405               .accessfn = access_aa64_tid3,
6406               .resetvalue = cpu->id_aa64afr1 },
6407             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6408               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
6409               .access = PL1_R, .type = ARM_CP_CONST,
6410               .accessfn = access_aa64_tid3,
6411               .resetvalue = 0 },
6412             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6413               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
6414               .access = PL1_R, .type = ARM_CP_CONST,
6415               .accessfn = access_aa64_tid3,
6416               .resetvalue = 0 },
6417             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
6418               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
6419               .access = PL1_R, .type = ARM_CP_CONST,
6420               .accessfn = access_aa64_tid3,
6421               .resetvalue = cpu->isar.id_aa64isar0 },
6422             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
6423               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
6424               .access = PL1_R, .type = ARM_CP_CONST,
6425               .accessfn = access_aa64_tid3,
6426               .resetvalue = cpu->isar.id_aa64isar1 },
6427             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6428               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
6429               .access = PL1_R, .type = ARM_CP_CONST,
6430               .accessfn = access_aa64_tid3,
6431               .resetvalue = 0 },
6432             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6433               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
6434               .access = PL1_R, .type = ARM_CP_CONST,
6435               .accessfn = access_aa64_tid3,
6436               .resetvalue = 0 },
6437             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6438               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
6439               .access = PL1_R, .type = ARM_CP_CONST,
6440               .accessfn = access_aa64_tid3,
6441               .resetvalue = 0 },
6442             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6443               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
6444               .access = PL1_R, .type = ARM_CP_CONST,
6445               .accessfn = access_aa64_tid3,
6446               .resetvalue = 0 },
6447             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6448               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
6449               .access = PL1_R, .type = ARM_CP_CONST,
6450               .accessfn = access_aa64_tid3,
6451               .resetvalue = 0 },
6452             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6453               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
6454               .access = PL1_R, .type = ARM_CP_CONST,
6455               .accessfn = access_aa64_tid3,
6456               .resetvalue = 0 },
6457             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
6458               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6459               .access = PL1_R, .type = ARM_CP_CONST,
6460               .accessfn = access_aa64_tid3,
6461               .resetvalue = cpu->isar.id_aa64mmfr0 },
6462             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
6463               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
6464               .access = PL1_R, .type = ARM_CP_CONST,
6465               .accessfn = access_aa64_tid3,
6466               .resetvalue = cpu->isar.id_aa64mmfr1 },
6467             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6468               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
6469               .access = PL1_R, .type = ARM_CP_CONST,
6470               .accessfn = access_aa64_tid3,
6471               .resetvalue = 0 },
6472             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6473               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
6474               .access = PL1_R, .type = ARM_CP_CONST,
6475               .accessfn = access_aa64_tid3,
6476               .resetvalue = 0 },
6477             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6478               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
6479               .access = PL1_R, .type = ARM_CP_CONST,
6480               .accessfn = access_aa64_tid3,
6481               .resetvalue = 0 },
6482             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6483               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
6484               .access = PL1_R, .type = ARM_CP_CONST,
6485               .accessfn = access_aa64_tid3,
6486               .resetvalue = 0 },
6487             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6488               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
6489               .access = PL1_R, .type = ARM_CP_CONST,
6490               .accessfn = access_aa64_tid3,
6491               .resetvalue = 0 },
6492             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6493               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
6494               .access = PL1_R, .type = ARM_CP_CONST,
6495               .accessfn = access_aa64_tid3,
6496               .resetvalue = 0 },
6497             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
6498               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
6499               .access = PL1_R, .type = ARM_CP_CONST,
6500               .accessfn = access_aa64_tid3,
6501               .resetvalue = cpu->isar.mvfr0 },
6502             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
6503               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
6504               .access = PL1_R, .type = ARM_CP_CONST,
6505               .accessfn = access_aa64_tid3,
6506               .resetvalue = cpu->isar.mvfr1 },
6507             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
6508               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
6509               .access = PL1_R, .type = ARM_CP_CONST,
6510               .accessfn = access_aa64_tid3,
6511               .resetvalue = cpu->isar.mvfr2 },
6512             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6513               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
6514               .access = PL1_R, .type = ARM_CP_CONST,
6515               .accessfn = access_aa64_tid3,
6516               .resetvalue = 0 },
6517             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6518               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
6519               .access = PL1_R, .type = ARM_CP_CONST,
6520               .accessfn = access_aa64_tid3,
6521               .resetvalue = 0 },
6522             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6523               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
6524               .access = PL1_R, .type = ARM_CP_CONST,
6525               .accessfn = access_aa64_tid3,
6526               .resetvalue = 0 },
6527             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6528               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
6529               .access = PL1_R, .type = ARM_CP_CONST,
6530               .accessfn = access_aa64_tid3,
6531               .resetvalue = 0 },
6532             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6533               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
6534               .access = PL1_R, .type = ARM_CP_CONST,
6535               .accessfn = access_aa64_tid3,
6536               .resetvalue = 0 },
6537             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
6538               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
6539               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6540               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
6541             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
6542               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
6543               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6544               .resetvalue = cpu->pmceid0 },
6545             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
6546               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
6547               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6548               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
6549             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
6550               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
6551               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6552               .resetvalue = cpu->pmceid1 },
6553             REGINFO_SENTINEL
6554         };
6555 #ifdef CONFIG_USER_ONLY
6556         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
6557             { .name = "ID_AA64PFR0_EL1",
6558               .exported_bits = 0x000f000f00ff0000,
6559               .fixed_bits    = 0x0000000000000011 },
6560             { .name = "ID_AA64PFR1_EL1",
6561               .exported_bits = 0x00000000000000f0 },
6562             { .name = "ID_AA64PFR*_EL1_RESERVED",
6563               .is_glob = true                     },
6564             { .name = "ID_AA64ZFR0_EL1"           },
6565             { .name = "ID_AA64MMFR0_EL1",
6566               .fixed_bits    = 0x00000000ff000000 },
6567             { .name = "ID_AA64MMFR1_EL1"          },
6568             { .name = "ID_AA64MMFR*_EL1_RESERVED",
6569               .is_glob = true                     },
6570             { .name = "ID_AA64DFR0_EL1",
6571               .fixed_bits    = 0x0000000000000006 },
6572             { .name = "ID_AA64DFR1_EL1"           },
6573             { .name = "ID_AA64DFR*_EL1_RESERVED",
6574               .is_glob = true                     },
6575             { .name = "ID_AA64AFR*",
6576               .is_glob = true                     },
6577             { .name = "ID_AA64ISAR0_EL1",
6578               .exported_bits = 0x00fffffff0fffff0 },
6579             { .name = "ID_AA64ISAR1_EL1",
6580               .exported_bits = 0x000000f0ffffffff },
6581             { .name = "ID_AA64ISAR*_EL1_RESERVED",
6582               .is_glob = true                     },
6583             REGUSERINFO_SENTINEL
6584         };
6585         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
6586 #endif
6587         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
6588         if (!arm_feature(env, ARM_FEATURE_EL3) &&
6589             !arm_feature(env, ARM_FEATURE_EL2)) {
6590             ARMCPRegInfo rvbar = {
6591                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
6592                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
6593                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
6594             };
6595             define_one_arm_cp_reg(cpu, &rvbar);
6596         }
6597         define_arm_cp_regs(cpu, v8_idregs);
6598         define_arm_cp_regs(cpu, v8_cp_reginfo);
6599     }
6600     if (arm_feature(env, ARM_FEATURE_EL2)) {
6601         uint64_t vmpidr_def = mpidr_read_val(env);
6602         ARMCPRegInfo vpidr_regs[] = {
6603             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
6604               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6605               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6606               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
6607               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
6608             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
6609               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6610               .access = PL2_RW, .resetvalue = cpu->midr,
6611               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6612             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
6613               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6614               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6615               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
6616               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
6617             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
6618               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6619               .access = PL2_RW,
6620               .resetvalue = vmpidr_def,
6621               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
6622             REGINFO_SENTINEL
6623         };
6624         define_arm_cp_regs(cpu, vpidr_regs);
6625         define_arm_cp_regs(cpu, el2_cp_reginfo);
6626         if (arm_feature(env, ARM_FEATURE_V8)) {
6627             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
6628         }
6629         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
6630         if (!arm_feature(env, ARM_FEATURE_EL3)) {
6631             ARMCPRegInfo rvbar = {
6632                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
6633                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
6634                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
6635             };
6636             define_one_arm_cp_reg(cpu, &rvbar);
6637         }
6638     } else {
6639         /* If EL2 is missing but higher ELs are enabled, we need to
6640          * register the no_el2 reginfos.
6641          */
6642         if (arm_feature(env, ARM_FEATURE_EL3)) {
6643             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
6644              * of MIDR_EL1 and MPIDR_EL1.
6645              */
6646             ARMCPRegInfo vpidr_regs[] = {
6647                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6648                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6649                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6650                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
6651                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6652                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6653                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6654                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6655                   .type = ARM_CP_NO_RAW,
6656                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
6657                 REGINFO_SENTINEL
6658             };
6659             define_arm_cp_regs(cpu, vpidr_regs);
6660             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
6661             if (arm_feature(env, ARM_FEATURE_V8)) {
6662                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
6663             }
6664         }
6665     }
6666     if (arm_feature(env, ARM_FEATURE_EL3)) {
6667         define_arm_cp_regs(cpu, el3_cp_reginfo);
6668         ARMCPRegInfo el3_regs[] = {
6669             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
6670               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
6671               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
6672             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
6673               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
6674               .access = PL3_RW,
6675               .raw_writefn = raw_write, .writefn = sctlr_write,
6676               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
6677               .resetvalue = cpu->reset_sctlr },
6678             REGINFO_SENTINEL
6679         };
6680 
6681         define_arm_cp_regs(cpu, el3_regs);
6682     }
6683     /* The behaviour of NSACR is sufficiently various that we don't
6684      * try to describe it in a single reginfo:
6685      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
6686      *     reads as constant 0xc00 from NS EL1 and NS EL2
6687      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
6688      *  if v7 without EL3, register doesn't exist
6689      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
6690      */
6691     if (arm_feature(env, ARM_FEATURE_EL3)) {
6692         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6693             ARMCPRegInfo nsacr = {
6694                 .name = "NSACR", .type = ARM_CP_CONST,
6695                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6696                 .access = PL1_RW, .accessfn = nsacr_access,
6697                 .resetvalue = 0xc00
6698             };
6699             define_one_arm_cp_reg(cpu, &nsacr);
6700         } else {
6701             ARMCPRegInfo nsacr = {
6702                 .name = "NSACR",
6703                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6704                 .access = PL3_RW | PL1_R,
6705                 .resetvalue = 0,
6706                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
6707             };
6708             define_one_arm_cp_reg(cpu, &nsacr);
6709         }
6710     } else {
6711         if (arm_feature(env, ARM_FEATURE_V8)) {
6712             ARMCPRegInfo nsacr = {
6713                 .name = "NSACR", .type = ARM_CP_CONST,
6714                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6715                 .access = PL1_R,
6716                 .resetvalue = 0xc00
6717             };
6718             define_one_arm_cp_reg(cpu, &nsacr);
6719         }
6720     }
6721 
6722     if (arm_feature(env, ARM_FEATURE_PMSA)) {
6723         if (arm_feature(env, ARM_FEATURE_V6)) {
6724             /* PMSAv6 not implemented */
6725             assert(arm_feature(env, ARM_FEATURE_V7));
6726             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6727             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
6728         } else {
6729             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
6730         }
6731     } else {
6732         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6733         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
6734         /* TTCBR2 is introduced with ARMv8.2-A32HPD.  */
6735         if (FIELD_EX32(cpu->id_mmfr4, ID_MMFR4, HPDS) != 0) {
6736             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
6737         }
6738     }
6739     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
6740         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
6741     }
6742     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
6743         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
6744     }
6745     if (arm_feature(env, ARM_FEATURE_VAPA)) {
6746         define_arm_cp_regs(cpu, vapa_cp_reginfo);
6747     }
6748     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
6749         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
6750     }
6751     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
6752         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
6753     }
6754     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
6755         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
6756     }
6757     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
6758         define_arm_cp_regs(cpu, omap_cp_reginfo);
6759     }
6760     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
6761         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
6762     }
6763     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6764         define_arm_cp_regs(cpu, xscale_cp_reginfo);
6765     }
6766     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
6767         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
6768     }
6769     if (arm_feature(env, ARM_FEATURE_LPAE)) {
6770         define_arm_cp_regs(cpu, lpae_cp_reginfo);
6771     }
6772     if (cpu_isar_feature(jazelle, cpu)) {
6773         define_arm_cp_regs(cpu, jazelle_regs);
6774     }
6775     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
6776      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
6777      * be read-only (ie write causes UNDEF exception).
6778      */
6779     {
6780         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
6781             /* Pre-v8 MIDR space.
6782              * Note that the MIDR isn't a simple constant register because
6783              * of the TI925 behaviour where writes to another register can
6784              * cause the MIDR value to change.
6785              *
6786              * Unimplemented registers in the c15 0 0 0 space default to
6787              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
6788              * and friends override accordingly.
6789              */
6790             { .name = "MIDR",
6791               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
6792               .access = PL1_R, .resetvalue = cpu->midr,
6793               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
6794               .readfn = midr_read,
6795               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6796               .type = ARM_CP_OVERRIDE },
6797             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
6798             { .name = "DUMMY",
6799               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
6800               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6801             { .name = "DUMMY",
6802               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
6803               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6804             { .name = "DUMMY",
6805               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
6806               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6807             { .name = "DUMMY",
6808               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
6809               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6810             { .name = "DUMMY",
6811               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
6812               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6813             REGINFO_SENTINEL
6814         };
6815         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
6816             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
6817               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
6818               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
6819               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6820               .readfn = midr_read },
6821             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
6822             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6823               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6824               .access = PL1_R, .resetvalue = cpu->midr },
6825             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6826               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
6827               .access = PL1_R, .resetvalue = cpu->midr },
6828             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
6829               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
6830               .access = PL1_R,
6831               .accessfn = access_aa64_tid1,
6832               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
6833             REGINFO_SENTINEL
6834         };
6835         ARMCPRegInfo id_cp_reginfo[] = {
6836             /* These are common to v8 and pre-v8 */
6837             { .name = "CTR",
6838               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
6839               .access = PL1_R, .accessfn = ctr_el0_access,
6840               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6841             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
6842               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
6843               .access = PL0_R, .accessfn = ctr_el0_access,
6844               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6845             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
6846             { .name = "TCMTR",
6847               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
6848               .access = PL1_R,
6849               .accessfn = access_aa32_tid1,
6850               .type = ARM_CP_CONST, .resetvalue = 0 },
6851             REGINFO_SENTINEL
6852         };
6853         /* TLBTR is specific to VMSA */
6854         ARMCPRegInfo id_tlbtr_reginfo = {
6855               .name = "TLBTR",
6856               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
6857               .access = PL1_R,
6858               .accessfn = access_aa32_tid1,
6859               .type = ARM_CP_CONST, .resetvalue = 0,
6860         };
6861         /* MPUIR is specific to PMSA V6+ */
6862         ARMCPRegInfo id_mpuir_reginfo = {
6863               .name = "MPUIR",
6864               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6865               .access = PL1_R, .type = ARM_CP_CONST,
6866               .resetvalue = cpu->pmsav7_dregion << 8
6867         };
6868         ARMCPRegInfo crn0_wi_reginfo = {
6869             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
6870             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
6871             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
6872         };
6873 #ifdef CONFIG_USER_ONLY
6874         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
6875             { .name = "MIDR_EL1",
6876               .exported_bits = 0x00000000ffffffff },
6877             { .name = "REVIDR_EL1"                },
6878             REGUSERINFO_SENTINEL
6879         };
6880         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
6881 #endif
6882         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
6883             arm_feature(env, ARM_FEATURE_STRONGARM)) {
6884             ARMCPRegInfo *r;
6885             /* Register the blanket "writes ignored" value first to cover the
6886              * whole space. Then update the specific ID registers to allow write
6887              * access, so that they ignore writes rather than causing them to
6888              * UNDEF.
6889              */
6890             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
6891             for (r = id_pre_v8_midr_cp_reginfo;
6892                  r->type != ARM_CP_SENTINEL; r++) {
6893                 r->access = PL1_RW;
6894             }
6895             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
6896                 r->access = PL1_RW;
6897             }
6898             id_mpuir_reginfo.access = PL1_RW;
6899             id_tlbtr_reginfo.access = PL1_RW;
6900         }
6901         if (arm_feature(env, ARM_FEATURE_V8)) {
6902             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
6903         } else {
6904             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
6905         }
6906         define_arm_cp_regs(cpu, id_cp_reginfo);
6907         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
6908             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
6909         } else if (arm_feature(env, ARM_FEATURE_V7)) {
6910             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
6911         }
6912     }
6913 
6914     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
6915         ARMCPRegInfo mpidr_cp_reginfo[] = {
6916             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
6917               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
6918               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
6919             REGINFO_SENTINEL
6920         };
6921 #ifdef CONFIG_USER_ONLY
6922         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
6923             { .name = "MPIDR_EL1",
6924               .fixed_bits = 0x0000000080000000 },
6925             REGUSERINFO_SENTINEL
6926         };
6927         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
6928 #endif
6929         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
6930     }
6931 
6932     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
6933         ARMCPRegInfo auxcr_reginfo[] = {
6934             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
6935               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
6936               .access = PL1_RW, .type = ARM_CP_CONST,
6937               .resetvalue = cpu->reset_auxcr },
6938             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
6939               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
6940               .access = PL2_RW, .type = ARM_CP_CONST,
6941               .resetvalue = 0 },
6942             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
6943               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
6944               .access = PL3_RW, .type = ARM_CP_CONST,
6945               .resetvalue = 0 },
6946             REGINFO_SENTINEL
6947         };
6948         define_arm_cp_regs(cpu, auxcr_reginfo);
6949         if (arm_feature(env, ARM_FEATURE_V8)) {
6950             /* HACTLR2 maps to ACTLR_EL2[63:32] and is not in ARMv7 */
6951             ARMCPRegInfo hactlr2_reginfo = {
6952                 .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
6953                 .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
6954                 .access = PL2_RW, .type = ARM_CP_CONST,
6955                 .resetvalue = 0
6956             };
6957             define_one_arm_cp_reg(cpu, &hactlr2_reginfo);
6958         }
6959     }
6960 
6961     if (arm_feature(env, ARM_FEATURE_CBAR)) {
6962         /*
6963          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
6964          * There are two flavours:
6965          *  (1) older 32-bit only cores have a simple 32-bit CBAR
6966          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
6967          *      32-bit register visible to AArch32 at a different encoding
6968          *      to the "flavour 1" register and with the bits rearranged to
6969          *      be able to squash a 64-bit address into the 32-bit view.
6970          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
6971          * in future if we support AArch32-only configs of some of the
6972          * AArch64 cores we might need to add a specific feature flag
6973          * to indicate cores with "flavour 2" CBAR.
6974          */
6975         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6976             /* 32 bit view is [31:18] 0...0 [43:32]. */
6977             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
6978                 | extract64(cpu->reset_cbar, 32, 12);
6979             ARMCPRegInfo cbar_reginfo[] = {
6980                 { .name = "CBAR",
6981                   .type = ARM_CP_CONST,
6982                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
6983                   .access = PL1_R, .resetvalue = cbar32 },
6984                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
6985                   .type = ARM_CP_CONST,
6986                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
6987                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
6988                 REGINFO_SENTINEL
6989             };
6990             /* We don't implement a r/w 64 bit CBAR currently */
6991             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
6992             define_arm_cp_regs(cpu, cbar_reginfo);
6993         } else {
6994             ARMCPRegInfo cbar = {
6995                 .name = "CBAR",
6996                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
6997                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
6998                 .fieldoffset = offsetof(CPUARMState,
6999                                         cp15.c15_config_base_address)
7000             };
7001             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
7002                 cbar.access = PL1_R;
7003                 cbar.fieldoffset = 0;
7004                 cbar.type = ARM_CP_CONST;
7005             }
7006             define_one_arm_cp_reg(cpu, &cbar);
7007         }
7008     }
7009 
7010     if (arm_feature(env, ARM_FEATURE_VBAR)) {
7011         ARMCPRegInfo vbar_cp_reginfo[] = {
7012             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
7013               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
7014               .access = PL1_RW, .writefn = vbar_write,
7015               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
7016                                      offsetof(CPUARMState, cp15.vbar_ns) },
7017               .resetvalue = 0 },
7018             REGINFO_SENTINEL
7019         };
7020         define_arm_cp_regs(cpu, vbar_cp_reginfo);
7021     }
7022 
7023     /* Generic registers whose values depend on the implementation */
7024     {
7025         ARMCPRegInfo sctlr = {
7026             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
7027             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
7028             .access = PL1_RW,
7029             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
7030                                    offsetof(CPUARMState, cp15.sctlr_ns) },
7031             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
7032             .raw_writefn = raw_write,
7033         };
7034         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7035             /* Normally we would always end the TB on an SCTLR write, but Linux
7036              * arch/arm/mach-pxa/sleep.S expects two instructions following
7037              * an MMU enable to execute from cache.  Imitate this behaviour.
7038              */
7039             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
7040         }
7041         define_one_arm_cp_reg(cpu, &sctlr);
7042     }
7043 
7044     if (cpu_isar_feature(aa64_lor, cpu)) {
7045         /*
7046          * A trivial implementation of ARMv8.1-LOR leaves all of these
7047          * registers fixed at 0, which indicates that there are zero
7048          * supported Limited Ordering regions.
7049          */
7050         static const ARMCPRegInfo lor_reginfo[] = {
7051             { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
7052               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
7053               .access = PL1_RW, .accessfn = access_lor_other,
7054               .type = ARM_CP_CONST, .resetvalue = 0 },
7055             { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
7056               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
7057               .access = PL1_RW, .accessfn = access_lor_other,
7058               .type = ARM_CP_CONST, .resetvalue = 0 },
7059             { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
7060               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
7061               .access = PL1_RW, .accessfn = access_lor_other,
7062               .type = ARM_CP_CONST, .resetvalue = 0 },
7063             { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
7064               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
7065               .access = PL1_RW, .accessfn = access_lor_other,
7066               .type = ARM_CP_CONST, .resetvalue = 0 },
7067             { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
7068               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
7069               .access = PL1_R, .accessfn = access_lorid,
7070               .type = ARM_CP_CONST, .resetvalue = 0 },
7071             REGINFO_SENTINEL
7072         };
7073         define_arm_cp_regs(cpu, lor_reginfo);
7074     }
7075 
7076     if (cpu_isar_feature(aa64_sve, cpu)) {
7077         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
7078         if (arm_feature(env, ARM_FEATURE_EL2)) {
7079             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
7080         } else {
7081             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
7082         }
7083         if (arm_feature(env, ARM_FEATURE_EL3)) {
7084             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
7085         }
7086     }
7087 
7088 #ifdef TARGET_AARCH64
7089     if (cpu_isar_feature(aa64_pauth, cpu)) {
7090         define_arm_cp_regs(cpu, pauth_reginfo);
7091     }
7092     if (cpu_isar_feature(aa64_rndr, cpu)) {
7093         define_arm_cp_regs(cpu, rndr_reginfo);
7094     }
7095 #ifndef CONFIG_USER_ONLY
7096     /* Data Cache clean instructions up to PoP */
7097     if (cpu_isar_feature(aa64_dcpop, cpu)) {
7098         define_one_arm_cp_reg(cpu, dcpop_reg);
7099 
7100         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
7101             define_one_arm_cp_reg(cpu, dcpodp_reg);
7102         }
7103     }
7104 #endif /*CONFIG_USER_ONLY*/
7105 #endif
7106 
7107     /*
7108      * While all v8.0 cpus support aarch64, QEMU does have configurations
7109      * that do not set ID_AA64ISAR1, e.g. user-only qemu-arm -cpu max,
7110      * which will set ID_ISAR6.
7111      */
7112     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)
7113         ? cpu_isar_feature(aa64_predinv, cpu)
7114         : cpu_isar_feature(aa32_predinv, cpu)) {
7115         define_arm_cp_regs(cpu, predinv_reginfo);
7116     }
7117 }
7118 
7119 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
7120 {
7121     CPUState *cs = CPU(cpu);
7122     CPUARMState *env = &cpu->env;
7123 
7124     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7125         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
7126                                  aarch64_fpu_gdb_set_reg,
7127                                  34, "aarch64-fpu.xml", 0);
7128     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
7129         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
7130                                  51, "arm-neon.xml", 0);
7131     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
7132         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
7133                                  35, "arm-vfp3.xml", 0);
7134     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
7135         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
7136                                  19, "arm-vfp.xml", 0);
7137     }
7138     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
7139                              arm_gen_dynamic_xml(cs),
7140                              "system-registers.xml", 0);
7141 }
7142 
7143 /* Sort alphabetically by type name, except for "any". */
7144 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
7145 {
7146     ObjectClass *class_a = (ObjectClass *)a;
7147     ObjectClass *class_b = (ObjectClass *)b;
7148     const char *name_a, *name_b;
7149 
7150     name_a = object_class_get_name(class_a);
7151     name_b = object_class_get_name(class_b);
7152     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
7153         return 1;
7154     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
7155         return -1;
7156     } else {
7157         return strcmp(name_a, name_b);
7158     }
7159 }
7160 
7161 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
7162 {
7163     ObjectClass *oc = data;
7164     const char *typename;
7165     char *name;
7166 
7167     typename = object_class_get_name(oc);
7168     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
7169     qemu_printf("  %s\n", name);
7170     g_free(name);
7171 }
7172 
7173 void arm_cpu_list(void)
7174 {
7175     GSList *list;
7176 
7177     list = object_class_get_list(TYPE_ARM_CPU, false);
7178     list = g_slist_sort(list, arm_cpu_list_compare);
7179     qemu_printf("Available CPUs:\n");
7180     g_slist_foreach(list, arm_cpu_list_entry, NULL);
7181     g_slist_free(list);
7182 }
7183 
7184 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
7185 {
7186     ObjectClass *oc = data;
7187     CpuDefinitionInfoList **cpu_list = user_data;
7188     CpuDefinitionInfoList *entry;
7189     CpuDefinitionInfo *info;
7190     const char *typename;
7191 
7192     typename = object_class_get_name(oc);
7193     info = g_malloc0(sizeof(*info));
7194     info->name = g_strndup(typename,
7195                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
7196     info->q_typename = g_strdup(typename);
7197 
7198     entry = g_malloc0(sizeof(*entry));
7199     entry->value = info;
7200     entry->next = *cpu_list;
7201     *cpu_list = entry;
7202 }
7203 
7204 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
7205 {
7206     CpuDefinitionInfoList *cpu_list = NULL;
7207     GSList *list;
7208 
7209     list = object_class_get_list(TYPE_ARM_CPU, false);
7210     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
7211     g_slist_free(list);
7212 
7213     return cpu_list;
7214 }
7215 
7216 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
7217                                    void *opaque, int state, int secstate,
7218                                    int crm, int opc1, int opc2,
7219                                    const char *name)
7220 {
7221     /* Private utility function for define_one_arm_cp_reg_with_opaque():
7222      * add a single reginfo struct to the hash table.
7223      */
7224     uint32_t *key = g_new(uint32_t, 1);
7225     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
7226     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
7227     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
7228 
7229     r2->name = g_strdup(name);
7230     /* Reset the secure state to the specific incoming state.  This is
7231      * necessary as the register may have been defined with both states.
7232      */
7233     r2->secure = secstate;
7234 
7235     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
7236         /* Register is banked (using both entries in array).
7237          * Overwriting fieldoffset as the array is only used to define
7238          * banked registers but later only fieldoffset is used.
7239          */
7240         r2->fieldoffset = r->bank_fieldoffsets[ns];
7241     }
7242 
7243     if (state == ARM_CP_STATE_AA32) {
7244         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
7245             /* If the register is banked then we don't need to migrate or
7246              * reset the 32-bit instance in certain cases:
7247              *
7248              * 1) If the register has both 32-bit and 64-bit instances then we
7249              *    can count on the 64-bit instance taking care of the
7250              *    non-secure bank.
7251              * 2) If ARMv8 is enabled then we can count on a 64-bit version
7252              *    taking care of the secure bank.  This requires that separate
7253              *    32 and 64-bit definitions are provided.
7254              */
7255             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
7256                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
7257                 r2->type |= ARM_CP_ALIAS;
7258             }
7259         } else if ((secstate != r->secure) && !ns) {
7260             /* The register is not banked so we only want to allow migration of
7261              * the non-secure instance.
7262              */
7263             r2->type |= ARM_CP_ALIAS;
7264         }
7265 
7266         if (r->state == ARM_CP_STATE_BOTH) {
7267             /* We assume it is a cp15 register if the .cp field is left unset.
7268              */
7269             if (r2->cp == 0) {
7270                 r2->cp = 15;
7271             }
7272 
7273 #ifdef HOST_WORDS_BIGENDIAN
7274             if (r2->fieldoffset) {
7275                 r2->fieldoffset += sizeof(uint32_t);
7276             }
7277 #endif
7278         }
7279     }
7280     if (state == ARM_CP_STATE_AA64) {
7281         /* To allow abbreviation of ARMCPRegInfo
7282          * definitions, we treat cp == 0 as equivalent to
7283          * the value for "standard guest-visible sysreg".
7284          * STATE_BOTH definitions are also always "standard
7285          * sysreg" in their AArch64 view (the .cp value may
7286          * be non-zero for the benefit of the AArch32 view).
7287          */
7288         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
7289             r2->cp = CP_REG_ARM64_SYSREG_CP;
7290         }
7291         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
7292                                   r2->opc0, opc1, opc2);
7293     } else {
7294         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
7295     }
7296     if (opaque) {
7297         r2->opaque = opaque;
7298     }
7299     /* reginfo passed to helpers is correct for the actual access,
7300      * and is never ARM_CP_STATE_BOTH:
7301      */
7302     r2->state = state;
7303     /* Make sure reginfo passed to helpers for wildcarded regs
7304      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
7305      */
7306     r2->crm = crm;
7307     r2->opc1 = opc1;
7308     r2->opc2 = opc2;
7309     /* By convention, for wildcarded registers only the first
7310      * entry is used for migration; the others are marked as
7311      * ALIAS so we don't try to transfer the register
7312      * multiple times. Special registers (ie NOP/WFI) are
7313      * never migratable and not even raw-accessible.
7314      */
7315     if ((r->type & ARM_CP_SPECIAL)) {
7316         r2->type |= ARM_CP_NO_RAW;
7317     }
7318     if (((r->crm == CP_ANY) && crm != 0) ||
7319         ((r->opc1 == CP_ANY) && opc1 != 0) ||
7320         ((r->opc2 == CP_ANY) && opc2 != 0)) {
7321         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
7322     }
7323 
7324     /* Check that raw accesses are either forbidden or handled. Note that
7325      * we can't assert this earlier because the setup of fieldoffset for
7326      * banked registers has to be done first.
7327      */
7328     if (!(r2->type & ARM_CP_NO_RAW)) {
7329         assert(!raw_accessors_invalid(r2));
7330     }
7331 
7332     /* Overriding of an existing definition must be explicitly
7333      * requested.
7334      */
7335     if (!(r->type & ARM_CP_OVERRIDE)) {
7336         ARMCPRegInfo *oldreg;
7337         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
7338         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
7339             fprintf(stderr, "Register redefined: cp=%d %d bit "
7340                     "crn=%d crm=%d opc1=%d opc2=%d, "
7341                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
7342                     r2->crn, r2->crm, r2->opc1, r2->opc2,
7343                     oldreg->name, r2->name);
7344             g_assert_not_reached();
7345         }
7346     }
7347     g_hash_table_insert(cpu->cp_regs, key, r2);
7348 }
7349 
7350 
7351 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
7352                                        const ARMCPRegInfo *r, void *opaque)
7353 {
7354     /* Define implementations of coprocessor registers.
7355      * We store these in a hashtable because typically
7356      * there are less than 150 registers in a space which
7357      * is 16*16*16*8*8 = 262144 in size.
7358      * Wildcarding is supported for the crm, opc1 and opc2 fields.
7359      * If a register is defined twice then the second definition is
7360      * used, so this can be used to define some generic registers and
7361      * then override them with implementation specific variations.
7362      * At least one of the original and the second definition should
7363      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
7364      * against accidental use.
7365      *
7366      * The state field defines whether the register is to be
7367      * visible in the AArch32 or AArch64 execution state. If the
7368      * state is set to ARM_CP_STATE_BOTH then we synthesise a
7369      * reginfo structure for the AArch32 view, which sees the lower
7370      * 32 bits of the 64 bit register.
7371      *
7372      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
7373      * be wildcarded. AArch64 registers are always considered to be 64
7374      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
7375      * the register, if any.
7376      */
7377     int crm, opc1, opc2, state;
7378     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
7379     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
7380     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
7381     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
7382     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
7383     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
7384     /* 64 bit registers have only CRm and Opc1 fields */
7385     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
7386     /* op0 only exists in the AArch64 encodings */
7387     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
7388     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
7389     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
7390     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
7391      * encodes a minimum access level for the register. We roll this
7392      * runtime check into our general permission check code, so check
7393      * here that the reginfo's specified permissions are strict enough
7394      * to encompass the generic architectural permission check.
7395      */
7396     if (r->state != ARM_CP_STATE_AA32) {
7397         int mask = 0;
7398         switch (r->opc1) {
7399         case 0:
7400             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
7401             mask = PL0U_R | PL1_RW;
7402             break;
7403         case 1: case 2:
7404             /* min_EL EL1 */
7405             mask = PL1_RW;
7406             break;
7407         case 3:
7408             /* min_EL EL0 */
7409             mask = PL0_RW;
7410             break;
7411         case 4:
7412             /* min_EL EL2 */
7413             mask = PL2_RW;
7414             break;
7415         case 5:
7416             /* unallocated encoding, so not possible */
7417             assert(false);
7418             break;
7419         case 6:
7420             /* min_EL EL3 */
7421             mask = PL3_RW;
7422             break;
7423         case 7:
7424             /* min_EL EL1, secure mode only (we don't check the latter) */
7425             mask = PL1_RW;
7426             break;
7427         default:
7428             /* broken reginfo with out-of-range opc1 */
7429             assert(false);
7430             break;
7431         }
7432         /* assert our permissions are not too lax (stricter is fine) */
7433         assert((r->access & ~mask) == 0);
7434     }
7435 
7436     /* Check that the register definition has enough info to handle
7437      * reads and writes if they are permitted.
7438      */
7439     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
7440         if (r->access & PL3_R) {
7441             assert((r->fieldoffset ||
7442                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7443                    r->readfn);
7444         }
7445         if (r->access & PL3_W) {
7446             assert((r->fieldoffset ||
7447                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7448                    r->writefn);
7449         }
7450     }
7451     /* Bad type field probably means missing sentinel at end of reg list */
7452     assert(cptype_valid(r->type));
7453     for (crm = crmmin; crm <= crmmax; crm++) {
7454         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
7455             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
7456                 for (state = ARM_CP_STATE_AA32;
7457                      state <= ARM_CP_STATE_AA64; state++) {
7458                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
7459                         continue;
7460                     }
7461                     if (state == ARM_CP_STATE_AA32) {
7462                         /* Under AArch32 CP registers can be common
7463                          * (same for secure and non-secure world) or banked.
7464                          */
7465                         char *name;
7466 
7467                         switch (r->secure) {
7468                         case ARM_CP_SECSTATE_S:
7469                         case ARM_CP_SECSTATE_NS:
7470                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7471                                                    r->secure, crm, opc1, opc2,
7472                                                    r->name);
7473                             break;
7474                         default:
7475                             name = g_strdup_printf("%s_S", r->name);
7476                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7477                                                    ARM_CP_SECSTATE_S,
7478                                                    crm, opc1, opc2, name);
7479                             g_free(name);
7480                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7481                                                    ARM_CP_SECSTATE_NS,
7482                                                    crm, opc1, opc2, r->name);
7483                             break;
7484                         }
7485                     } else {
7486                         /* AArch64 registers get mapped to non-secure instance
7487                          * of AArch32 */
7488                         add_cpreg_to_hashtable(cpu, r, opaque, state,
7489                                                ARM_CP_SECSTATE_NS,
7490                                                crm, opc1, opc2, r->name);
7491                     }
7492                 }
7493             }
7494         }
7495     }
7496 }
7497 
7498 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
7499                                     const ARMCPRegInfo *regs, void *opaque)
7500 {
7501     /* Define a whole list of registers */
7502     const ARMCPRegInfo *r;
7503     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7504         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
7505     }
7506 }
7507 
7508 /*
7509  * Modify ARMCPRegInfo for access from userspace.
7510  *
7511  * This is a data driven modification directed by
7512  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
7513  * user-space cannot alter any values and dynamic values pertaining to
7514  * execution state are hidden from user space view anyway.
7515  */
7516 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
7517 {
7518     const ARMCPRegUserSpaceInfo *m;
7519     ARMCPRegInfo *r;
7520 
7521     for (m = mods; m->name; m++) {
7522         GPatternSpec *pat = NULL;
7523         if (m->is_glob) {
7524             pat = g_pattern_spec_new(m->name);
7525         }
7526         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7527             if (pat && g_pattern_match_string(pat, r->name)) {
7528                 r->type = ARM_CP_CONST;
7529                 r->access = PL0U_R;
7530                 r->resetvalue = 0;
7531                 /* continue */
7532             } else if (strcmp(r->name, m->name) == 0) {
7533                 r->type = ARM_CP_CONST;
7534                 r->access = PL0U_R;
7535                 r->resetvalue &= m->exported_bits;
7536                 r->resetvalue |= m->fixed_bits;
7537                 break;
7538             }
7539         }
7540         if (pat) {
7541             g_pattern_spec_free(pat);
7542         }
7543     }
7544 }
7545 
7546 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
7547 {
7548     return g_hash_table_lookup(cpregs, &encoded_cp);
7549 }
7550 
7551 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
7552                          uint64_t value)
7553 {
7554     /* Helper coprocessor write function for write-ignore registers */
7555 }
7556 
7557 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
7558 {
7559     /* Helper coprocessor write function for read-as-zero registers */
7560     return 0;
7561 }
7562 
7563 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
7564 {
7565     /* Helper coprocessor reset function for do-nothing-on-reset registers */
7566 }
7567 
7568 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
7569 {
7570     /* Return true if it is not valid for us to switch to
7571      * this CPU mode (ie all the UNPREDICTABLE cases in
7572      * the ARM ARM CPSRWriteByInstr pseudocode).
7573      */
7574 
7575     /* Changes to or from Hyp via MSR and CPS are illegal. */
7576     if (write_type == CPSRWriteByInstr &&
7577         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
7578          mode == ARM_CPU_MODE_HYP)) {
7579         return 1;
7580     }
7581 
7582     switch (mode) {
7583     case ARM_CPU_MODE_USR:
7584         return 0;
7585     case ARM_CPU_MODE_SYS:
7586     case ARM_CPU_MODE_SVC:
7587     case ARM_CPU_MODE_ABT:
7588     case ARM_CPU_MODE_UND:
7589     case ARM_CPU_MODE_IRQ:
7590     case ARM_CPU_MODE_FIQ:
7591         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
7592          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
7593          */
7594         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
7595          * and CPS are treated as illegal mode changes.
7596          */
7597         if (write_type == CPSRWriteByInstr &&
7598             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
7599             (arm_hcr_el2_eff(env) & HCR_TGE)) {
7600             return 1;
7601         }
7602         return 0;
7603     case ARM_CPU_MODE_HYP:
7604         return !arm_feature(env, ARM_FEATURE_EL2)
7605             || arm_current_el(env) < 2 || arm_is_secure_below_el3(env);
7606     case ARM_CPU_MODE_MON:
7607         return arm_current_el(env) < 3;
7608     default:
7609         return 1;
7610     }
7611 }
7612 
7613 uint32_t cpsr_read(CPUARMState *env)
7614 {
7615     int ZF;
7616     ZF = (env->ZF == 0);
7617     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
7618         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
7619         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
7620         | ((env->condexec_bits & 0xfc) << 8)
7621         | (env->GE << 16) | (env->daif & CPSR_AIF);
7622 }
7623 
7624 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
7625                 CPSRWriteType write_type)
7626 {
7627     uint32_t changed_daif;
7628 
7629     if (mask & CPSR_NZCV) {
7630         env->ZF = (~val) & CPSR_Z;
7631         env->NF = val;
7632         env->CF = (val >> 29) & 1;
7633         env->VF = (val << 3) & 0x80000000;
7634     }
7635     if (mask & CPSR_Q)
7636         env->QF = ((val & CPSR_Q) != 0);
7637     if (mask & CPSR_T)
7638         env->thumb = ((val & CPSR_T) != 0);
7639     if (mask & CPSR_IT_0_1) {
7640         env->condexec_bits &= ~3;
7641         env->condexec_bits |= (val >> 25) & 3;
7642     }
7643     if (mask & CPSR_IT_2_7) {
7644         env->condexec_bits &= 3;
7645         env->condexec_bits |= (val >> 8) & 0xfc;
7646     }
7647     if (mask & CPSR_GE) {
7648         env->GE = (val >> 16) & 0xf;
7649     }
7650 
7651     /* In a V7 implementation that includes the security extensions but does
7652      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
7653      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
7654      * bits respectively.
7655      *
7656      * In a V8 implementation, it is permitted for privileged software to
7657      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
7658      */
7659     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
7660         arm_feature(env, ARM_FEATURE_EL3) &&
7661         !arm_feature(env, ARM_FEATURE_EL2) &&
7662         !arm_is_secure(env)) {
7663 
7664         changed_daif = (env->daif ^ val) & mask;
7665 
7666         if (changed_daif & CPSR_A) {
7667             /* Check to see if we are allowed to change the masking of async
7668              * abort exceptions from a non-secure state.
7669              */
7670             if (!(env->cp15.scr_el3 & SCR_AW)) {
7671                 qemu_log_mask(LOG_GUEST_ERROR,
7672                               "Ignoring attempt to switch CPSR_A flag from "
7673                               "non-secure world with SCR.AW bit clear\n");
7674                 mask &= ~CPSR_A;
7675             }
7676         }
7677 
7678         if (changed_daif & CPSR_F) {
7679             /* Check to see if we are allowed to change the masking of FIQ
7680              * exceptions from a non-secure state.
7681              */
7682             if (!(env->cp15.scr_el3 & SCR_FW)) {
7683                 qemu_log_mask(LOG_GUEST_ERROR,
7684                               "Ignoring attempt to switch CPSR_F flag from "
7685                               "non-secure world with SCR.FW bit clear\n");
7686                 mask &= ~CPSR_F;
7687             }
7688 
7689             /* Check whether non-maskable FIQ (NMFI) support is enabled.
7690              * If this bit is set software is not allowed to mask
7691              * FIQs, but is allowed to set CPSR_F to 0.
7692              */
7693             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
7694                 (val & CPSR_F)) {
7695                 qemu_log_mask(LOG_GUEST_ERROR,
7696                               "Ignoring attempt to enable CPSR_F flag "
7697                               "(non-maskable FIQ [NMFI] support enabled)\n");
7698                 mask &= ~CPSR_F;
7699             }
7700         }
7701     }
7702 
7703     env->daif &= ~(CPSR_AIF & mask);
7704     env->daif |= val & CPSR_AIF & mask;
7705 
7706     if (write_type != CPSRWriteRaw &&
7707         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
7708         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
7709             /* Note that we can only get here in USR mode if this is a
7710              * gdb stub write; for this case we follow the architectural
7711              * behaviour for guest writes in USR mode of ignoring an attempt
7712              * to switch mode. (Those are caught by translate.c for writes
7713              * triggered by guest instructions.)
7714              */
7715             mask &= ~CPSR_M;
7716         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
7717             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
7718              * v7, and has defined behaviour in v8:
7719              *  + leave CPSR.M untouched
7720              *  + allow changes to the other CPSR fields
7721              *  + set PSTATE.IL
7722              * For user changes via the GDB stub, we don't set PSTATE.IL,
7723              * as this would be unnecessarily harsh for a user error.
7724              */
7725             mask &= ~CPSR_M;
7726             if (write_type != CPSRWriteByGDBStub &&
7727                 arm_feature(env, ARM_FEATURE_V8)) {
7728                 mask |= CPSR_IL;
7729                 val |= CPSR_IL;
7730             }
7731             qemu_log_mask(LOG_GUEST_ERROR,
7732                           "Illegal AArch32 mode switch attempt from %s to %s\n",
7733                           aarch32_mode_name(env->uncached_cpsr),
7734                           aarch32_mode_name(val));
7735         } else {
7736             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
7737                           write_type == CPSRWriteExceptionReturn ?
7738                           "Exception return from AArch32" :
7739                           "AArch32 mode switch from",
7740                           aarch32_mode_name(env->uncached_cpsr),
7741                           aarch32_mode_name(val), env->regs[15]);
7742             switch_mode(env, val & CPSR_M);
7743         }
7744     }
7745     mask &= ~CACHED_CPSR_BITS;
7746     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
7747 }
7748 
7749 /* Sign/zero extend */
7750 uint32_t HELPER(sxtb16)(uint32_t x)
7751 {
7752     uint32_t res;
7753     res = (uint16_t)(int8_t)x;
7754     res |= (uint32_t)(int8_t)(x >> 16) << 16;
7755     return res;
7756 }
7757 
7758 uint32_t HELPER(uxtb16)(uint32_t x)
7759 {
7760     uint32_t res;
7761     res = (uint16_t)(uint8_t)x;
7762     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
7763     return res;
7764 }
7765 
7766 int32_t HELPER(sdiv)(int32_t num, int32_t den)
7767 {
7768     if (den == 0)
7769       return 0;
7770     if (num == INT_MIN && den == -1)
7771       return INT_MIN;
7772     return num / den;
7773 }
7774 
7775 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
7776 {
7777     if (den == 0)
7778       return 0;
7779     return num / den;
7780 }
7781 
7782 uint32_t HELPER(rbit)(uint32_t x)
7783 {
7784     return revbit32(x);
7785 }
7786 
7787 #ifdef CONFIG_USER_ONLY
7788 
7789 static void switch_mode(CPUARMState *env, int mode)
7790 {
7791     ARMCPU *cpu = env_archcpu(env);
7792 
7793     if (mode != ARM_CPU_MODE_USR) {
7794         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
7795     }
7796 }
7797 
7798 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7799                                  uint32_t cur_el, bool secure)
7800 {
7801     return 1;
7802 }
7803 
7804 void aarch64_sync_64_to_32(CPUARMState *env)
7805 {
7806     g_assert_not_reached();
7807 }
7808 
7809 #else
7810 
7811 static void switch_mode(CPUARMState *env, int mode)
7812 {
7813     int old_mode;
7814     int i;
7815 
7816     old_mode = env->uncached_cpsr & CPSR_M;
7817     if (mode == old_mode)
7818         return;
7819 
7820     if (old_mode == ARM_CPU_MODE_FIQ) {
7821         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
7822         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
7823     } else if (mode == ARM_CPU_MODE_FIQ) {
7824         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
7825         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
7826     }
7827 
7828     i = bank_number(old_mode);
7829     env->banked_r13[i] = env->regs[13];
7830     env->banked_spsr[i] = env->spsr;
7831 
7832     i = bank_number(mode);
7833     env->regs[13] = env->banked_r13[i];
7834     env->spsr = env->banked_spsr[i];
7835 
7836     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
7837     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
7838 }
7839 
7840 /* Physical Interrupt Target EL Lookup Table
7841  *
7842  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
7843  *
7844  * The below multi-dimensional table is used for looking up the target
7845  * exception level given numerous condition criteria.  Specifically, the
7846  * target EL is based on SCR and HCR routing controls as well as the
7847  * currently executing EL and secure state.
7848  *
7849  *    Dimensions:
7850  *    target_el_table[2][2][2][2][2][4]
7851  *                    |  |  |  |  |  +--- Current EL
7852  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
7853  *                    |  |  |  +--------- HCR mask override
7854  *                    |  |  +------------ SCR exec state control
7855  *                    |  +--------------- SCR mask override
7856  *                    +------------------ 32-bit(0)/64-bit(1) EL3
7857  *
7858  *    The table values are as such:
7859  *    0-3 = EL0-EL3
7860  *     -1 = Cannot occur
7861  *
7862  * The ARM ARM target EL table includes entries indicating that an "exception
7863  * is not taken".  The two cases where this is applicable are:
7864  *    1) An exception is taken from EL3 but the SCR does not have the exception
7865  *    routed to EL3.
7866  *    2) An exception is taken from EL2 but the HCR does not have the exception
7867  *    routed to EL2.
7868  * In these two cases, the below table contain a target of EL1.  This value is
7869  * returned as it is expected that the consumer of the table data will check
7870  * for "target EL >= current EL" to ensure the exception is not taken.
7871  *
7872  *            SCR     HCR
7873  *         64  EA     AMO                 From
7874  *        BIT IRQ     IMO      Non-secure         Secure
7875  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
7876  */
7877 static const int8_t target_el_table[2][2][2][2][2][4] = {
7878     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7879        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
7880       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7881        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
7882      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7883        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
7884       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7885        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
7886     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
7887        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
7888       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
7889        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
7890      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7891        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
7892       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7893        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
7894 };
7895 
7896 /*
7897  * Determine the target EL for physical exceptions
7898  */
7899 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7900                                  uint32_t cur_el, bool secure)
7901 {
7902     CPUARMState *env = cs->env_ptr;
7903     bool rw;
7904     bool scr;
7905     bool hcr;
7906     int target_el;
7907     /* Is the highest EL AArch64? */
7908     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
7909     uint64_t hcr_el2;
7910 
7911     if (arm_feature(env, ARM_FEATURE_EL3)) {
7912         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
7913     } else {
7914         /* Either EL2 is the highest EL (and so the EL2 register width
7915          * is given by is64); or there is no EL2 or EL3, in which case
7916          * the value of 'rw' does not affect the table lookup anyway.
7917          */
7918         rw = is64;
7919     }
7920 
7921     hcr_el2 = arm_hcr_el2_eff(env);
7922     switch (excp_idx) {
7923     case EXCP_IRQ:
7924         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
7925         hcr = hcr_el2 & HCR_IMO;
7926         break;
7927     case EXCP_FIQ:
7928         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
7929         hcr = hcr_el2 & HCR_FMO;
7930         break;
7931     default:
7932         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
7933         hcr = hcr_el2 & HCR_AMO;
7934         break;
7935     };
7936 
7937     /* Perform a table-lookup for the target EL given the current state */
7938     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
7939 
7940     assert(target_el > 0);
7941 
7942     return target_el;
7943 }
7944 
7945 void arm_log_exception(int idx)
7946 {
7947     if (qemu_loglevel_mask(CPU_LOG_INT)) {
7948         const char *exc = NULL;
7949         static const char * const excnames[] = {
7950             [EXCP_UDEF] = "Undefined Instruction",
7951             [EXCP_SWI] = "SVC",
7952             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
7953             [EXCP_DATA_ABORT] = "Data Abort",
7954             [EXCP_IRQ] = "IRQ",
7955             [EXCP_FIQ] = "FIQ",
7956             [EXCP_BKPT] = "Breakpoint",
7957             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
7958             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
7959             [EXCP_HVC] = "Hypervisor Call",
7960             [EXCP_HYP_TRAP] = "Hypervisor Trap",
7961             [EXCP_SMC] = "Secure Monitor Call",
7962             [EXCP_VIRQ] = "Virtual IRQ",
7963             [EXCP_VFIQ] = "Virtual FIQ",
7964             [EXCP_SEMIHOST] = "Semihosting call",
7965             [EXCP_NOCP] = "v7M NOCP UsageFault",
7966             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
7967             [EXCP_STKOF] = "v8M STKOF UsageFault",
7968             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
7969             [EXCP_LSERR] = "v8M LSERR UsageFault",
7970             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
7971         };
7972 
7973         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
7974             exc = excnames[idx];
7975         }
7976         if (!exc) {
7977             exc = "unknown";
7978         }
7979         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
7980     }
7981 }
7982 
7983 /*
7984  * Function used to synchronize QEMU's AArch64 register set with AArch32
7985  * register set.  This is necessary when switching between AArch32 and AArch64
7986  * execution state.
7987  */
7988 void aarch64_sync_32_to_64(CPUARMState *env)
7989 {
7990     int i;
7991     uint32_t mode = env->uncached_cpsr & CPSR_M;
7992 
7993     /* We can blanket copy R[0:7] to X[0:7] */
7994     for (i = 0; i < 8; i++) {
7995         env->xregs[i] = env->regs[i];
7996     }
7997 
7998     /*
7999      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
8000      * Otherwise, they come from the banked user regs.
8001      */
8002     if (mode == ARM_CPU_MODE_FIQ) {
8003         for (i = 8; i < 13; i++) {
8004             env->xregs[i] = env->usr_regs[i - 8];
8005         }
8006     } else {
8007         for (i = 8; i < 13; i++) {
8008             env->xregs[i] = env->regs[i];
8009         }
8010     }
8011 
8012     /*
8013      * Registers x13-x23 are the various mode SP and FP registers. Registers
8014      * r13 and r14 are only copied if we are in that mode, otherwise we copy
8015      * from the mode banked register.
8016      */
8017     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
8018         env->xregs[13] = env->regs[13];
8019         env->xregs[14] = env->regs[14];
8020     } else {
8021         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
8022         /* HYP is an exception in that it is copied from r14 */
8023         if (mode == ARM_CPU_MODE_HYP) {
8024             env->xregs[14] = env->regs[14];
8025         } else {
8026             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
8027         }
8028     }
8029 
8030     if (mode == ARM_CPU_MODE_HYP) {
8031         env->xregs[15] = env->regs[13];
8032     } else {
8033         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
8034     }
8035 
8036     if (mode == ARM_CPU_MODE_IRQ) {
8037         env->xregs[16] = env->regs[14];
8038         env->xregs[17] = env->regs[13];
8039     } else {
8040         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
8041         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
8042     }
8043 
8044     if (mode == ARM_CPU_MODE_SVC) {
8045         env->xregs[18] = env->regs[14];
8046         env->xregs[19] = env->regs[13];
8047     } else {
8048         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
8049         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
8050     }
8051 
8052     if (mode == ARM_CPU_MODE_ABT) {
8053         env->xregs[20] = env->regs[14];
8054         env->xregs[21] = env->regs[13];
8055     } else {
8056         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
8057         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
8058     }
8059 
8060     if (mode == ARM_CPU_MODE_UND) {
8061         env->xregs[22] = env->regs[14];
8062         env->xregs[23] = env->regs[13];
8063     } else {
8064         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
8065         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
8066     }
8067 
8068     /*
8069      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
8070      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
8071      * FIQ bank for r8-r14.
8072      */
8073     if (mode == ARM_CPU_MODE_FIQ) {
8074         for (i = 24; i < 31; i++) {
8075             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
8076         }
8077     } else {
8078         for (i = 24; i < 29; i++) {
8079             env->xregs[i] = env->fiq_regs[i - 24];
8080         }
8081         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
8082         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
8083     }
8084 
8085     env->pc = env->regs[15];
8086 }
8087 
8088 /*
8089  * Function used to synchronize QEMU's AArch32 register set with AArch64
8090  * register set.  This is necessary when switching between AArch32 and AArch64
8091  * execution state.
8092  */
8093 void aarch64_sync_64_to_32(CPUARMState *env)
8094 {
8095     int i;
8096     uint32_t mode = env->uncached_cpsr & CPSR_M;
8097 
8098     /* We can blanket copy X[0:7] to R[0:7] */
8099     for (i = 0; i < 8; i++) {
8100         env->regs[i] = env->xregs[i];
8101     }
8102 
8103     /*
8104      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
8105      * Otherwise, we copy x8-x12 into the banked user regs.
8106      */
8107     if (mode == ARM_CPU_MODE_FIQ) {
8108         for (i = 8; i < 13; i++) {
8109             env->usr_regs[i - 8] = env->xregs[i];
8110         }
8111     } else {
8112         for (i = 8; i < 13; i++) {
8113             env->regs[i] = env->xregs[i];
8114         }
8115     }
8116 
8117     /*
8118      * Registers r13 & r14 depend on the current mode.
8119      * If we are in a given mode, we copy the corresponding x registers to r13
8120      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
8121      * for the mode.
8122      */
8123     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
8124         env->regs[13] = env->xregs[13];
8125         env->regs[14] = env->xregs[14];
8126     } else {
8127         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
8128 
8129         /*
8130          * HYP is an exception in that it does not have its own banked r14 but
8131          * shares the USR r14
8132          */
8133         if (mode == ARM_CPU_MODE_HYP) {
8134             env->regs[14] = env->xregs[14];
8135         } else {
8136             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
8137         }
8138     }
8139 
8140     if (mode == ARM_CPU_MODE_HYP) {
8141         env->regs[13] = env->xregs[15];
8142     } else {
8143         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
8144     }
8145 
8146     if (mode == ARM_CPU_MODE_IRQ) {
8147         env->regs[14] = env->xregs[16];
8148         env->regs[13] = env->xregs[17];
8149     } else {
8150         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
8151         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
8152     }
8153 
8154     if (mode == ARM_CPU_MODE_SVC) {
8155         env->regs[14] = env->xregs[18];
8156         env->regs[13] = env->xregs[19];
8157     } else {
8158         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
8159         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
8160     }
8161 
8162     if (mode == ARM_CPU_MODE_ABT) {
8163         env->regs[14] = env->xregs[20];
8164         env->regs[13] = env->xregs[21];
8165     } else {
8166         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
8167         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
8168     }
8169 
8170     if (mode == ARM_CPU_MODE_UND) {
8171         env->regs[14] = env->xregs[22];
8172         env->regs[13] = env->xregs[23];
8173     } else {
8174         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
8175         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
8176     }
8177 
8178     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
8179      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
8180      * FIQ bank for r8-r14.
8181      */
8182     if (mode == ARM_CPU_MODE_FIQ) {
8183         for (i = 24; i < 31; i++) {
8184             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
8185         }
8186     } else {
8187         for (i = 24; i < 29; i++) {
8188             env->fiq_regs[i - 24] = env->xregs[i];
8189         }
8190         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
8191         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
8192     }
8193 
8194     env->regs[15] = env->pc;
8195 }
8196 
8197 static void take_aarch32_exception(CPUARMState *env, int new_mode,
8198                                    uint32_t mask, uint32_t offset,
8199                                    uint32_t newpc)
8200 {
8201     /* Change the CPU state so as to actually take the exception. */
8202     switch_mode(env, new_mode);
8203     /*
8204      * For exceptions taken to AArch32 we must clear the SS bit in both
8205      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
8206      */
8207     env->uncached_cpsr &= ~PSTATE_SS;
8208     env->spsr = cpsr_read(env);
8209     /* Clear IT bits.  */
8210     env->condexec_bits = 0;
8211     /* Switch to the new mode, and to the correct instruction set.  */
8212     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
8213     /* Set new mode endianness */
8214     env->uncached_cpsr &= ~CPSR_E;
8215     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
8216         env->uncached_cpsr |= CPSR_E;
8217     }
8218     /* J and IL must always be cleared for exception entry */
8219     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
8220     env->daif |= mask;
8221 
8222     if (new_mode == ARM_CPU_MODE_HYP) {
8223         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
8224         env->elr_el[2] = env->regs[15];
8225     } else {
8226         /*
8227          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
8228          * and we should just guard the thumb mode on V4
8229          */
8230         if (arm_feature(env, ARM_FEATURE_V4T)) {
8231             env->thumb =
8232                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
8233         }
8234         env->regs[14] = env->regs[15] + offset;
8235     }
8236     env->regs[15] = newpc;
8237     arm_rebuild_hflags(env);
8238 }
8239 
8240 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
8241 {
8242     /*
8243      * Handle exception entry to Hyp mode; this is sufficiently
8244      * different to entry to other AArch32 modes that we handle it
8245      * separately here.
8246      *
8247      * The vector table entry used is always the 0x14 Hyp mode entry point,
8248      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
8249      * The offset applied to the preferred return address is always zero
8250      * (see DDI0487C.a section G1.12.3).
8251      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
8252      */
8253     uint32_t addr, mask;
8254     ARMCPU *cpu = ARM_CPU(cs);
8255     CPUARMState *env = &cpu->env;
8256 
8257     switch (cs->exception_index) {
8258     case EXCP_UDEF:
8259         addr = 0x04;
8260         break;
8261     case EXCP_SWI:
8262         addr = 0x14;
8263         break;
8264     case EXCP_BKPT:
8265         /* Fall through to prefetch abort.  */
8266     case EXCP_PREFETCH_ABORT:
8267         env->cp15.ifar_s = env->exception.vaddress;
8268         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
8269                       (uint32_t)env->exception.vaddress);
8270         addr = 0x0c;
8271         break;
8272     case EXCP_DATA_ABORT:
8273         env->cp15.dfar_s = env->exception.vaddress;
8274         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
8275                       (uint32_t)env->exception.vaddress);
8276         addr = 0x10;
8277         break;
8278     case EXCP_IRQ:
8279         addr = 0x18;
8280         break;
8281     case EXCP_FIQ:
8282         addr = 0x1c;
8283         break;
8284     case EXCP_HVC:
8285         addr = 0x08;
8286         break;
8287     case EXCP_HYP_TRAP:
8288         addr = 0x14;
8289         break;
8290     default:
8291         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8292     }
8293 
8294     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
8295         if (!arm_feature(env, ARM_FEATURE_V8)) {
8296             /*
8297              * QEMU syndrome values are v8-style. v7 has the IL bit
8298              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
8299              * If this is a v7 CPU, squash the IL bit in those cases.
8300              */
8301             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
8302                 (cs->exception_index == EXCP_DATA_ABORT &&
8303                  !(env->exception.syndrome & ARM_EL_ISV)) ||
8304                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
8305                 env->exception.syndrome &= ~ARM_EL_IL;
8306             }
8307         }
8308         env->cp15.esr_el[2] = env->exception.syndrome;
8309     }
8310 
8311     if (arm_current_el(env) != 2 && addr < 0x14) {
8312         addr = 0x14;
8313     }
8314 
8315     mask = 0;
8316     if (!(env->cp15.scr_el3 & SCR_EA)) {
8317         mask |= CPSR_A;
8318     }
8319     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
8320         mask |= CPSR_I;
8321     }
8322     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
8323         mask |= CPSR_F;
8324     }
8325 
8326     addr += env->cp15.hvbar;
8327 
8328     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
8329 }
8330 
8331 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
8332 {
8333     ARMCPU *cpu = ARM_CPU(cs);
8334     CPUARMState *env = &cpu->env;
8335     uint32_t addr;
8336     uint32_t mask;
8337     int new_mode;
8338     uint32_t offset;
8339     uint32_t moe;
8340 
8341     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
8342     switch (syn_get_ec(env->exception.syndrome)) {
8343     case EC_BREAKPOINT:
8344     case EC_BREAKPOINT_SAME_EL:
8345         moe = 1;
8346         break;
8347     case EC_WATCHPOINT:
8348     case EC_WATCHPOINT_SAME_EL:
8349         moe = 10;
8350         break;
8351     case EC_AA32_BKPT:
8352         moe = 3;
8353         break;
8354     case EC_VECTORCATCH:
8355         moe = 5;
8356         break;
8357     default:
8358         moe = 0;
8359         break;
8360     }
8361 
8362     if (moe) {
8363         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
8364     }
8365 
8366     if (env->exception.target_el == 2) {
8367         arm_cpu_do_interrupt_aarch32_hyp(cs);
8368         return;
8369     }
8370 
8371     switch (cs->exception_index) {
8372     case EXCP_UDEF:
8373         new_mode = ARM_CPU_MODE_UND;
8374         addr = 0x04;
8375         mask = CPSR_I;
8376         if (env->thumb)
8377             offset = 2;
8378         else
8379             offset = 4;
8380         break;
8381     case EXCP_SWI:
8382         new_mode = ARM_CPU_MODE_SVC;
8383         addr = 0x08;
8384         mask = CPSR_I;
8385         /* The PC already points to the next instruction.  */
8386         offset = 0;
8387         break;
8388     case EXCP_BKPT:
8389         /* Fall through to prefetch abort.  */
8390     case EXCP_PREFETCH_ABORT:
8391         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
8392         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
8393         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
8394                       env->exception.fsr, (uint32_t)env->exception.vaddress);
8395         new_mode = ARM_CPU_MODE_ABT;
8396         addr = 0x0c;
8397         mask = CPSR_A | CPSR_I;
8398         offset = 4;
8399         break;
8400     case EXCP_DATA_ABORT:
8401         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
8402         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
8403         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
8404                       env->exception.fsr,
8405                       (uint32_t)env->exception.vaddress);
8406         new_mode = ARM_CPU_MODE_ABT;
8407         addr = 0x10;
8408         mask = CPSR_A | CPSR_I;
8409         offset = 8;
8410         break;
8411     case EXCP_IRQ:
8412         new_mode = ARM_CPU_MODE_IRQ;
8413         addr = 0x18;
8414         /* Disable IRQ and imprecise data aborts.  */
8415         mask = CPSR_A | CPSR_I;
8416         offset = 4;
8417         if (env->cp15.scr_el3 & SCR_IRQ) {
8418             /* IRQ routed to monitor mode */
8419             new_mode = ARM_CPU_MODE_MON;
8420             mask |= CPSR_F;
8421         }
8422         break;
8423     case EXCP_FIQ:
8424         new_mode = ARM_CPU_MODE_FIQ;
8425         addr = 0x1c;
8426         /* Disable FIQ, IRQ and imprecise data aborts.  */
8427         mask = CPSR_A | CPSR_I | CPSR_F;
8428         if (env->cp15.scr_el3 & SCR_FIQ) {
8429             /* FIQ routed to monitor mode */
8430             new_mode = ARM_CPU_MODE_MON;
8431         }
8432         offset = 4;
8433         break;
8434     case EXCP_VIRQ:
8435         new_mode = ARM_CPU_MODE_IRQ;
8436         addr = 0x18;
8437         /* Disable IRQ and imprecise data aborts.  */
8438         mask = CPSR_A | CPSR_I;
8439         offset = 4;
8440         break;
8441     case EXCP_VFIQ:
8442         new_mode = ARM_CPU_MODE_FIQ;
8443         addr = 0x1c;
8444         /* Disable FIQ, IRQ and imprecise data aborts.  */
8445         mask = CPSR_A | CPSR_I | CPSR_F;
8446         offset = 4;
8447         break;
8448     case EXCP_SMC:
8449         new_mode = ARM_CPU_MODE_MON;
8450         addr = 0x08;
8451         mask = CPSR_A | CPSR_I | CPSR_F;
8452         offset = 0;
8453         break;
8454     default:
8455         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8456         return; /* Never happens.  Keep compiler happy.  */
8457     }
8458 
8459     if (new_mode == ARM_CPU_MODE_MON) {
8460         addr += env->cp15.mvbar;
8461     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
8462         /* High vectors. When enabled, base address cannot be remapped. */
8463         addr += 0xffff0000;
8464     } else {
8465         /* ARM v7 architectures provide a vector base address register to remap
8466          * the interrupt vector table.
8467          * This register is only followed in non-monitor mode, and is banked.
8468          * Note: only bits 31:5 are valid.
8469          */
8470         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
8471     }
8472 
8473     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
8474         env->cp15.scr_el3 &= ~SCR_NS;
8475     }
8476 
8477     take_aarch32_exception(env, new_mode, mask, offset, addr);
8478 }
8479 
8480 /* Handle exception entry to a target EL which is using AArch64 */
8481 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
8482 {
8483     ARMCPU *cpu = ARM_CPU(cs);
8484     CPUARMState *env = &cpu->env;
8485     unsigned int new_el = env->exception.target_el;
8486     target_ulong addr = env->cp15.vbar_el[new_el];
8487     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
8488     unsigned int cur_el = arm_current_el(env);
8489 
8490     /*
8491      * Note that new_el can never be 0.  If cur_el is 0, then
8492      * el0_a64 is is_a64(), else el0_a64 is ignored.
8493      */
8494     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
8495 
8496     if (cur_el < new_el) {
8497         /* Entry vector offset depends on whether the implemented EL
8498          * immediately lower than the target level is using AArch32 or AArch64
8499          */
8500         bool is_aa64;
8501 
8502         switch (new_el) {
8503         case 3:
8504             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
8505             break;
8506         case 2:
8507             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
8508             break;
8509         case 1:
8510             is_aa64 = is_a64(env);
8511             break;
8512         default:
8513             g_assert_not_reached();
8514         }
8515 
8516         if (is_aa64) {
8517             addr += 0x400;
8518         } else {
8519             addr += 0x600;
8520         }
8521     } else if (pstate_read(env) & PSTATE_SP) {
8522         addr += 0x200;
8523     }
8524 
8525     switch (cs->exception_index) {
8526     case EXCP_PREFETCH_ABORT:
8527     case EXCP_DATA_ABORT:
8528         env->cp15.far_el[new_el] = env->exception.vaddress;
8529         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
8530                       env->cp15.far_el[new_el]);
8531         /* fall through */
8532     case EXCP_BKPT:
8533     case EXCP_UDEF:
8534     case EXCP_SWI:
8535     case EXCP_HVC:
8536     case EXCP_HYP_TRAP:
8537     case EXCP_SMC:
8538         if (syn_get_ec(env->exception.syndrome) == EC_ADVSIMDFPACCESSTRAP) {
8539             /*
8540              * QEMU internal FP/SIMD syndromes from AArch32 include the
8541              * TA and coproc fields which are only exposed if the exception
8542              * is taken to AArch32 Hyp mode. Mask them out to get a valid
8543              * AArch64 format syndrome.
8544              */
8545             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
8546         }
8547         env->cp15.esr_el[new_el] = env->exception.syndrome;
8548         break;
8549     case EXCP_IRQ:
8550     case EXCP_VIRQ:
8551         addr += 0x80;
8552         break;
8553     case EXCP_FIQ:
8554     case EXCP_VFIQ:
8555         addr += 0x100;
8556         break;
8557     case EXCP_SEMIHOST:
8558         qemu_log_mask(CPU_LOG_INT,
8559                       "...handling as semihosting call 0x%" PRIx64 "\n",
8560                       env->xregs[0]);
8561         env->xregs[0] = do_arm_semihosting(env);
8562         return;
8563     default:
8564         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8565     }
8566 
8567     if (is_a64(env)) {
8568         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
8569         aarch64_save_sp(env, arm_current_el(env));
8570         env->elr_el[new_el] = env->pc;
8571     } else {
8572         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
8573         env->elr_el[new_el] = env->regs[15];
8574 
8575         aarch64_sync_32_to_64(env);
8576 
8577         env->condexec_bits = 0;
8578     }
8579     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
8580                   env->elr_el[new_el]);
8581 
8582     pstate_write(env, PSTATE_DAIF | new_mode);
8583     env->aarch64 = 1;
8584     aarch64_restore_sp(env, new_el);
8585     helper_rebuild_hflags_a64(env, new_el);
8586 
8587     env->pc = addr;
8588 
8589     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
8590                   new_el, env->pc, pstate_read(env));
8591 }
8592 
8593 /*
8594  * Do semihosting call and set the appropriate return value. All the
8595  * permission and validity checks have been done at translate time.
8596  *
8597  * We only see semihosting exceptions in TCG only as they are not
8598  * trapped to the hypervisor in KVM.
8599  */
8600 #ifdef CONFIG_TCG
8601 static void handle_semihosting(CPUState *cs)
8602 {
8603     ARMCPU *cpu = ARM_CPU(cs);
8604     CPUARMState *env = &cpu->env;
8605 
8606     if (is_a64(env)) {
8607         qemu_log_mask(CPU_LOG_INT,
8608                       "...handling as semihosting call 0x%" PRIx64 "\n",
8609                       env->xregs[0]);
8610         env->xregs[0] = do_arm_semihosting(env);
8611     } else {
8612         qemu_log_mask(CPU_LOG_INT,
8613                       "...handling as semihosting call 0x%x\n",
8614                       env->regs[0]);
8615         env->regs[0] = do_arm_semihosting(env);
8616     }
8617 }
8618 #endif
8619 
8620 /* Handle a CPU exception for A and R profile CPUs.
8621  * Do any appropriate logging, handle PSCI calls, and then hand off
8622  * to the AArch64-entry or AArch32-entry function depending on the
8623  * target exception level's register width.
8624  */
8625 void arm_cpu_do_interrupt(CPUState *cs)
8626 {
8627     ARMCPU *cpu = ARM_CPU(cs);
8628     CPUARMState *env = &cpu->env;
8629     unsigned int new_el = env->exception.target_el;
8630 
8631     assert(!arm_feature(env, ARM_FEATURE_M));
8632 
8633     arm_log_exception(cs->exception_index);
8634     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
8635                   new_el);
8636     if (qemu_loglevel_mask(CPU_LOG_INT)
8637         && !excp_is_internal(cs->exception_index)) {
8638         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
8639                       syn_get_ec(env->exception.syndrome),
8640                       env->exception.syndrome);
8641     }
8642 
8643     if (arm_is_psci_call(cpu, cs->exception_index)) {
8644         arm_handle_psci_call(cpu);
8645         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
8646         return;
8647     }
8648 
8649     /*
8650      * Semihosting semantics depend on the register width of the code
8651      * that caused the exception, not the target exception level, so
8652      * must be handled here.
8653      */
8654 #ifdef CONFIG_TCG
8655     if (cs->exception_index == EXCP_SEMIHOST) {
8656         handle_semihosting(cs);
8657         return;
8658     }
8659 #endif
8660 
8661     /* Hooks may change global state so BQL should be held, also the
8662      * BQL needs to be held for any modification of
8663      * cs->interrupt_request.
8664      */
8665     g_assert(qemu_mutex_iothread_locked());
8666 
8667     arm_call_pre_el_change_hook(cpu);
8668 
8669     assert(!excp_is_internal(cs->exception_index));
8670     if (arm_el_is_aa64(env, new_el)) {
8671         arm_cpu_do_interrupt_aarch64(cs);
8672     } else {
8673         arm_cpu_do_interrupt_aarch32(cs);
8674     }
8675 
8676     arm_call_el_change_hook(cpu);
8677 
8678     if (!kvm_enabled()) {
8679         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
8680     }
8681 }
8682 #endif /* !CONFIG_USER_ONLY */
8683 
8684 /* Return the exception level which controls this address translation regime */
8685 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
8686 {
8687     switch (mmu_idx) {
8688     case ARMMMUIdx_S2NS:
8689     case ARMMMUIdx_S1E2:
8690         return 2;
8691     case ARMMMUIdx_S1E3:
8692         return 3;
8693     case ARMMMUIdx_S1SE0:
8694         return arm_el_is_aa64(env, 3) ? 1 : 3;
8695     case ARMMMUIdx_S1SE1:
8696     case ARMMMUIdx_S1NSE0:
8697     case ARMMMUIdx_S1NSE1:
8698     case ARMMMUIdx_MPrivNegPri:
8699     case ARMMMUIdx_MUserNegPri:
8700     case ARMMMUIdx_MPriv:
8701     case ARMMMUIdx_MUser:
8702     case ARMMMUIdx_MSPrivNegPri:
8703     case ARMMMUIdx_MSUserNegPri:
8704     case ARMMMUIdx_MSPriv:
8705     case ARMMMUIdx_MSUser:
8706         return 1;
8707     default:
8708         g_assert_not_reached();
8709     }
8710 }
8711 
8712 #ifndef CONFIG_USER_ONLY
8713 
8714 /* Return the SCTLR value which controls this address translation regime */
8715 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
8716 {
8717     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
8718 }
8719 
8720 /* Return true if the specified stage of address translation is disabled */
8721 static inline bool regime_translation_disabled(CPUARMState *env,
8722                                                ARMMMUIdx mmu_idx)
8723 {
8724     if (arm_feature(env, ARM_FEATURE_M)) {
8725         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
8726                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
8727         case R_V7M_MPU_CTRL_ENABLE_MASK:
8728             /* Enabled, but not for HardFault and NMI */
8729             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
8730         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
8731             /* Enabled for all cases */
8732             return false;
8733         case 0:
8734         default:
8735             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
8736              * we warned about that in armv7m_nvic.c when the guest set it.
8737              */
8738             return true;
8739         }
8740     }
8741 
8742     if (mmu_idx == ARMMMUIdx_S2NS) {
8743         /* HCR.DC means HCR.VM behaves as 1 */
8744         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
8745     }
8746 
8747     if (env->cp15.hcr_el2 & HCR_TGE) {
8748         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
8749         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
8750             return true;
8751         }
8752     }
8753 
8754     if ((env->cp15.hcr_el2 & HCR_DC) &&
8755         (mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1)) {
8756         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
8757         return true;
8758     }
8759 
8760     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
8761 }
8762 
8763 static inline bool regime_translation_big_endian(CPUARMState *env,
8764                                                  ARMMMUIdx mmu_idx)
8765 {
8766     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
8767 }
8768 
8769 /* Return the TTBR associated with this translation regime */
8770 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
8771                                    int ttbrn)
8772 {
8773     if (mmu_idx == ARMMMUIdx_S2NS) {
8774         return env->cp15.vttbr_el2;
8775     }
8776     if (ttbrn == 0) {
8777         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
8778     } else {
8779         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
8780     }
8781 }
8782 
8783 #endif /* !CONFIG_USER_ONLY */
8784 
8785 /* Return the TCR controlling this translation regime */
8786 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
8787 {
8788     if (mmu_idx == ARMMMUIdx_S2NS) {
8789         return &env->cp15.vtcr_el2;
8790     }
8791     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
8792 }
8793 
8794 /* Convert a possible stage1+2 MMU index into the appropriate
8795  * stage 1 MMU index
8796  */
8797 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
8798 {
8799     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
8800         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
8801     }
8802     return mmu_idx;
8803 }
8804 
8805 /* Return true if the translation regime is using LPAE format page tables */
8806 static inline bool regime_using_lpae_format(CPUARMState *env,
8807                                             ARMMMUIdx mmu_idx)
8808 {
8809     int el = regime_el(env, mmu_idx);
8810     if (el == 2 || arm_el_is_aa64(env, el)) {
8811         return true;
8812     }
8813     if (arm_feature(env, ARM_FEATURE_LPAE)
8814         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
8815         return true;
8816     }
8817     return false;
8818 }
8819 
8820 /* Returns true if the stage 1 translation regime is using LPAE format page
8821  * tables. Used when raising alignment exceptions, whose FSR changes depending
8822  * on whether the long or short descriptor format is in use. */
8823 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
8824 {
8825     mmu_idx = stage_1_mmu_idx(mmu_idx);
8826 
8827     return regime_using_lpae_format(env, mmu_idx);
8828 }
8829 
8830 #ifndef CONFIG_USER_ONLY
8831 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
8832 {
8833     switch (mmu_idx) {
8834     case ARMMMUIdx_S1SE0:
8835     case ARMMMUIdx_S1NSE0:
8836     case ARMMMUIdx_MUser:
8837     case ARMMMUIdx_MSUser:
8838     case ARMMMUIdx_MUserNegPri:
8839     case ARMMMUIdx_MSUserNegPri:
8840         return true;
8841     default:
8842         return false;
8843     case ARMMMUIdx_S12NSE0:
8844     case ARMMMUIdx_S12NSE1:
8845         g_assert_not_reached();
8846     }
8847 }
8848 
8849 /* Translate section/page access permissions to page
8850  * R/W protection flags
8851  *
8852  * @env:         CPUARMState
8853  * @mmu_idx:     MMU index indicating required translation regime
8854  * @ap:          The 3-bit access permissions (AP[2:0])
8855  * @domain_prot: The 2-bit domain access permissions
8856  */
8857 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
8858                                 int ap, int domain_prot)
8859 {
8860     bool is_user = regime_is_user(env, mmu_idx);
8861 
8862     if (domain_prot == 3) {
8863         return PAGE_READ | PAGE_WRITE;
8864     }
8865 
8866     switch (ap) {
8867     case 0:
8868         if (arm_feature(env, ARM_FEATURE_V7)) {
8869             return 0;
8870         }
8871         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
8872         case SCTLR_S:
8873             return is_user ? 0 : PAGE_READ;
8874         case SCTLR_R:
8875             return PAGE_READ;
8876         default:
8877             return 0;
8878         }
8879     case 1:
8880         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8881     case 2:
8882         if (is_user) {
8883             return PAGE_READ;
8884         } else {
8885             return PAGE_READ | PAGE_WRITE;
8886         }
8887     case 3:
8888         return PAGE_READ | PAGE_WRITE;
8889     case 4: /* Reserved.  */
8890         return 0;
8891     case 5:
8892         return is_user ? 0 : PAGE_READ;
8893     case 6:
8894         return PAGE_READ;
8895     case 7:
8896         if (!arm_feature(env, ARM_FEATURE_V6K)) {
8897             return 0;
8898         }
8899         return PAGE_READ;
8900     default:
8901         g_assert_not_reached();
8902     }
8903 }
8904 
8905 /* Translate section/page access permissions to page
8906  * R/W protection flags.
8907  *
8908  * @ap:      The 2-bit simple AP (AP[2:1])
8909  * @is_user: TRUE if accessing from PL0
8910  */
8911 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
8912 {
8913     switch (ap) {
8914     case 0:
8915         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8916     case 1:
8917         return PAGE_READ | PAGE_WRITE;
8918     case 2:
8919         return is_user ? 0 : PAGE_READ;
8920     case 3:
8921         return PAGE_READ;
8922     default:
8923         g_assert_not_reached();
8924     }
8925 }
8926 
8927 static inline int
8928 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
8929 {
8930     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
8931 }
8932 
8933 /* Translate S2 section/page access permissions to protection flags
8934  *
8935  * @env:     CPUARMState
8936  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
8937  * @xn:      XN (execute-never) bit
8938  */
8939 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
8940 {
8941     int prot = 0;
8942 
8943     if (s2ap & 1) {
8944         prot |= PAGE_READ;
8945     }
8946     if (s2ap & 2) {
8947         prot |= PAGE_WRITE;
8948     }
8949     if (!xn) {
8950         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
8951             prot |= PAGE_EXEC;
8952         }
8953     }
8954     return prot;
8955 }
8956 
8957 /* Translate section/page access permissions to protection flags
8958  *
8959  * @env:     CPUARMState
8960  * @mmu_idx: MMU index indicating required translation regime
8961  * @is_aa64: TRUE if AArch64
8962  * @ap:      The 2-bit simple AP (AP[2:1])
8963  * @ns:      NS (non-secure) bit
8964  * @xn:      XN (execute-never) bit
8965  * @pxn:     PXN (privileged execute-never) bit
8966  */
8967 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
8968                       int ap, int ns, int xn, int pxn)
8969 {
8970     bool is_user = regime_is_user(env, mmu_idx);
8971     int prot_rw, user_rw;
8972     bool have_wxn;
8973     int wxn = 0;
8974 
8975     assert(mmu_idx != ARMMMUIdx_S2NS);
8976 
8977     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
8978     if (is_user) {
8979         prot_rw = user_rw;
8980     } else {
8981         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
8982     }
8983 
8984     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
8985         return prot_rw;
8986     }
8987 
8988     /* TODO have_wxn should be replaced with
8989      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
8990      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
8991      * compatible processors have EL2, which is required for [U]WXN.
8992      */
8993     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
8994 
8995     if (have_wxn) {
8996         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
8997     }
8998 
8999     if (is_aa64) {
9000         switch (regime_el(env, mmu_idx)) {
9001         case 1:
9002             if (!is_user) {
9003                 xn = pxn || (user_rw & PAGE_WRITE);
9004             }
9005             break;
9006         case 2:
9007         case 3:
9008             break;
9009         }
9010     } else if (arm_feature(env, ARM_FEATURE_V7)) {
9011         switch (regime_el(env, mmu_idx)) {
9012         case 1:
9013         case 3:
9014             if (is_user) {
9015                 xn = xn || !(user_rw & PAGE_READ);
9016             } else {
9017                 int uwxn = 0;
9018                 if (have_wxn) {
9019                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
9020                 }
9021                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
9022                      (uwxn && (user_rw & PAGE_WRITE));
9023             }
9024             break;
9025         case 2:
9026             break;
9027         }
9028     } else {
9029         xn = wxn = 0;
9030     }
9031 
9032     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
9033         return prot_rw;
9034     }
9035     return prot_rw | PAGE_EXEC;
9036 }
9037 
9038 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
9039                                      uint32_t *table, uint32_t address)
9040 {
9041     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
9042     TCR *tcr = regime_tcr(env, mmu_idx);
9043 
9044     if (address & tcr->mask) {
9045         if (tcr->raw_tcr & TTBCR_PD1) {
9046             /* Translation table walk disabled for TTBR1 */
9047             return false;
9048         }
9049         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
9050     } else {
9051         if (tcr->raw_tcr & TTBCR_PD0) {
9052             /* Translation table walk disabled for TTBR0 */
9053             return false;
9054         }
9055         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
9056     }
9057     *table |= (address >> 18) & 0x3ffc;
9058     return true;
9059 }
9060 
9061 /* Translate a S1 pagetable walk through S2 if needed.  */
9062 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
9063                                hwaddr addr, MemTxAttrs txattrs,
9064                                ARMMMUFaultInfo *fi)
9065 {
9066     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
9067         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
9068         target_ulong s2size;
9069         hwaddr s2pa;
9070         int s2prot;
9071         int ret;
9072         ARMCacheAttrs cacheattrs = {};
9073         ARMCacheAttrs *pcacheattrs = NULL;
9074 
9075         if (env->cp15.hcr_el2 & HCR_PTW) {
9076             /*
9077              * PTW means we must fault if this S1 walk touches S2 Device
9078              * memory; otherwise we don't care about the attributes and can
9079              * save the S2 translation the effort of computing them.
9080              */
9081             pcacheattrs = &cacheattrs;
9082         }
9083 
9084         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
9085                                  &txattrs, &s2prot, &s2size, fi, pcacheattrs);
9086         if (ret) {
9087             assert(fi->type != ARMFault_None);
9088             fi->s2addr = addr;
9089             fi->stage2 = true;
9090             fi->s1ptw = true;
9091             return ~0;
9092         }
9093         if (pcacheattrs && (pcacheattrs->attrs & 0xf0) == 0) {
9094             /* Access was to Device memory: generate Permission fault */
9095             fi->type = ARMFault_Permission;
9096             fi->s2addr = addr;
9097             fi->stage2 = true;
9098             fi->s1ptw = true;
9099             return ~0;
9100         }
9101         addr = s2pa;
9102     }
9103     return addr;
9104 }
9105 
9106 /* All loads done in the course of a page table walk go through here. */
9107 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
9108                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
9109 {
9110     ARMCPU *cpu = ARM_CPU(cs);
9111     CPUARMState *env = &cpu->env;
9112     MemTxAttrs attrs = {};
9113     MemTxResult result = MEMTX_OK;
9114     AddressSpace *as;
9115     uint32_t data;
9116 
9117     attrs.secure = is_secure;
9118     as = arm_addressspace(cs, attrs);
9119     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
9120     if (fi->s1ptw) {
9121         return 0;
9122     }
9123     if (regime_translation_big_endian(env, mmu_idx)) {
9124         data = address_space_ldl_be(as, addr, attrs, &result);
9125     } else {
9126         data = address_space_ldl_le(as, addr, attrs, &result);
9127     }
9128     if (result == MEMTX_OK) {
9129         return data;
9130     }
9131     fi->type = ARMFault_SyncExternalOnWalk;
9132     fi->ea = arm_extabort_type(result);
9133     return 0;
9134 }
9135 
9136 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
9137                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
9138 {
9139     ARMCPU *cpu = ARM_CPU(cs);
9140     CPUARMState *env = &cpu->env;
9141     MemTxAttrs attrs = {};
9142     MemTxResult result = MEMTX_OK;
9143     AddressSpace *as;
9144     uint64_t data;
9145 
9146     attrs.secure = is_secure;
9147     as = arm_addressspace(cs, attrs);
9148     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
9149     if (fi->s1ptw) {
9150         return 0;
9151     }
9152     if (regime_translation_big_endian(env, mmu_idx)) {
9153         data = address_space_ldq_be(as, addr, attrs, &result);
9154     } else {
9155         data = address_space_ldq_le(as, addr, attrs, &result);
9156     }
9157     if (result == MEMTX_OK) {
9158         return data;
9159     }
9160     fi->type = ARMFault_SyncExternalOnWalk;
9161     fi->ea = arm_extabort_type(result);
9162     return 0;
9163 }
9164 
9165 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
9166                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
9167                              hwaddr *phys_ptr, int *prot,
9168                              target_ulong *page_size,
9169                              ARMMMUFaultInfo *fi)
9170 {
9171     CPUState *cs = env_cpu(env);
9172     int level = 1;
9173     uint32_t table;
9174     uint32_t desc;
9175     int type;
9176     int ap;
9177     int domain = 0;
9178     int domain_prot;
9179     hwaddr phys_addr;
9180     uint32_t dacr;
9181 
9182     /* Pagetable walk.  */
9183     /* Lookup l1 descriptor.  */
9184     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
9185         /* Section translation fault if page walk is disabled by PD0 or PD1 */
9186         fi->type = ARMFault_Translation;
9187         goto do_fault;
9188     }
9189     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9190                        mmu_idx, fi);
9191     if (fi->type != ARMFault_None) {
9192         goto do_fault;
9193     }
9194     type = (desc & 3);
9195     domain = (desc >> 5) & 0x0f;
9196     if (regime_el(env, mmu_idx) == 1) {
9197         dacr = env->cp15.dacr_ns;
9198     } else {
9199         dacr = env->cp15.dacr_s;
9200     }
9201     domain_prot = (dacr >> (domain * 2)) & 3;
9202     if (type == 0) {
9203         /* Section translation fault.  */
9204         fi->type = ARMFault_Translation;
9205         goto do_fault;
9206     }
9207     if (type != 2) {
9208         level = 2;
9209     }
9210     if (domain_prot == 0 || domain_prot == 2) {
9211         fi->type = ARMFault_Domain;
9212         goto do_fault;
9213     }
9214     if (type == 2) {
9215         /* 1Mb section.  */
9216         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
9217         ap = (desc >> 10) & 3;
9218         *page_size = 1024 * 1024;
9219     } else {
9220         /* Lookup l2 entry.  */
9221         if (type == 1) {
9222             /* Coarse pagetable.  */
9223             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
9224         } else {
9225             /* Fine pagetable.  */
9226             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
9227         }
9228         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9229                            mmu_idx, fi);
9230         if (fi->type != ARMFault_None) {
9231             goto do_fault;
9232         }
9233         switch (desc & 3) {
9234         case 0: /* Page translation fault.  */
9235             fi->type = ARMFault_Translation;
9236             goto do_fault;
9237         case 1: /* 64k page.  */
9238             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
9239             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
9240             *page_size = 0x10000;
9241             break;
9242         case 2: /* 4k page.  */
9243             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9244             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
9245             *page_size = 0x1000;
9246             break;
9247         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
9248             if (type == 1) {
9249                 /* ARMv6/XScale extended small page format */
9250                 if (arm_feature(env, ARM_FEATURE_XSCALE)
9251                     || arm_feature(env, ARM_FEATURE_V6)) {
9252                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9253                     *page_size = 0x1000;
9254                 } else {
9255                     /* UNPREDICTABLE in ARMv5; we choose to take a
9256                      * page translation fault.
9257                      */
9258                     fi->type = ARMFault_Translation;
9259                     goto do_fault;
9260                 }
9261             } else {
9262                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
9263                 *page_size = 0x400;
9264             }
9265             ap = (desc >> 4) & 3;
9266             break;
9267         default:
9268             /* Never happens, but compiler isn't smart enough to tell.  */
9269             abort();
9270         }
9271     }
9272     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9273     *prot |= *prot ? PAGE_EXEC : 0;
9274     if (!(*prot & (1 << access_type))) {
9275         /* Access permission fault.  */
9276         fi->type = ARMFault_Permission;
9277         goto do_fault;
9278     }
9279     *phys_ptr = phys_addr;
9280     return false;
9281 do_fault:
9282     fi->domain = domain;
9283     fi->level = level;
9284     return true;
9285 }
9286 
9287 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
9288                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
9289                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
9290                              target_ulong *page_size, ARMMMUFaultInfo *fi)
9291 {
9292     CPUState *cs = env_cpu(env);
9293     int level = 1;
9294     uint32_t table;
9295     uint32_t desc;
9296     uint32_t xn;
9297     uint32_t pxn = 0;
9298     int type;
9299     int ap;
9300     int domain = 0;
9301     int domain_prot;
9302     hwaddr phys_addr;
9303     uint32_t dacr;
9304     bool ns;
9305 
9306     /* Pagetable walk.  */
9307     /* Lookup l1 descriptor.  */
9308     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
9309         /* Section translation fault if page walk is disabled by PD0 or PD1 */
9310         fi->type = ARMFault_Translation;
9311         goto do_fault;
9312     }
9313     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9314                        mmu_idx, fi);
9315     if (fi->type != ARMFault_None) {
9316         goto do_fault;
9317     }
9318     type = (desc & 3);
9319     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
9320         /* Section translation fault, or attempt to use the encoding
9321          * which is Reserved on implementations without PXN.
9322          */
9323         fi->type = ARMFault_Translation;
9324         goto do_fault;
9325     }
9326     if ((type == 1) || !(desc & (1 << 18))) {
9327         /* Page or Section.  */
9328         domain = (desc >> 5) & 0x0f;
9329     }
9330     if (regime_el(env, mmu_idx) == 1) {
9331         dacr = env->cp15.dacr_ns;
9332     } else {
9333         dacr = env->cp15.dacr_s;
9334     }
9335     if (type == 1) {
9336         level = 2;
9337     }
9338     domain_prot = (dacr >> (domain * 2)) & 3;
9339     if (domain_prot == 0 || domain_prot == 2) {
9340         /* Section or Page domain fault */
9341         fi->type = ARMFault_Domain;
9342         goto do_fault;
9343     }
9344     if (type != 1) {
9345         if (desc & (1 << 18)) {
9346             /* Supersection.  */
9347             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
9348             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
9349             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
9350             *page_size = 0x1000000;
9351         } else {
9352             /* Section.  */
9353             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
9354             *page_size = 0x100000;
9355         }
9356         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
9357         xn = desc & (1 << 4);
9358         pxn = desc & 1;
9359         ns = extract32(desc, 19, 1);
9360     } else {
9361         if (arm_feature(env, ARM_FEATURE_PXN)) {
9362             pxn = (desc >> 2) & 1;
9363         }
9364         ns = extract32(desc, 3, 1);
9365         /* Lookup l2 entry.  */
9366         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
9367         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9368                            mmu_idx, fi);
9369         if (fi->type != ARMFault_None) {
9370             goto do_fault;
9371         }
9372         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
9373         switch (desc & 3) {
9374         case 0: /* Page translation fault.  */
9375             fi->type = ARMFault_Translation;
9376             goto do_fault;
9377         case 1: /* 64k page.  */
9378             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
9379             xn = desc & (1 << 15);
9380             *page_size = 0x10000;
9381             break;
9382         case 2: case 3: /* 4k page.  */
9383             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9384             xn = desc & 1;
9385             *page_size = 0x1000;
9386             break;
9387         default:
9388             /* Never happens, but compiler isn't smart enough to tell.  */
9389             abort();
9390         }
9391     }
9392     if (domain_prot == 3) {
9393         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9394     } else {
9395         if (pxn && !regime_is_user(env, mmu_idx)) {
9396             xn = 1;
9397         }
9398         if (xn && access_type == MMU_INST_FETCH) {
9399             fi->type = ARMFault_Permission;
9400             goto do_fault;
9401         }
9402 
9403         if (arm_feature(env, ARM_FEATURE_V6K) &&
9404                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
9405             /* The simplified model uses AP[0] as an access control bit.  */
9406             if ((ap & 1) == 0) {
9407                 /* Access flag fault.  */
9408                 fi->type = ARMFault_AccessFlag;
9409                 goto do_fault;
9410             }
9411             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
9412         } else {
9413             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9414         }
9415         if (*prot && !xn) {
9416             *prot |= PAGE_EXEC;
9417         }
9418         if (!(*prot & (1 << access_type))) {
9419             /* Access permission fault.  */
9420             fi->type = ARMFault_Permission;
9421             goto do_fault;
9422         }
9423     }
9424     if (ns) {
9425         /* The NS bit will (as required by the architecture) have no effect if
9426          * the CPU doesn't support TZ or this is a non-secure translation
9427          * regime, because the attribute will already be non-secure.
9428          */
9429         attrs->secure = false;
9430     }
9431     *phys_ptr = phys_addr;
9432     return false;
9433 do_fault:
9434     fi->domain = domain;
9435     fi->level = level;
9436     return true;
9437 }
9438 
9439 /*
9440  * check_s2_mmu_setup
9441  * @cpu:        ARMCPU
9442  * @is_aa64:    True if the translation regime is in AArch64 state
9443  * @startlevel: Suggested starting level
9444  * @inputsize:  Bitsize of IPAs
9445  * @stride:     Page-table stride (See the ARM ARM)
9446  *
9447  * Returns true if the suggested S2 translation parameters are OK and
9448  * false otherwise.
9449  */
9450 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
9451                                int inputsize, int stride)
9452 {
9453     const int grainsize = stride + 3;
9454     int startsizecheck;
9455 
9456     /* Negative levels are never allowed.  */
9457     if (level < 0) {
9458         return false;
9459     }
9460 
9461     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
9462     if (startsizecheck < 1 || startsizecheck > stride + 4) {
9463         return false;
9464     }
9465 
9466     if (is_aa64) {
9467         CPUARMState *env = &cpu->env;
9468         unsigned int pamax = arm_pamax(cpu);
9469 
9470         switch (stride) {
9471         case 13: /* 64KB Pages.  */
9472             if (level == 0 || (level == 1 && pamax <= 42)) {
9473                 return false;
9474             }
9475             break;
9476         case 11: /* 16KB Pages.  */
9477             if (level == 0 || (level == 1 && pamax <= 40)) {
9478                 return false;
9479             }
9480             break;
9481         case 9: /* 4KB Pages.  */
9482             if (level == 0 && pamax <= 42) {
9483                 return false;
9484             }
9485             break;
9486         default:
9487             g_assert_not_reached();
9488         }
9489 
9490         /* Inputsize checks.  */
9491         if (inputsize > pamax &&
9492             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
9493             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
9494             return false;
9495         }
9496     } else {
9497         /* AArch32 only supports 4KB pages. Assert on that.  */
9498         assert(stride == 9);
9499 
9500         if (level == 0) {
9501             return false;
9502         }
9503     }
9504     return true;
9505 }
9506 
9507 /* Translate from the 4-bit stage 2 representation of
9508  * memory attributes (without cache-allocation hints) to
9509  * the 8-bit representation of the stage 1 MAIR registers
9510  * (which includes allocation hints).
9511  *
9512  * ref: shared/translation/attrs/S2AttrDecode()
9513  *      .../S2ConvertAttrsHints()
9514  */
9515 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
9516 {
9517     uint8_t hiattr = extract32(s2attrs, 2, 2);
9518     uint8_t loattr = extract32(s2attrs, 0, 2);
9519     uint8_t hihint = 0, lohint = 0;
9520 
9521     if (hiattr != 0) { /* normal memory */
9522         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
9523             hiattr = loattr = 1; /* non-cacheable */
9524         } else {
9525             if (hiattr != 1) { /* Write-through or write-back */
9526                 hihint = 3; /* RW allocate */
9527             }
9528             if (loattr != 1) { /* Write-through or write-back */
9529                 lohint = 3; /* RW allocate */
9530             }
9531         }
9532     }
9533 
9534     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
9535 }
9536 #endif /* !CONFIG_USER_ONLY */
9537 
9538 ARMVAParameters aa64_va_parameters_both(CPUARMState *env, uint64_t va,
9539                                         ARMMMUIdx mmu_idx)
9540 {
9541     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
9542     uint32_t el = regime_el(env, mmu_idx);
9543     bool tbi, tbid, epd, hpd, using16k, using64k;
9544     int select, tsz;
9545 
9546     /*
9547      * Bit 55 is always between the two regions, and is canonical for
9548      * determining if address tagging is enabled.
9549      */
9550     select = extract64(va, 55, 1);
9551 
9552     if (el > 1) {
9553         tsz = extract32(tcr, 0, 6);
9554         using64k = extract32(tcr, 14, 1);
9555         using16k = extract32(tcr, 15, 1);
9556         if (mmu_idx == ARMMMUIdx_S2NS) {
9557             /* VTCR_EL2 */
9558             tbi = tbid = hpd = false;
9559         } else {
9560             tbi = extract32(tcr, 20, 1);
9561             hpd = extract32(tcr, 24, 1);
9562             tbid = extract32(tcr, 29, 1);
9563         }
9564         epd = false;
9565     } else if (!select) {
9566         tsz = extract32(tcr, 0, 6);
9567         epd = extract32(tcr, 7, 1);
9568         using64k = extract32(tcr, 14, 1);
9569         using16k = extract32(tcr, 15, 1);
9570         tbi = extract64(tcr, 37, 1);
9571         hpd = extract64(tcr, 41, 1);
9572         tbid = extract64(tcr, 51, 1);
9573     } else {
9574         int tg = extract32(tcr, 30, 2);
9575         using16k = tg == 1;
9576         using64k = tg == 3;
9577         tsz = extract32(tcr, 16, 6);
9578         epd = extract32(tcr, 23, 1);
9579         tbi = extract64(tcr, 38, 1);
9580         hpd = extract64(tcr, 42, 1);
9581         tbid = extract64(tcr, 52, 1);
9582     }
9583     tsz = MIN(tsz, 39);  /* TODO: ARMv8.4-TTST */
9584     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
9585 
9586     return (ARMVAParameters) {
9587         .tsz = tsz,
9588         .select = select,
9589         .tbi = tbi,
9590         .tbid = tbid,
9591         .epd = epd,
9592         .hpd = hpd,
9593         .using16k = using16k,
9594         .using64k = using64k,
9595     };
9596 }
9597 
9598 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
9599                                    ARMMMUIdx mmu_idx, bool data)
9600 {
9601     ARMVAParameters ret = aa64_va_parameters_both(env, va, mmu_idx);
9602 
9603     /* Present TBI as a composite with TBID.  */
9604     ret.tbi &= (data || !ret.tbid);
9605     return ret;
9606 }
9607 
9608 #ifndef CONFIG_USER_ONLY
9609 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
9610                                           ARMMMUIdx mmu_idx)
9611 {
9612     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
9613     uint32_t el = regime_el(env, mmu_idx);
9614     int select, tsz;
9615     bool epd, hpd;
9616 
9617     if (mmu_idx == ARMMMUIdx_S2NS) {
9618         /* VTCR */
9619         bool sext = extract32(tcr, 4, 1);
9620         bool sign = extract32(tcr, 3, 1);
9621 
9622         /*
9623          * If the sign-extend bit is not the same as t0sz[3], the result
9624          * is unpredictable. Flag this as a guest error.
9625          */
9626         if (sign != sext) {
9627             qemu_log_mask(LOG_GUEST_ERROR,
9628                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
9629         }
9630         tsz = sextract32(tcr, 0, 4) + 8;
9631         select = 0;
9632         hpd = false;
9633         epd = false;
9634     } else if (el == 2) {
9635         /* HTCR */
9636         tsz = extract32(tcr, 0, 3);
9637         select = 0;
9638         hpd = extract64(tcr, 24, 1);
9639         epd = false;
9640     } else {
9641         int t0sz = extract32(tcr, 0, 3);
9642         int t1sz = extract32(tcr, 16, 3);
9643 
9644         if (t1sz == 0) {
9645             select = va > (0xffffffffu >> t0sz);
9646         } else {
9647             /* Note that we will detect errors later.  */
9648             select = va >= ~(0xffffffffu >> t1sz);
9649         }
9650         if (!select) {
9651             tsz = t0sz;
9652             epd = extract32(tcr, 7, 1);
9653             hpd = extract64(tcr, 41, 1);
9654         } else {
9655             tsz = t1sz;
9656             epd = extract32(tcr, 23, 1);
9657             hpd = extract64(tcr, 42, 1);
9658         }
9659         /* For aarch32, hpd0 is not enabled without t2e as well.  */
9660         hpd &= extract32(tcr, 6, 1);
9661     }
9662 
9663     return (ARMVAParameters) {
9664         .tsz = tsz,
9665         .select = select,
9666         .epd = epd,
9667         .hpd = hpd,
9668     };
9669 }
9670 
9671 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
9672                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
9673                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
9674                                target_ulong *page_size_ptr,
9675                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
9676 {
9677     ARMCPU *cpu = env_archcpu(env);
9678     CPUState *cs = CPU(cpu);
9679     /* Read an LPAE long-descriptor translation table. */
9680     ARMFaultType fault_type = ARMFault_Translation;
9681     uint32_t level;
9682     ARMVAParameters param;
9683     uint64_t ttbr;
9684     hwaddr descaddr, indexmask, indexmask_grainsize;
9685     uint32_t tableattrs;
9686     target_ulong page_size;
9687     uint32_t attrs;
9688     int32_t stride;
9689     int addrsize, inputsize;
9690     TCR *tcr = regime_tcr(env, mmu_idx);
9691     int ap, ns, xn, pxn;
9692     uint32_t el = regime_el(env, mmu_idx);
9693     bool ttbr1_valid;
9694     uint64_t descaddrmask;
9695     bool aarch64 = arm_el_is_aa64(env, el);
9696     bool guarded = false;
9697 
9698     /* TODO:
9699      * This code does not handle the different format TCR for VTCR_EL2.
9700      * This code also does not support shareability levels.
9701      * Attribute and permission bit handling should also be checked when adding
9702      * support for those page table walks.
9703      */
9704     if (aarch64) {
9705         param = aa64_va_parameters(env, address, mmu_idx,
9706                                    access_type != MMU_INST_FETCH);
9707         level = 0;
9708         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
9709          * invalid.
9710          */
9711         ttbr1_valid = (el < 2);
9712         addrsize = 64 - 8 * param.tbi;
9713         inputsize = 64 - param.tsz;
9714     } else {
9715         param = aa32_va_parameters(env, address, mmu_idx);
9716         level = 1;
9717         /* There is no TTBR1 for EL2 */
9718         ttbr1_valid = (el != 2);
9719         addrsize = (mmu_idx == ARMMMUIdx_S2NS ? 40 : 32);
9720         inputsize = addrsize - param.tsz;
9721     }
9722 
9723     /*
9724      * We determined the region when collecting the parameters, but we
9725      * have not yet validated that the address is valid for the region.
9726      * Extract the top bits and verify that they all match select.
9727      *
9728      * For aa32, if inputsize == addrsize, then we have selected the
9729      * region by exclusion in aa32_va_parameters and there is no more
9730      * validation to do here.
9731      */
9732     if (inputsize < addrsize) {
9733         target_ulong top_bits = sextract64(address, inputsize,
9734                                            addrsize - inputsize);
9735         if (-top_bits != param.select || (param.select && !ttbr1_valid)) {
9736             /* The gap between the two regions is a Translation fault */
9737             fault_type = ARMFault_Translation;
9738             goto do_fault;
9739         }
9740     }
9741 
9742     if (param.using64k) {
9743         stride = 13;
9744     } else if (param.using16k) {
9745         stride = 11;
9746     } else {
9747         stride = 9;
9748     }
9749 
9750     /* Note that QEMU ignores shareability and cacheability attributes,
9751      * so we don't need to do anything with the SH, ORGN, IRGN fields
9752      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
9753      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
9754      * implement any ASID-like capability so we can ignore it (instead
9755      * we will always flush the TLB any time the ASID is changed).
9756      */
9757     ttbr = regime_ttbr(env, mmu_idx, param.select);
9758 
9759     /* Here we should have set up all the parameters for the translation:
9760      * inputsize, ttbr, epd, stride, tbi
9761      */
9762 
9763     if (param.epd) {
9764         /* Translation table walk disabled => Translation fault on TLB miss
9765          * Note: This is always 0 on 64-bit EL2 and EL3.
9766          */
9767         goto do_fault;
9768     }
9769 
9770     if (mmu_idx != ARMMMUIdx_S2NS) {
9771         /* The starting level depends on the virtual address size (which can
9772          * be up to 48 bits) and the translation granule size. It indicates
9773          * the number of strides (stride bits at a time) needed to
9774          * consume the bits of the input address. In the pseudocode this is:
9775          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
9776          * where their 'inputsize' is our 'inputsize', 'grainsize' is
9777          * our 'stride + 3' and 'stride' is our 'stride'.
9778          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
9779          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
9780          * = 4 - (inputsize - 4) / stride;
9781          */
9782         level = 4 - (inputsize - 4) / stride;
9783     } else {
9784         /* For stage 2 translations the starting level is specified by the
9785          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
9786          */
9787         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
9788         uint32_t startlevel;
9789         bool ok;
9790 
9791         if (!aarch64 || stride == 9) {
9792             /* AArch32 or 4KB pages */
9793             startlevel = 2 - sl0;
9794         } else {
9795             /* 16KB or 64KB pages */
9796             startlevel = 3 - sl0;
9797         }
9798 
9799         /* Check that the starting level is valid. */
9800         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
9801                                 inputsize, stride);
9802         if (!ok) {
9803             fault_type = ARMFault_Translation;
9804             goto do_fault;
9805         }
9806         level = startlevel;
9807     }
9808 
9809     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
9810     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
9811 
9812     /* Now we can extract the actual base address from the TTBR */
9813     descaddr = extract64(ttbr, 0, 48);
9814     descaddr &= ~indexmask;
9815 
9816     /* The address field in the descriptor goes up to bit 39 for ARMv7
9817      * but up to bit 47 for ARMv8, but we use the descaddrmask
9818      * up to bit 39 for AArch32, because we don't need other bits in that case
9819      * to construct next descriptor address (anyway they should be all zeroes).
9820      */
9821     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
9822                    ~indexmask_grainsize;
9823 
9824     /* Secure accesses start with the page table in secure memory and
9825      * can be downgraded to non-secure at any step. Non-secure accesses
9826      * remain non-secure. We implement this by just ORing in the NSTable/NS
9827      * bits at each step.
9828      */
9829     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
9830     for (;;) {
9831         uint64_t descriptor;
9832         bool nstable;
9833 
9834         descaddr |= (address >> (stride * (4 - level))) & indexmask;
9835         descaddr &= ~7ULL;
9836         nstable = extract32(tableattrs, 4, 1);
9837         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
9838         if (fi->type != ARMFault_None) {
9839             goto do_fault;
9840         }
9841 
9842         if (!(descriptor & 1) ||
9843             (!(descriptor & 2) && (level == 3))) {
9844             /* Invalid, or the Reserved level 3 encoding */
9845             goto do_fault;
9846         }
9847         descaddr = descriptor & descaddrmask;
9848 
9849         if ((descriptor & 2) && (level < 3)) {
9850             /* Table entry. The top five bits are attributes which may
9851              * propagate down through lower levels of the table (and
9852              * which are all arranged so that 0 means "no effect", so
9853              * we can gather them up by ORing in the bits at each level).
9854              */
9855             tableattrs |= extract64(descriptor, 59, 5);
9856             level++;
9857             indexmask = indexmask_grainsize;
9858             continue;
9859         }
9860         /* Block entry at level 1 or 2, or page entry at level 3.
9861          * These are basically the same thing, although the number
9862          * of bits we pull in from the vaddr varies.
9863          */
9864         page_size = (1ULL << ((stride * (4 - level)) + 3));
9865         descaddr |= (address & (page_size - 1));
9866         /* Extract attributes from the descriptor */
9867         attrs = extract64(descriptor, 2, 10)
9868             | (extract64(descriptor, 52, 12) << 10);
9869 
9870         if (mmu_idx == ARMMMUIdx_S2NS) {
9871             /* Stage 2 table descriptors do not include any attribute fields */
9872             break;
9873         }
9874         /* Merge in attributes from table descriptors */
9875         attrs |= nstable << 3; /* NS */
9876         guarded = extract64(descriptor, 50, 1);  /* GP */
9877         if (param.hpd) {
9878             /* HPD disables all the table attributes except NSTable.  */
9879             break;
9880         }
9881         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
9882         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
9883          * means "force PL1 access only", which means forcing AP[1] to 0.
9884          */
9885         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
9886         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
9887         break;
9888     }
9889     /* Here descaddr is the final physical address, and attributes
9890      * are all in attrs.
9891      */
9892     fault_type = ARMFault_AccessFlag;
9893     if ((attrs & (1 << 8)) == 0) {
9894         /* Access flag */
9895         goto do_fault;
9896     }
9897 
9898     ap = extract32(attrs, 4, 2);
9899     xn = extract32(attrs, 12, 1);
9900 
9901     if (mmu_idx == ARMMMUIdx_S2NS) {
9902         ns = true;
9903         *prot = get_S2prot(env, ap, xn);
9904     } else {
9905         ns = extract32(attrs, 3, 1);
9906         pxn = extract32(attrs, 11, 1);
9907         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
9908     }
9909 
9910     fault_type = ARMFault_Permission;
9911     if (!(*prot & (1 << access_type))) {
9912         goto do_fault;
9913     }
9914 
9915     if (ns) {
9916         /* The NS bit will (as required by the architecture) have no effect if
9917          * the CPU doesn't support TZ or this is a non-secure translation
9918          * regime, because the attribute will already be non-secure.
9919          */
9920         txattrs->secure = false;
9921     }
9922     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
9923     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
9924         txattrs->target_tlb_bit0 = true;
9925     }
9926 
9927     if (cacheattrs != NULL) {
9928         if (mmu_idx == ARMMMUIdx_S2NS) {
9929             cacheattrs->attrs = convert_stage2_attrs(env,
9930                                                      extract32(attrs, 0, 4));
9931         } else {
9932             /* Index into MAIR registers for cache attributes */
9933             uint8_t attrindx = extract32(attrs, 0, 3);
9934             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
9935             assert(attrindx <= 7);
9936             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
9937         }
9938         cacheattrs->shareability = extract32(attrs, 6, 2);
9939     }
9940 
9941     *phys_ptr = descaddr;
9942     *page_size_ptr = page_size;
9943     return false;
9944 
9945 do_fault:
9946     fi->type = fault_type;
9947     fi->level = level;
9948     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
9949     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
9950     return true;
9951 }
9952 
9953 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
9954                                                 ARMMMUIdx mmu_idx,
9955                                                 int32_t address, int *prot)
9956 {
9957     if (!arm_feature(env, ARM_FEATURE_M)) {
9958         *prot = PAGE_READ | PAGE_WRITE;
9959         switch (address) {
9960         case 0xF0000000 ... 0xFFFFFFFF:
9961             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
9962                 /* hivecs execing is ok */
9963                 *prot |= PAGE_EXEC;
9964             }
9965             break;
9966         case 0x00000000 ... 0x7FFFFFFF:
9967             *prot |= PAGE_EXEC;
9968             break;
9969         }
9970     } else {
9971         /* Default system address map for M profile cores.
9972          * The architecture specifies which regions are execute-never;
9973          * at the MPU level no other checks are defined.
9974          */
9975         switch (address) {
9976         case 0x00000000 ... 0x1fffffff: /* ROM */
9977         case 0x20000000 ... 0x3fffffff: /* SRAM */
9978         case 0x60000000 ... 0x7fffffff: /* RAM */
9979         case 0x80000000 ... 0x9fffffff: /* RAM */
9980             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9981             break;
9982         case 0x40000000 ... 0x5fffffff: /* Peripheral */
9983         case 0xa0000000 ... 0xbfffffff: /* Device */
9984         case 0xc0000000 ... 0xdfffffff: /* Device */
9985         case 0xe0000000 ... 0xffffffff: /* System */
9986             *prot = PAGE_READ | PAGE_WRITE;
9987             break;
9988         default:
9989             g_assert_not_reached();
9990         }
9991     }
9992 }
9993 
9994 static bool pmsav7_use_background_region(ARMCPU *cpu,
9995                                          ARMMMUIdx mmu_idx, bool is_user)
9996 {
9997     /* Return true if we should use the default memory map as a
9998      * "background" region if there are no hits against any MPU regions.
9999      */
10000     CPUARMState *env = &cpu->env;
10001 
10002     if (is_user) {
10003         return false;
10004     }
10005 
10006     if (arm_feature(env, ARM_FEATURE_M)) {
10007         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
10008             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
10009     } else {
10010         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
10011     }
10012 }
10013 
10014 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
10015 {
10016     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
10017     return arm_feature(env, ARM_FEATURE_M) &&
10018         extract32(address, 20, 12) == 0xe00;
10019 }
10020 
10021 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
10022 {
10023     /* True if address is in the M profile system region
10024      * 0xe0000000 - 0xffffffff
10025      */
10026     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
10027 }
10028 
10029 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
10030                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10031                                  hwaddr *phys_ptr, int *prot,
10032                                  target_ulong *page_size,
10033                                  ARMMMUFaultInfo *fi)
10034 {
10035     ARMCPU *cpu = env_archcpu(env);
10036     int n;
10037     bool is_user = regime_is_user(env, mmu_idx);
10038 
10039     *phys_ptr = address;
10040     *page_size = TARGET_PAGE_SIZE;
10041     *prot = 0;
10042 
10043     if (regime_translation_disabled(env, mmu_idx) ||
10044         m_is_ppb_region(env, address)) {
10045         /* MPU disabled or M profile PPB access: use default memory map.
10046          * The other case which uses the default memory map in the
10047          * v7M ARM ARM pseudocode is exception vector reads from the vector
10048          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
10049          * which always does a direct read using address_space_ldl(), rather
10050          * than going via this function, so we don't need to check that here.
10051          */
10052         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
10053     } else { /* MPU enabled */
10054         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
10055             /* region search */
10056             uint32_t base = env->pmsav7.drbar[n];
10057             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
10058             uint32_t rmask;
10059             bool srdis = false;
10060 
10061             if (!(env->pmsav7.drsr[n] & 0x1)) {
10062                 continue;
10063             }
10064 
10065             if (!rsize) {
10066                 qemu_log_mask(LOG_GUEST_ERROR,
10067                               "DRSR[%d]: Rsize field cannot be 0\n", n);
10068                 continue;
10069             }
10070             rsize++;
10071             rmask = (1ull << rsize) - 1;
10072 
10073             if (base & rmask) {
10074                 qemu_log_mask(LOG_GUEST_ERROR,
10075                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
10076                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
10077                               n, base, rmask);
10078                 continue;
10079             }
10080 
10081             if (address < base || address > base + rmask) {
10082                 /*
10083                  * Address not in this region. We must check whether the
10084                  * region covers addresses in the same page as our address.
10085                  * In that case we must not report a size that covers the
10086                  * whole page for a subsequent hit against a different MPU
10087                  * region or the background region, because it would result in
10088                  * incorrect TLB hits for subsequent accesses to addresses that
10089                  * are in this MPU region.
10090                  */
10091                 if (ranges_overlap(base, rmask,
10092                                    address & TARGET_PAGE_MASK,
10093                                    TARGET_PAGE_SIZE)) {
10094                     *page_size = 1;
10095                 }
10096                 continue;
10097             }
10098 
10099             /* Region matched */
10100 
10101             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
10102                 int i, snd;
10103                 uint32_t srdis_mask;
10104 
10105                 rsize -= 3; /* sub region size (power of 2) */
10106                 snd = ((address - base) >> rsize) & 0x7;
10107                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
10108 
10109                 srdis_mask = srdis ? 0x3 : 0x0;
10110                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
10111                     /* This will check in groups of 2, 4 and then 8, whether
10112                      * the subregion bits are consistent. rsize is incremented
10113                      * back up to give the region size, considering consistent
10114                      * adjacent subregions as one region. Stop testing if rsize
10115                      * is already big enough for an entire QEMU page.
10116                      */
10117                     int snd_rounded = snd & ~(i - 1);
10118                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
10119                                                      snd_rounded + 8, i);
10120                     if (srdis_mask ^ srdis_multi) {
10121                         break;
10122                     }
10123                     srdis_mask = (srdis_mask << i) | srdis_mask;
10124                     rsize++;
10125                 }
10126             }
10127             if (srdis) {
10128                 continue;
10129             }
10130             if (rsize < TARGET_PAGE_BITS) {
10131                 *page_size = 1 << rsize;
10132             }
10133             break;
10134         }
10135 
10136         if (n == -1) { /* no hits */
10137             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
10138                 /* background fault */
10139                 fi->type = ARMFault_Background;
10140                 return true;
10141             }
10142             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
10143         } else { /* a MPU hit! */
10144             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
10145             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
10146 
10147             if (m_is_system_region(env, address)) {
10148                 /* System space is always execute never */
10149                 xn = 1;
10150             }
10151 
10152             if (is_user) { /* User mode AP bit decoding */
10153                 switch (ap) {
10154                 case 0:
10155                 case 1:
10156                 case 5:
10157                     break; /* no access */
10158                 case 3:
10159                     *prot |= PAGE_WRITE;
10160                     /* fall through */
10161                 case 2:
10162                 case 6:
10163                     *prot |= PAGE_READ | PAGE_EXEC;
10164                     break;
10165                 case 7:
10166                     /* for v7M, same as 6; for R profile a reserved value */
10167                     if (arm_feature(env, ARM_FEATURE_M)) {
10168                         *prot |= PAGE_READ | PAGE_EXEC;
10169                         break;
10170                     }
10171                     /* fall through */
10172                 default:
10173                     qemu_log_mask(LOG_GUEST_ERROR,
10174                                   "DRACR[%d]: Bad value for AP bits: 0x%"
10175                                   PRIx32 "\n", n, ap);
10176                 }
10177             } else { /* Priv. mode AP bits decoding */
10178                 switch (ap) {
10179                 case 0:
10180                     break; /* no access */
10181                 case 1:
10182                 case 2:
10183                 case 3:
10184                     *prot |= PAGE_WRITE;
10185                     /* fall through */
10186                 case 5:
10187                 case 6:
10188                     *prot |= PAGE_READ | PAGE_EXEC;
10189                     break;
10190                 case 7:
10191                     /* for v7M, same as 6; for R profile a reserved value */
10192                     if (arm_feature(env, ARM_FEATURE_M)) {
10193                         *prot |= PAGE_READ | PAGE_EXEC;
10194                         break;
10195                     }
10196                     /* fall through */
10197                 default:
10198                     qemu_log_mask(LOG_GUEST_ERROR,
10199                                   "DRACR[%d]: Bad value for AP bits: 0x%"
10200                                   PRIx32 "\n", n, ap);
10201                 }
10202             }
10203 
10204             /* execute never */
10205             if (xn) {
10206                 *prot &= ~PAGE_EXEC;
10207             }
10208         }
10209     }
10210 
10211     fi->type = ARMFault_Permission;
10212     fi->level = 1;
10213     return !(*prot & (1 << access_type));
10214 }
10215 
10216 static bool v8m_is_sau_exempt(CPUARMState *env,
10217                               uint32_t address, MMUAccessType access_type)
10218 {
10219     /* The architecture specifies that certain address ranges are
10220      * exempt from v8M SAU/IDAU checks.
10221      */
10222     return
10223         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
10224         (address >= 0xe0000000 && address <= 0xe0002fff) ||
10225         (address >= 0xe000e000 && address <= 0xe000efff) ||
10226         (address >= 0xe002e000 && address <= 0xe002efff) ||
10227         (address >= 0xe0040000 && address <= 0xe0041fff) ||
10228         (address >= 0xe00ff000 && address <= 0xe00fffff);
10229 }
10230 
10231 void v8m_security_lookup(CPUARMState *env, uint32_t address,
10232                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
10233                                 V8M_SAttributes *sattrs)
10234 {
10235     /* Look up the security attributes for this address. Compare the
10236      * pseudocode SecurityCheck() function.
10237      * We assume the caller has zero-initialized *sattrs.
10238      */
10239     ARMCPU *cpu = env_archcpu(env);
10240     int r;
10241     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
10242     int idau_region = IREGION_NOTVALID;
10243     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
10244     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
10245 
10246     if (cpu->idau) {
10247         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
10248         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
10249 
10250         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
10251                    &idau_nsc);
10252     }
10253 
10254     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
10255         /* 0xf0000000..0xffffffff is always S for insn fetches */
10256         return;
10257     }
10258 
10259     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
10260         sattrs->ns = !regime_is_secure(env, mmu_idx);
10261         return;
10262     }
10263 
10264     if (idau_region != IREGION_NOTVALID) {
10265         sattrs->irvalid = true;
10266         sattrs->iregion = idau_region;
10267     }
10268 
10269     switch (env->sau.ctrl & 3) {
10270     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
10271         break;
10272     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
10273         sattrs->ns = true;
10274         break;
10275     default: /* SAU.ENABLE == 1 */
10276         for (r = 0; r < cpu->sau_sregion; r++) {
10277             if (env->sau.rlar[r] & 1) {
10278                 uint32_t base = env->sau.rbar[r] & ~0x1f;
10279                 uint32_t limit = env->sau.rlar[r] | 0x1f;
10280 
10281                 if (base <= address && limit >= address) {
10282                     if (base > addr_page_base || limit < addr_page_limit) {
10283                         sattrs->subpage = true;
10284                     }
10285                     if (sattrs->srvalid) {
10286                         /* If we hit in more than one region then we must report
10287                          * as Secure, not NS-Callable, with no valid region
10288                          * number info.
10289                          */
10290                         sattrs->ns = false;
10291                         sattrs->nsc = false;
10292                         sattrs->sregion = 0;
10293                         sattrs->srvalid = false;
10294                         break;
10295                     } else {
10296                         if (env->sau.rlar[r] & 2) {
10297                             sattrs->nsc = true;
10298                         } else {
10299                             sattrs->ns = true;
10300                         }
10301                         sattrs->srvalid = true;
10302                         sattrs->sregion = r;
10303                     }
10304                 } else {
10305                     /*
10306                      * Address not in this region. We must check whether the
10307                      * region covers addresses in the same page as our address.
10308                      * In that case we must not report a size that covers the
10309                      * whole page for a subsequent hit against a different MPU
10310                      * region or the background region, because it would result
10311                      * in incorrect TLB hits for subsequent accesses to
10312                      * addresses that are in this MPU region.
10313                      */
10314                     if (limit >= base &&
10315                         ranges_overlap(base, limit - base + 1,
10316                                        addr_page_base,
10317                                        TARGET_PAGE_SIZE)) {
10318                         sattrs->subpage = true;
10319                     }
10320                 }
10321             }
10322         }
10323         break;
10324     }
10325 
10326     /*
10327      * The IDAU will override the SAU lookup results if it specifies
10328      * higher security than the SAU does.
10329      */
10330     if (!idau_ns) {
10331         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
10332             sattrs->ns = false;
10333             sattrs->nsc = idau_nsc;
10334         }
10335     }
10336 }
10337 
10338 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
10339                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
10340                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
10341                               int *prot, bool *is_subpage,
10342                               ARMMMUFaultInfo *fi, uint32_t *mregion)
10343 {
10344     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
10345      * that a full phys-to-virt translation does).
10346      * mregion is (if not NULL) set to the region number which matched,
10347      * or -1 if no region number is returned (MPU off, address did not
10348      * hit a region, address hit in multiple regions).
10349      * We set is_subpage to true if the region hit doesn't cover the
10350      * entire TARGET_PAGE the address is within.
10351      */
10352     ARMCPU *cpu = env_archcpu(env);
10353     bool is_user = regime_is_user(env, mmu_idx);
10354     uint32_t secure = regime_is_secure(env, mmu_idx);
10355     int n;
10356     int matchregion = -1;
10357     bool hit = false;
10358     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
10359     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
10360 
10361     *is_subpage = false;
10362     *phys_ptr = address;
10363     *prot = 0;
10364     if (mregion) {
10365         *mregion = -1;
10366     }
10367 
10368     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
10369      * was an exception vector read from the vector table (which is always
10370      * done using the default system address map), because those accesses
10371      * are done in arm_v7m_load_vector(), which always does a direct
10372      * read using address_space_ldl(), rather than going via this function.
10373      */
10374     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
10375         hit = true;
10376     } else if (m_is_ppb_region(env, address)) {
10377         hit = true;
10378     } else {
10379         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
10380             hit = true;
10381         }
10382 
10383         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
10384             /* region search */
10385             /* Note that the base address is bits [31:5] from the register
10386              * with bits [4:0] all zeroes, but the limit address is bits
10387              * [31:5] from the register with bits [4:0] all ones.
10388              */
10389             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
10390             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
10391 
10392             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
10393                 /* Region disabled */
10394                 continue;
10395             }
10396 
10397             if (address < base || address > limit) {
10398                 /*
10399                  * Address not in this region. We must check whether the
10400                  * region covers addresses in the same page as our address.
10401                  * In that case we must not report a size that covers the
10402                  * whole page for a subsequent hit against a different MPU
10403                  * region or the background region, because it would result in
10404                  * incorrect TLB hits for subsequent accesses to addresses that
10405                  * are in this MPU region.
10406                  */
10407                 if (limit >= base &&
10408                     ranges_overlap(base, limit - base + 1,
10409                                    addr_page_base,
10410                                    TARGET_PAGE_SIZE)) {
10411                     *is_subpage = true;
10412                 }
10413                 continue;
10414             }
10415 
10416             if (base > addr_page_base || limit < addr_page_limit) {
10417                 *is_subpage = true;
10418             }
10419 
10420             if (matchregion != -1) {
10421                 /* Multiple regions match -- always a failure (unlike
10422                  * PMSAv7 where highest-numbered-region wins)
10423                  */
10424                 fi->type = ARMFault_Permission;
10425                 fi->level = 1;
10426                 return true;
10427             }
10428 
10429             matchregion = n;
10430             hit = true;
10431         }
10432     }
10433 
10434     if (!hit) {
10435         /* background fault */
10436         fi->type = ARMFault_Background;
10437         return true;
10438     }
10439 
10440     if (matchregion == -1) {
10441         /* hit using the background region */
10442         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
10443     } else {
10444         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
10445         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
10446 
10447         if (m_is_system_region(env, address)) {
10448             /* System space is always execute never */
10449             xn = 1;
10450         }
10451 
10452         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
10453         if (*prot && !xn) {
10454             *prot |= PAGE_EXEC;
10455         }
10456         /* We don't need to look the attribute up in the MAIR0/MAIR1
10457          * registers because that only tells us about cacheability.
10458          */
10459         if (mregion) {
10460             *mregion = matchregion;
10461         }
10462     }
10463 
10464     fi->type = ARMFault_Permission;
10465     fi->level = 1;
10466     return !(*prot & (1 << access_type));
10467 }
10468 
10469 
10470 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
10471                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10472                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
10473                                  int *prot, target_ulong *page_size,
10474                                  ARMMMUFaultInfo *fi)
10475 {
10476     uint32_t secure = regime_is_secure(env, mmu_idx);
10477     V8M_SAttributes sattrs = {};
10478     bool ret;
10479     bool mpu_is_subpage;
10480 
10481     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10482         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
10483         if (access_type == MMU_INST_FETCH) {
10484             /* Instruction fetches always use the MMU bank and the
10485              * transaction attribute determined by the fetch address,
10486              * regardless of CPU state. This is painful for QEMU
10487              * to handle, because it would mean we need to encode
10488              * into the mmu_idx not just the (user, negpri) information
10489              * for the current security state but also that for the
10490              * other security state, which would balloon the number
10491              * of mmu_idx values needed alarmingly.
10492              * Fortunately we can avoid this because it's not actually
10493              * possible to arbitrarily execute code from memory with
10494              * the wrong security attribute: it will always generate
10495              * an exception of some kind or another, apart from the
10496              * special case of an NS CPU executing an SG instruction
10497              * in S&NSC memory. So we always just fail the translation
10498              * here and sort things out in the exception handler
10499              * (including possibly emulating an SG instruction).
10500              */
10501             if (sattrs.ns != !secure) {
10502                 if (sattrs.nsc) {
10503                     fi->type = ARMFault_QEMU_NSCExec;
10504                 } else {
10505                     fi->type = ARMFault_QEMU_SFault;
10506                 }
10507                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10508                 *phys_ptr = address;
10509                 *prot = 0;
10510                 return true;
10511             }
10512         } else {
10513             /* For data accesses we always use the MMU bank indicated
10514              * by the current CPU state, but the security attributes
10515              * might downgrade a secure access to nonsecure.
10516              */
10517             if (sattrs.ns) {
10518                 txattrs->secure = false;
10519             } else if (!secure) {
10520                 /* NS access to S memory must fault.
10521                  * Architecturally we should first check whether the
10522                  * MPU information for this address indicates that we
10523                  * are doing an unaligned access to Device memory, which
10524                  * should generate a UsageFault instead. QEMU does not
10525                  * currently check for that kind of unaligned access though.
10526                  * If we added it we would need to do so as a special case
10527                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
10528                  */
10529                 fi->type = ARMFault_QEMU_SFault;
10530                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10531                 *phys_ptr = address;
10532                 *prot = 0;
10533                 return true;
10534             }
10535         }
10536     }
10537 
10538     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
10539                             txattrs, prot, &mpu_is_subpage, fi, NULL);
10540     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
10541     return ret;
10542 }
10543 
10544 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
10545                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10546                                  hwaddr *phys_ptr, int *prot,
10547                                  ARMMMUFaultInfo *fi)
10548 {
10549     int n;
10550     uint32_t mask;
10551     uint32_t base;
10552     bool is_user = regime_is_user(env, mmu_idx);
10553 
10554     if (regime_translation_disabled(env, mmu_idx)) {
10555         /* MPU disabled.  */
10556         *phys_ptr = address;
10557         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10558         return false;
10559     }
10560 
10561     *phys_ptr = address;
10562     for (n = 7; n >= 0; n--) {
10563         base = env->cp15.c6_region[n];
10564         if ((base & 1) == 0) {
10565             continue;
10566         }
10567         mask = 1 << ((base >> 1) & 0x1f);
10568         /* Keep this shift separate from the above to avoid an
10569            (undefined) << 32.  */
10570         mask = (mask << 1) - 1;
10571         if (((base ^ address) & ~mask) == 0) {
10572             break;
10573         }
10574     }
10575     if (n < 0) {
10576         fi->type = ARMFault_Background;
10577         return true;
10578     }
10579 
10580     if (access_type == MMU_INST_FETCH) {
10581         mask = env->cp15.pmsav5_insn_ap;
10582     } else {
10583         mask = env->cp15.pmsav5_data_ap;
10584     }
10585     mask = (mask >> (n * 4)) & 0xf;
10586     switch (mask) {
10587     case 0:
10588         fi->type = ARMFault_Permission;
10589         fi->level = 1;
10590         return true;
10591     case 1:
10592         if (is_user) {
10593             fi->type = ARMFault_Permission;
10594             fi->level = 1;
10595             return true;
10596         }
10597         *prot = PAGE_READ | PAGE_WRITE;
10598         break;
10599     case 2:
10600         *prot = PAGE_READ;
10601         if (!is_user) {
10602             *prot |= PAGE_WRITE;
10603         }
10604         break;
10605     case 3:
10606         *prot = PAGE_READ | PAGE_WRITE;
10607         break;
10608     case 5:
10609         if (is_user) {
10610             fi->type = ARMFault_Permission;
10611             fi->level = 1;
10612             return true;
10613         }
10614         *prot = PAGE_READ;
10615         break;
10616     case 6:
10617         *prot = PAGE_READ;
10618         break;
10619     default:
10620         /* Bad permission.  */
10621         fi->type = ARMFault_Permission;
10622         fi->level = 1;
10623         return true;
10624     }
10625     *prot |= PAGE_EXEC;
10626     return false;
10627 }
10628 
10629 /* Combine either inner or outer cacheability attributes for normal
10630  * memory, according to table D4-42 and pseudocode procedure
10631  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
10632  *
10633  * NB: only stage 1 includes allocation hints (RW bits), leading to
10634  * some asymmetry.
10635  */
10636 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
10637 {
10638     if (s1 == 4 || s2 == 4) {
10639         /* non-cacheable has precedence */
10640         return 4;
10641     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
10642         /* stage 1 write-through takes precedence */
10643         return s1;
10644     } else if (extract32(s2, 2, 2) == 2) {
10645         /* stage 2 write-through takes precedence, but the allocation hint
10646          * is still taken from stage 1
10647          */
10648         return (2 << 2) | extract32(s1, 0, 2);
10649     } else { /* write-back */
10650         return s1;
10651     }
10652 }
10653 
10654 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
10655  * and CombineS1S2Desc()
10656  *
10657  * @s1:      Attributes from stage 1 walk
10658  * @s2:      Attributes from stage 2 walk
10659  */
10660 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
10661 {
10662     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
10663     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
10664     ARMCacheAttrs ret;
10665 
10666     /* Combine shareability attributes (table D4-43) */
10667     if (s1.shareability == 2 || s2.shareability == 2) {
10668         /* if either are outer-shareable, the result is outer-shareable */
10669         ret.shareability = 2;
10670     } else if (s1.shareability == 3 || s2.shareability == 3) {
10671         /* if either are inner-shareable, the result is inner-shareable */
10672         ret.shareability = 3;
10673     } else {
10674         /* both non-shareable */
10675         ret.shareability = 0;
10676     }
10677 
10678     /* Combine memory type and cacheability attributes */
10679     if (s1hi == 0 || s2hi == 0) {
10680         /* Device has precedence over normal */
10681         if (s1lo == 0 || s2lo == 0) {
10682             /* nGnRnE has precedence over anything */
10683             ret.attrs = 0;
10684         } else if (s1lo == 4 || s2lo == 4) {
10685             /* non-Reordering has precedence over Reordering */
10686             ret.attrs = 4;  /* nGnRE */
10687         } else if (s1lo == 8 || s2lo == 8) {
10688             /* non-Gathering has precedence over Gathering */
10689             ret.attrs = 8;  /* nGRE */
10690         } else {
10691             ret.attrs = 0xc; /* GRE */
10692         }
10693 
10694         /* Any location for which the resultant memory type is any
10695          * type of Device memory is always treated as Outer Shareable.
10696          */
10697         ret.shareability = 2;
10698     } else { /* Normal memory */
10699         /* Outer/inner cacheability combine independently */
10700         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
10701                   | combine_cacheattr_nibble(s1lo, s2lo);
10702 
10703         if (ret.attrs == 0x44) {
10704             /* Any location for which the resultant memory type is Normal
10705              * Inner Non-cacheable, Outer Non-cacheable is always treated
10706              * as Outer Shareable.
10707              */
10708             ret.shareability = 2;
10709         }
10710     }
10711 
10712     return ret;
10713 }
10714 
10715 
10716 /* get_phys_addr - get the physical address for this virtual address
10717  *
10718  * Find the physical address corresponding to the given virtual address,
10719  * by doing a translation table walk on MMU based systems or using the
10720  * MPU state on MPU based systems.
10721  *
10722  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
10723  * prot and page_size may not be filled in, and the populated fsr value provides
10724  * information on why the translation aborted, in the format of a
10725  * DFSR/IFSR fault register, with the following caveats:
10726  *  * we honour the short vs long DFSR format differences.
10727  *  * the WnR bit is never set (the caller must do this).
10728  *  * for PSMAv5 based systems we don't bother to return a full FSR format
10729  *    value.
10730  *
10731  * @env: CPUARMState
10732  * @address: virtual address to get physical address for
10733  * @access_type: 0 for read, 1 for write, 2 for execute
10734  * @mmu_idx: MMU index indicating required translation regime
10735  * @phys_ptr: set to the physical address corresponding to the virtual address
10736  * @attrs: set to the memory transaction attributes to use
10737  * @prot: set to the permissions for the page containing phys_ptr
10738  * @page_size: set to the size of the page containing phys_ptr
10739  * @fi: set to fault info if the translation fails
10740  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
10741  */
10742 bool get_phys_addr(CPUARMState *env, target_ulong address,
10743                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
10744                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10745                    target_ulong *page_size,
10746                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10747 {
10748     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10749         /* Call ourselves recursively to do the stage 1 and then stage 2
10750          * translations.
10751          */
10752         if (arm_feature(env, ARM_FEATURE_EL2)) {
10753             hwaddr ipa;
10754             int s2_prot;
10755             int ret;
10756             ARMCacheAttrs cacheattrs2 = {};
10757 
10758             ret = get_phys_addr(env, address, access_type,
10759                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
10760                                 prot, page_size, fi, cacheattrs);
10761 
10762             /* If S1 fails or S2 is disabled, return early.  */
10763             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10764                 *phys_ptr = ipa;
10765                 return ret;
10766             }
10767 
10768             /* S1 is done. Now do S2 translation.  */
10769             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
10770                                      phys_ptr, attrs, &s2_prot,
10771                                      page_size, fi,
10772                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
10773             fi->s2addr = ipa;
10774             /* Combine the S1 and S2 perms.  */
10775             *prot &= s2_prot;
10776 
10777             /* Combine the S1 and S2 cache attributes, if needed */
10778             if (!ret && cacheattrs != NULL) {
10779                 if (env->cp15.hcr_el2 & HCR_DC) {
10780                     /*
10781                      * HCR.DC forces the first stage attributes to
10782                      *  Normal Non-Shareable,
10783                      *  Inner Write-Back Read-Allocate Write-Allocate,
10784                      *  Outer Write-Back Read-Allocate Write-Allocate.
10785                      */
10786                     cacheattrs->attrs = 0xff;
10787                     cacheattrs->shareability = 0;
10788                 }
10789                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
10790             }
10791 
10792             return ret;
10793         } else {
10794             /*
10795              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
10796              */
10797             mmu_idx = stage_1_mmu_idx(mmu_idx);
10798         }
10799     }
10800 
10801     /* The page table entries may downgrade secure to non-secure, but
10802      * cannot upgrade an non-secure translation regime's attributes
10803      * to secure.
10804      */
10805     attrs->secure = regime_is_secure(env, mmu_idx);
10806     attrs->user = regime_is_user(env, mmu_idx);
10807 
10808     /* Fast Context Switch Extension. This doesn't exist at all in v8.
10809      * In v7 and earlier it affects all stage 1 translations.
10810      */
10811     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
10812         && !arm_feature(env, ARM_FEATURE_V8)) {
10813         if (regime_el(env, mmu_idx) == 3) {
10814             address += env->cp15.fcseidr_s;
10815         } else {
10816             address += env->cp15.fcseidr_ns;
10817         }
10818     }
10819 
10820     if (arm_feature(env, ARM_FEATURE_PMSA)) {
10821         bool ret;
10822         *page_size = TARGET_PAGE_SIZE;
10823 
10824         if (arm_feature(env, ARM_FEATURE_V8)) {
10825             /* PMSAv8 */
10826             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
10827                                        phys_ptr, attrs, prot, page_size, fi);
10828         } else if (arm_feature(env, ARM_FEATURE_V7)) {
10829             /* PMSAv7 */
10830             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
10831                                        phys_ptr, prot, page_size, fi);
10832         } else {
10833             /* Pre-v7 MPU */
10834             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
10835                                        phys_ptr, prot, fi);
10836         }
10837         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
10838                       " mmu_idx %u -> %s (prot %c%c%c)\n",
10839                       access_type == MMU_DATA_LOAD ? "reading" :
10840                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
10841                       (uint32_t)address, mmu_idx,
10842                       ret ? "Miss" : "Hit",
10843                       *prot & PAGE_READ ? 'r' : '-',
10844                       *prot & PAGE_WRITE ? 'w' : '-',
10845                       *prot & PAGE_EXEC ? 'x' : '-');
10846 
10847         return ret;
10848     }
10849 
10850     /* Definitely a real MMU, not an MPU */
10851 
10852     if (regime_translation_disabled(env, mmu_idx)) {
10853         /* MMU disabled. */
10854         *phys_ptr = address;
10855         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10856         *page_size = TARGET_PAGE_SIZE;
10857         return 0;
10858     }
10859 
10860     if (regime_using_lpae_format(env, mmu_idx)) {
10861         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
10862                                   phys_ptr, attrs, prot, page_size,
10863                                   fi, cacheattrs);
10864     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
10865         return get_phys_addr_v6(env, address, access_type, mmu_idx,
10866                                 phys_ptr, attrs, prot, page_size, fi);
10867     } else {
10868         return get_phys_addr_v5(env, address, access_type, mmu_idx,
10869                                     phys_ptr, prot, page_size, fi);
10870     }
10871 }
10872 
10873 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
10874                                          MemTxAttrs *attrs)
10875 {
10876     ARMCPU *cpu = ARM_CPU(cs);
10877     CPUARMState *env = &cpu->env;
10878     hwaddr phys_addr;
10879     target_ulong page_size;
10880     int prot;
10881     bool ret;
10882     ARMMMUFaultInfo fi = {};
10883     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
10884 
10885     *attrs = (MemTxAttrs) {};
10886 
10887     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
10888                         attrs, &prot, &page_size, &fi, NULL);
10889 
10890     if (ret) {
10891         return -1;
10892     }
10893     return phys_addr;
10894 }
10895 
10896 #endif
10897 
10898 /* Note that signed overflow is undefined in C.  The following routines are
10899    careful to use unsigned types where modulo arithmetic is required.
10900    Failure to do so _will_ break on newer gcc.  */
10901 
10902 /* Signed saturating arithmetic.  */
10903 
10904 /* Perform 16-bit signed saturating addition.  */
10905 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
10906 {
10907     uint16_t res;
10908 
10909     res = a + b;
10910     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
10911         if (a & 0x8000)
10912             res = 0x8000;
10913         else
10914             res = 0x7fff;
10915     }
10916     return res;
10917 }
10918 
10919 /* Perform 8-bit signed saturating addition.  */
10920 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
10921 {
10922     uint8_t res;
10923 
10924     res = a + b;
10925     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
10926         if (a & 0x80)
10927             res = 0x80;
10928         else
10929             res = 0x7f;
10930     }
10931     return res;
10932 }
10933 
10934 /* Perform 16-bit signed saturating subtraction.  */
10935 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
10936 {
10937     uint16_t res;
10938 
10939     res = a - b;
10940     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
10941         if (a & 0x8000)
10942             res = 0x8000;
10943         else
10944             res = 0x7fff;
10945     }
10946     return res;
10947 }
10948 
10949 /* Perform 8-bit signed saturating subtraction.  */
10950 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
10951 {
10952     uint8_t res;
10953 
10954     res = a - b;
10955     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
10956         if (a & 0x80)
10957             res = 0x80;
10958         else
10959             res = 0x7f;
10960     }
10961     return res;
10962 }
10963 
10964 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
10965 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
10966 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
10967 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
10968 #define PFX q
10969 
10970 #include "op_addsub.h"
10971 
10972 /* Unsigned saturating arithmetic.  */
10973 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
10974 {
10975     uint16_t res;
10976     res = a + b;
10977     if (res < a)
10978         res = 0xffff;
10979     return res;
10980 }
10981 
10982 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
10983 {
10984     if (a > b)
10985         return a - b;
10986     else
10987         return 0;
10988 }
10989 
10990 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
10991 {
10992     uint8_t res;
10993     res = a + b;
10994     if (res < a)
10995         res = 0xff;
10996     return res;
10997 }
10998 
10999 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
11000 {
11001     if (a > b)
11002         return a - b;
11003     else
11004         return 0;
11005 }
11006 
11007 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
11008 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
11009 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
11010 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
11011 #define PFX uq
11012 
11013 #include "op_addsub.h"
11014 
11015 /* Signed modulo arithmetic.  */
11016 #define SARITH16(a, b, n, op) do { \
11017     int32_t sum; \
11018     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
11019     RESULT(sum, n, 16); \
11020     if (sum >= 0) \
11021         ge |= 3 << (n * 2); \
11022     } while(0)
11023 
11024 #define SARITH8(a, b, n, op) do { \
11025     int32_t sum; \
11026     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
11027     RESULT(sum, n, 8); \
11028     if (sum >= 0) \
11029         ge |= 1 << n; \
11030     } while(0)
11031 
11032 
11033 #define ADD16(a, b, n) SARITH16(a, b, n, +)
11034 #define SUB16(a, b, n) SARITH16(a, b, n, -)
11035 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
11036 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
11037 #define PFX s
11038 #define ARITH_GE
11039 
11040 #include "op_addsub.h"
11041 
11042 /* Unsigned modulo arithmetic.  */
11043 #define ADD16(a, b, n) do { \
11044     uint32_t sum; \
11045     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
11046     RESULT(sum, n, 16); \
11047     if ((sum >> 16) == 1) \
11048         ge |= 3 << (n * 2); \
11049     } while(0)
11050 
11051 #define ADD8(a, b, n) do { \
11052     uint32_t sum; \
11053     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
11054     RESULT(sum, n, 8); \
11055     if ((sum >> 8) == 1) \
11056         ge |= 1 << n; \
11057     } while(0)
11058 
11059 #define SUB16(a, b, n) do { \
11060     uint32_t sum; \
11061     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
11062     RESULT(sum, n, 16); \
11063     if ((sum >> 16) == 0) \
11064         ge |= 3 << (n * 2); \
11065     } while(0)
11066 
11067 #define SUB8(a, b, n) do { \
11068     uint32_t sum; \
11069     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
11070     RESULT(sum, n, 8); \
11071     if ((sum >> 8) == 0) \
11072         ge |= 1 << n; \
11073     } while(0)
11074 
11075 #define PFX u
11076 #define ARITH_GE
11077 
11078 #include "op_addsub.h"
11079 
11080 /* Halved signed arithmetic.  */
11081 #define ADD16(a, b, n) \
11082   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
11083 #define SUB16(a, b, n) \
11084   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
11085 #define ADD8(a, b, n) \
11086   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
11087 #define SUB8(a, b, n) \
11088   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
11089 #define PFX sh
11090 
11091 #include "op_addsub.h"
11092 
11093 /* Halved unsigned arithmetic.  */
11094 #define ADD16(a, b, n) \
11095   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11096 #define SUB16(a, b, n) \
11097   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11098 #define ADD8(a, b, n) \
11099   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11100 #define SUB8(a, b, n) \
11101   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11102 #define PFX uh
11103 
11104 #include "op_addsub.h"
11105 
11106 static inline uint8_t do_usad(uint8_t a, uint8_t b)
11107 {
11108     if (a > b)
11109         return a - b;
11110     else
11111         return b - a;
11112 }
11113 
11114 /* Unsigned sum of absolute byte differences.  */
11115 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
11116 {
11117     uint32_t sum;
11118     sum = do_usad(a, b);
11119     sum += do_usad(a >> 8, b >> 8);
11120     sum += do_usad(a >> 16, b >>16);
11121     sum += do_usad(a >> 24, b >> 24);
11122     return sum;
11123 }
11124 
11125 /* For ARMv6 SEL instruction.  */
11126 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
11127 {
11128     uint32_t mask;
11129 
11130     mask = 0;
11131     if (flags & 1)
11132         mask |= 0xff;
11133     if (flags & 2)
11134         mask |= 0xff00;
11135     if (flags & 4)
11136         mask |= 0xff0000;
11137     if (flags & 8)
11138         mask |= 0xff000000;
11139     return (a & mask) | (b & ~mask);
11140 }
11141 
11142 /* CRC helpers.
11143  * The upper bytes of val (above the number specified by 'bytes') must have
11144  * been zeroed out by the caller.
11145  */
11146 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
11147 {
11148     uint8_t buf[4];
11149 
11150     stl_le_p(buf, val);
11151 
11152     /* zlib crc32 converts the accumulator and output to one's complement.  */
11153     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
11154 }
11155 
11156 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
11157 {
11158     uint8_t buf[4];
11159 
11160     stl_le_p(buf, val);
11161 
11162     /* Linux crc32c converts the output to one's complement.  */
11163     return crc32c(acc, buf, bytes) ^ 0xffffffff;
11164 }
11165 
11166 /* Return the exception level to which FP-disabled exceptions should
11167  * be taken, or 0 if FP is enabled.
11168  */
11169 int fp_exception_el(CPUARMState *env, int cur_el)
11170 {
11171 #ifndef CONFIG_USER_ONLY
11172     int fpen;
11173 
11174     /* CPACR and the CPTR registers don't exist before v6, so FP is
11175      * always accessible
11176      */
11177     if (!arm_feature(env, ARM_FEATURE_V6)) {
11178         return 0;
11179     }
11180 
11181     if (arm_feature(env, ARM_FEATURE_M)) {
11182         /* CPACR can cause a NOCP UsageFault taken to current security state */
11183         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
11184             return 1;
11185         }
11186 
11187         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
11188             if (!extract32(env->v7m.nsacr, 10, 1)) {
11189                 /* FP insns cause a NOCP UsageFault taken to Secure */
11190                 return 3;
11191             }
11192         }
11193 
11194         return 0;
11195     }
11196 
11197     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
11198      * 0, 2 : trap EL0 and EL1/PL1 accesses
11199      * 1    : trap only EL0 accesses
11200      * 3    : trap no accesses
11201      */
11202     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
11203     switch (fpen) {
11204     case 0:
11205     case 2:
11206         if (cur_el == 0 || cur_el == 1) {
11207             /* Trap to PL1, which might be EL1 or EL3 */
11208             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
11209                 return 3;
11210             }
11211             return 1;
11212         }
11213         if (cur_el == 3 && !is_a64(env)) {
11214             /* Secure PL1 running at EL3 */
11215             return 3;
11216         }
11217         break;
11218     case 1:
11219         if (cur_el == 0) {
11220             return 1;
11221         }
11222         break;
11223     case 3:
11224         break;
11225     }
11226 
11227     /*
11228      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
11229      * to control non-secure access to the FPU. It doesn't have any
11230      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
11231      */
11232     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
11233          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
11234         if (!extract32(env->cp15.nsacr, 10, 1)) {
11235             /* FP insns act as UNDEF */
11236             return cur_el == 2 ? 2 : 1;
11237         }
11238     }
11239 
11240     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
11241      * check because zero bits in the registers mean "don't trap".
11242      */
11243 
11244     /* CPTR_EL2 : present in v7VE or v8 */
11245     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
11246         && !arm_is_secure_below_el3(env)) {
11247         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
11248         return 2;
11249     }
11250 
11251     /* CPTR_EL3 : present in v8 */
11252     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
11253         /* Trap all FP ops to EL3 */
11254         return 3;
11255     }
11256 #endif
11257     return 0;
11258 }
11259 
11260 #ifndef CONFIG_TCG
11261 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
11262 {
11263     g_assert_not_reached();
11264 }
11265 #endif
11266 
11267 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
11268 {
11269     if (arm_feature(env, ARM_FEATURE_M)) {
11270         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
11271     }
11272 
11273     if (el < 2 && arm_is_secure_below_el3(env)) {
11274         return ARMMMUIdx_S1SE0 + el;
11275     } else {
11276         return ARMMMUIdx_S12NSE0 + el;
11277     }
11278 }
11279 
11280 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
11281 {
11282     return arm_mmu_idx_el(env, arm_current_el(env));
11283 }
11284 
11285 int cpu_mmu_index(CPUARMState *env, bool ifetch)
11286 {
11287     return arm_to_core_mmu_idx(arm_mmu_idx(env));
11288 }
11289 
11290 #ifndef CONFIG_USER_ONLY
11291 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
11292 {
11293     return stage_1_mmu_idx(arm_mmu_idx(env));
11294 }
11295 #endif
11296 
11297 static uint32_t rebuild_hflags_common(CPUARMState *env, int fp_el,
11298                                       ARMMMUIdx mmu_idx, uint32_t flags)
11299 {
11300     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
11301     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX,
11302                        arm_to_core_mmu_idx(mmu_idx));
11303 
11304     if (arm_singlestep_active(env)) {
11305         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
11306     }
11307     return flags;
11308 }
11309 
11310 static uint32_t rebuild_hflags_common_32(CPUARMState *env, int fp_el,
11311                                          ARMMMUIdx mmu_idx, uint32_t flags)
11312 {
11313     bool sctlr_b = arm_sctlr_b(env);
11314 
11315     if (sctlr_b) {
11316         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, 1);
11317     }
11318     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
11319         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
11320     }
11321     flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
11322 
11323     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
11324 }
11325 
11326 static uint32_t rebuild_hflags_m32(CPUARMState *env, int fp_el,
11327                                    ARMMMUIdx mmu_idx)
11328 {
11329     uint32_t flags = 0;
11330 
11331     /* v8M always enables the fpu.  */
11332     flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
11333 
11334     if (arm_v7m_is_handler_mode(env)) {
11335         flags = FIELD_DP32(flags, TBFLAG_A32, HANDLER, 1);
11336     }
11337 
11338     /*
11339      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
11340      * is suppressing them because the requested execution priority
11341      * is less than 0.
11342      */
11343     if (arm_feature(env, ARM_FEATURE_V8) &&
11344         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
11345           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
11346         flags = FIELD_DP32(flags, TBFLAG_A32, STACKCHECK, 1);
11347     }
11348 
11349     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
11350 }
11351 
11352 static uint32_t rebuild_hflags_aprofile(CPUARMState *env)
11353 {
11354     int flags = 0;
11355 
11356     flags = FIELD_DP32(flags, TBFLAG_ANY, DEBUG_TARGET_EL,
11357                        arm_debug_target_el(env));
11358     return flags;
11359 }
11360 
11361 static uint32_t rebuild_hflags_a32(CPUARMState *env, int fp_el,
11362                                    ARMMMUIdx mmu_idx)
11363 {
11364     uint32_t flags = rebuild_hflags_aprofile(env);
11365 
11366     if (arm_el_is_aa64(env, 1)) {
11367         flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
11368     }
11369 
11370     if (arm_current_el(env) < 2 && env->cp15.hstr_el2 &&
11371         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
11372         flags = FIELD_DP32(flags, TBFLAG_A32, HSTR_ACTIVE, 1);
11373     }
11374 
11375     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
11376 }
11377 
11378 static uint32_t rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
11379                                    ARMMMUIdx mmu_idx)
11380 {
11381     uint32_t flags = rebuild_hflags_aprofile(env);
11382     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
11383     ARMVAParameters p0 = aa64_va_parameters_both(env, 0, stage1);
11384     uint64_t sctlr;
11385     int tbii, tbid;
11386 
11387     flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
11388 
11389     /* FIXME: ARMv8.1-VHE S2 translation regime.  */
11390     if (regime_el(env, stage1) < 2) {
11391         ARMVAParameters p1 = aa64_va_parameters_both(env, -1, stage1);
11392         tbid = (p1.tbi << 1) | p0.tbi;
11393         tbii = tbid & ~((p1.tbid << 1) | p0.tbid);
11394     } else {
11395         tbid = p0.tbi;
11396         tbii = tbid & !p0.tbid;
11397     }
11398 
11399     flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
11400     flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
11401 
11402     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
11403         int sve_el = sve_exception_el(env, el);
11404         uint32_t zcr_len;
11405 
11406         /*
11407          * If SVE is disabled, but FP is enabled,
11408          * then the effective len is 0.
11409          */
11410         if (sve_el != 0 && fp_el == 0) {
11411             zcr_len = 0;
11412         } else {
11413             zcr_len = sve_zcr_len_for_el(env, el);
11414         }
11415         flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
11416         flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
11417     }
11418 
11419     sctlr = arm_sctlr(env, el);
11420 
11421     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
11422         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
11423     }
11424 
11425     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
11426         /*
11427          * In order to save space in flags, we record only whether
11428          * pauth is "inactive", meaning all insns are implemented as
11429          * a nop, or "active" when some action must be performed.
11430          * The decision of which action to take is left to a helper.
11431          */
11432         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
11433             flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
11434         }
11435     }
11436 
11437     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
11438         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
11439         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
11440             flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
11441         }
11442     }
11443 
11444     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
11445 }
11446 
11447 static uint32_t rebuild_hflags_internal(CPUARMState *env)
11448 {
11449     int el = arm_current_el(env);
11450     int fp_el = fp_exception_el(env, el);
11451     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11452 
11453     if (is_a64(env)) {
11454         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
11455     } else if (arm_feature(env, ARM_FEATURE_M)) {
11456         return rebuild_hflags_m32(env, fp_el, mmu_idx);
11457     } else {
11458         return rebuild_hflags_a32(env, fp_el, mmu_idx);
11459     }
11460 }
11461 
11462 void arm_rebuild_hflags(CPUARMState *env)
11463 {
11464     env->hflags = rebuild_hflags_internal(env);
11465 }
11466 
11467 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
11468 {
11469     int fp_el = fp_exception_el(env, el);
11470     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11471 
11472     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
11473 }
11474 
11475 /*
11476  * If we have triggered a EL state change we can't rely on the
11477  * translator having passed it too us, we need to recompute.
11478  */
11479 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
11480 {
11481     int el = arm_current_el(env);
11482     int fp_el = fp_exception_el(env, el);
11483     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11484     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
11485 }
11486 
11487 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
11488 {
11489     int fp_el = fp_exception_el(env, el);
11490     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11491 
11492     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
11493 }
11494 
11495 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
11496 {
11497     int fp_el = fp_exception_el(env, el);
11498     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11499 
11500     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
11501 }
11502 
11503 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
11504                           target_ulong *cs_base, uint32_t *pflags)
11505 {
11506     uint32_t flags = env->hflags;
11507     uint32_t pstate_for_ss;
11508 
11509     *cs_base = 0;
11510 #ifdef CONFIG_DEBUG_TCG
11511     assert(flags == rebuild_hflags_internal(env));
11512 #endif
11513 
11514     if (FIELD_EX32(flags, TBFLAG_ANY, AARCH64_STATE)) {
11515         *pc = env->pc;
11516         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
11517             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
11518         }
11519         pstate_for_ss = env->pstate;
11520     } else {
11521         *pc = env->regs[15];
11522 
11523         if (arm_feature(env, ARM_FEATURE_M)) {
11524             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
11525                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
11526                 != env->v7m.secure) {
11527                 flags = FIELD_DP32(flags, TBFLAG_A32, FPCCR_S_WRONG, 1);
11528             }
11529 
11530             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
11531                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
11532                  (env->v7m.secure &&
11533                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
11534                 /*
11535                  * ASPEN is set, but FPCA/SFPA indicate that there is no
11536                  * active FP context; we must create a new FP context before
11537                  * executing any FP insn.
11538                  */
11539                 flags = FIELD_DP32(flags, TBFLAG_A32, NEW_FP_CTXT_NEEDED, 1);
11540             }
11541 
11542             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
11543             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
11544                 flags = FIELD_DP32(flags, TBFLAG_A32, LSPACT, 1);
11545             }
11546         } else {
11547             /*
11548              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
11549              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
11550              */
11551             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
11552                 flags = FIELD_DP32(flags, TBFLAG_A32,
11553                                    XSCALE_CPAR, env->cp15.c15_cpar);
11554             } else {
11555                 flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN,
11556                                    env->vfp.vec_len);
11557                 flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE,
11558                                    env->vfp.vec_stride);
11559             }
11560             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
11561                 flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
11562             }
11563         }
11564 
11565         flags = FIELD_DP32(flags, TBFLAG_A32, THUMB, env->thumb);
11566         flags = FIELD_DP32(flags, TBFLAG_A32, CONDEXEC, env->condexec_bits);
11567         pstate_for_ss = env->uncached_cpsr;
11568     }
11569 
11570     /*
11571      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
11572      * states defined in the ARM ARM for software singlestep:
11573      *  SS_ACTIVE   PSTATE.SS   State
11574      *     0            x       Inactive (the TB flag for SS is always 0)
11575      *     1            0       Active-pending
11576      *     1            1       Active-not-pending
11577      * SS_ACTIVE is set in hflags; PSTATE_SS is computed every TB.
11578      */
11579     if (FIELD_EX32(flags, TBFLAG_ANY, SS_ACTIVE) &&
11580         (pstate_for_ss & PSTATE_SS)) {
11581         flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
11582     }
11583 
11584     *pflags = flags;
11585 }
11586 
11587 #ifdef TARGET_AARCH64
11588 /*
11589  * The manual says that when SVE is enabled and VQ is widened the
11590  * implementation is allowed to zero the previously inaccessible
11591  * portion of the registers.  The corollary to that is that when
11592  * SVE is enabled and VQ is narrowed we are also allowed to zero
11593  * the now inaccessible portion of the registers.
11594  *
11595  * The intent of this is that no predicate bit beyond VQ is ever set.
11596  * Which means that some operations on predicate registers themselves
11597  * may operate on full uint64_t or even unrolled across the maximum
11598  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
11599  * may well be cheaper than conditionals to restrict the operation
11600  * to the relevant portion of a uint16_t[16].
11601  */
11602 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
11603 {
11604     int i, j;
11605     uint64_t pmask;
11606 
11607     assert(vq >= 1 && vq <= ARM_MAX_VQ);
11608     assert(vq <= env_archcpu(env)->sve_max_vq);
11609 
11610     /* Zap the high bits of the zregs.  */
11611     for (i = 0; i < 32; i++) {
11612         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
11613     }
11614 
11615     /* Zap the high bits of the pregs and ffr.  */
11616     pmask = 0;
11617     if (vq & 3) {
11618         pmask = ~(-1ULL << (16 * (vq & 3)));
11619     }
11620     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
11621         for (i = 0; i < 17; ++i) {
11622             env->vfp.pregs[i].p[j] &= pmask;
11623         }
11624         pmask = 0;
11625     }
11626 }
11627 
11628 /*
11629  * Notice a change in SVE vector size when changing EL.
11630  */
11631 void aarch64_sve_change_el(CPUARMState *env, int old_el,
11632                            int new_el, bool el0_a64)
11633 {
11634     ARMCPU *cpu = env_archcpu(env);
11635     int old_len, new_len;
11636     bool old_a64, new_a64;
11637 
11638     /* Nothing to do if no SVE.  */
11639     if (!cpu_isar_feature(aa64_sve, cpu)) {
11640         return;
11641     }
11642 
11643     /* Nothing to do if FP is disabled in either EL.  */
11644     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
11645         return;
11646     }
11647 
11648     /*
11649      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
11650      * at ELx, or not available because the EL is in AArch32 state, then
11651      * for all purposes other than a direct read, the ZCR_ELx.LEN field
11652      * has an effective value of 0".
11653      *
11654      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
11655      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
11656      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
11657      * we already have the correct register contents when encountering the
11658      * vq0->vq0 transition between EL0->EL1.
11659      */
11660     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
11661     old_len = (old_a64 && !sve_exception_el(env, old_el)
11662                ? sve_zcr_len_for_el(env, old_el) : 0);
11663     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
11664     new_len = (new_a64 && !sve_exception_el(env, new_el)
11665                ? sve_zcr_len_for_el(env, new_el) : 0);
11666 
11667     /* When changing vector length, clear inaccessible state.  */
11668     if (new_len < old_len) {
11669         aarch64_sve_narrow_vq(env, new_len + 1);
11670     }
11671 }
11672 #endif
11673