xref: /openbmc/qemu/target/arm/helper.c (revision 6a0acfff)
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 #include "qemu/osdep.h"
9 #include "qemu/units.h"
10 #include "target/arm/idau.h"
11 #include "trace.h"
12 #include "cpu.h"
13 #include "internals.h"
14 #include "exec/gdbstub.h"
15 #include "exec/helper-proto.h"
16 #include "qemu/host-utils.h"
17 #include "sysemu/sysemu.h"
18 #include "qemu/bitops.h"
19 #include "qemu/crc32c.h"
20 #include "qemu/qemu-print.h"
21 #include "exec/exec-all.h"
22 #include <zlib.h> /* For crc32 */
23 #include "hw/irq.h"
24 #include "hw/semihosting/semihost.h"
25 #include "sysemu/cpus.h"
26 #include "sysemu/kvm.h"
27 #include "qemu/range.h"
28 #include "qapi/qapi-commands-machine-target.h"
29 #include "qapi/error.h"
30 #include "qemu/guest-random.h"
31 #ifdef CONFIG_TCG
32 #include "arm_ldst.h"
33 #include "exec/cpu_ldst.h"
34 #endif
35 
36 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
37 
38 #ifndef CONFIG_USER_ONLY
39 
40 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
41                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
42                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
43                                target_ulong *page_size_ptr,
44                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
45 #endif
46 
47 static void switch_mode(CPUARMState *env, int mode);
48 
49 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
50 {
51     int nregs;
52 
53     /* VFP data registers are always little-endian.  */
54     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
55     if (reg < nregs) {
56         stq_le_p(buf, *aa32_vfp_dreg(env, reg));
57         return 8;
58     }
59     if (arm_feature(env, ARM_FEATURE_NEON)) {
60         /* Aliases for Q regs.  */
61         nregs += 16;
62         if (reg < nregs) {
63             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
64             stq_le_p(buf, q[0]);
65             stq_le_p(buf + 8, q[1]);
66             return 16;
67         }
68     }
69     switch (reg - nregs) {
70     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
71     case 1: stl_p(buf, vfp_get_fpscr(env)); return 4;
72     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
73     }
74     return 0;
75 }
76 
77 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
78 {
79     int nregs;
80 
81     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
82     if (reg < nregs) {
83         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
84         return 8;
85     }
86     if (arm_feature(env, ARM_FEATURE_NEON)) {
87         nregs += 16;
88         if (reg < nregs) {
89             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
90             q[0] = ldq_le_p(buf);
91             q[1] = ldq_le_p(buf + 8);
92             return 16;
93         }
94     }
95     switch (reg - nregs) {
96     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
97     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
98     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
99     }
100     return 0;
101 }
102 
103 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
104 {
105     switch (reg) {
106     case 0 ... 31:
107         /* 128 bit FP register */
108         {
109             uint64_t *q = aa64_vfp_qreg(env, reg);
110             stq_le_p(buf, q[0]);
111             stq_le_p(buf + 8, q[1]);
112             return 16;
113         }
114     case 32:
115         /* FPSR */
116         stl_p(buf, vfp_get_fpsr(env));
117         return 4;
118     case 33:
119         /* FPCR */
120         stl_p(buf, vfp_get_fpcr(env));
121         return 4;
122     default:
123         return 0;
124     }
125 }
126 
127 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
128 {
129     switch (reg) {
130     case 0 ... 31:
131         /* 128 bit FP register */
132         {
133             uint64_t *q = aa64_vfp_qreg(env, reg);
134             q[0] = ldq_le_p(buf);
135             q[1] = ldq_le_p(buf + 8);
136             return 16;
137         }
138     case 32:
139         /* FPSR */
140         vfp_set_fpsr(env, ldl_p(buf));
141         return 4;
142     case 33:
143         /* FPCR */
144         vfp_set_fpcr(env, ldl_p(buf));
145         return 4;
146     default:
147         return 0;
148     }
149 }
150 
151 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
152 {
153     assert(ri->fieldoffset);
154     if (cpreg_field_is_64bit(ri)) {
155         return CPREG_FIELD64(env, ri);
156     } else {
157         return CPREG_FIELD32(env, ri);
158     }
159 }
160 
161 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
162                       uint64_t value)
163 {
164     assert(ri->fieldoffset);
165     if (cpreg_field_is_64bit(ri)) {
166         CPREG_FIELD64(env, ri) = value;
167     } else {
168         CPREG_FIELD32(env, ri) = value;
169     }
170 }
171 
172 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
173 {
174     return (char *)env + ri->fieldoffset;
175 }
176 
177 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
178 {
179     /* Raw read of a coprocessor register (as needed for migration, etc). */
180     if (ri->type & ARM_CP_CONST) {
181         return ri->resetvalue;
182     } else if (ri->raw_readfn) {
183         return ri->raw_readfn(env, ri);
184     } else if (ri->readfn) {
185         return ri->readfn(env, ri);
186     } else {
187         return raw_read(env, ri);
188     }
189 }
190 
191 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
192                              uint64_t v)
193 {
194     /* Raw write of a coprocessor register (as needed for migration, etc).
195      * Note that constant registers are treated as write-ignored; the
196      * caller should check for success by whether a readback gives the
197      * value written.
198      */
199     if (ri->type & ARM_CP_CONST) {
200         return;
201     } else if (ri->raw_writefn) {
202         ri->raw_writefn(env, ri, v);
203     } else if (ri->writefn) {
204         ri->writefn(env, ri, v);
205     } else {
206         raw_write(env, ri, v);
207     }
208 }
209 
210 static int arm_gdb_get_sysreg(CPUARMState *env, uint8_t *buf, int reg)
211 {
212     ARMCPU *cpu = env_archcpu(env);
213     const ARMCPRegInfo *ri;
214     uint32_t key;
215 
216     key = cpu->dyn_xml.cpregs_keys[reg];
217     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
218     if (ri) {
219         if (cpreg_field_is_64bit(ri)) {
220             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
221         } else {
222             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
223         }
224     }
225     return 0;
226 }
227 
228 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
229 {
230     return 0;
231 }
232 
233 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
234 {
235    /* Return true if the regdef would cause an assertion if you called
236     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
237     * program bug for it not to have the NO_RAW flag).
238     * NB that returning false here doesn't necessarily mean that calling
239     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
240     * read/write access functions which are safe for raw use" from "has
241     * read/write access functions which have side effects but has forgotten
242     * to provide raw access functions".
243     * The tests here line up with the conditions in read/write_raw_cp_reg()
244     * and assertions in raw_read()/raw_write().
245     */
246     if ((ri->type & ARM_CP_CONST) ||
247         ri->fieldoffset ||
248         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
249         return false;
250     }
251     return true;
252 }
253 
254 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
255 {
256     /* Write the coprocessor state from cpu->env to the (index,value) list. */
257     int i;
258     bool ok = true;
259 
260     for (i = 0; i < cpu->cpreg_array_len; i++) {
261         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
262         const ARMCPRegInfo *ri;
263         uint64_t newval;
264 
265         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
266         if (!ri) {
267             ok = false;
268             continue;
269         }
270         if (ri->type & ARM_CP_NO_RAW) {
271             continue;
272         }
273 
274         newval = read_raw_cp_reg(&cpu->env, ri);
275         if (kvm_sync) {
276             /*
277              * Only sync if the previous list->cpustate sync succeeded.
278              * Rather than tracking the success/failure state for every
279              * item in the list, we just recheck "does the raw write we must
280              * have made in write_list_to_cpustate() read back OK" here.
281              */
282             uint64_t oldval = cpu->cpreg_values[i];
283 
284             if (oldval == newval) {
285                 continue;
286             }
287 
288             write_raw_cp_reg(&cpu->env, ri, oldval);
289             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
290                 continue;
291             }
292 
293             write_raw_cp_reg(&cpu->env, ri, newval);
294         }
295         cpu->cpreg_values[i] = newval;
296     }
297     return ok;
298 }
299 
300 bool write_list_to_cpustate(ARMCPU *cpu)
301 {
302     int i;
303     bool ok = true;
304 
305     for (i = 0; i < cpu->cpreg_array_len; i++) {
306         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
307         uint64_t v = cpu->cpreg_values[i];
308         const ARMCPRegInfo *ri;
309 
310         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
311         if (!ri) {
312             ok = false;
313             continue;
314         }
315         if (ri->type & ARM_CP_NO_RAW) {
316             continue;
317         }
318         /* Write value and confirm it reads back as written
319          * (to catch read-only registers and partially read-only
320          * registers where the incoming migration value doesn't match)
321          */
322         write_raw_cp_reg(&cpu->env, ri, v);
323         if (read_raw_cp_reg(&cpu->env, ri) != v) {
324             ok = false;
325         }
326     }
327     return ok;
328 }
329 
330 static void add_cpreg_to_list(gpointer key, gpointer opaque)
331 {
332     ARMCPU *cpu = opaque;
333     uint64_t regidx;
334     const ARMCPRegInfo *ri;
335 
336     regidx = *(uint32_t *)key;
337     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
338 
339     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
340         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
341         /* The value array need not be initialized at this point */
342         cpu->cpreg_array_len++;
343     }
344 }
345 
346 static void count_cpreg(gpointer key, gpointer opaque)
347 {
348     ARMCPU *cpu = opaque;
349     uint64_t regidx;
350     const ARMCPRegInfo *ri;
351 
352     regidx = *(uint32_t *)key;
353     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
354 
355     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
356         cpu->cpreg_array_len++;
357     }
358 }
359 
360 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
361 {
362     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
363     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
364 
365     if (aidx > bidx) {
366         return 1;
367     }
368     if (aidx < bidx) {
369         return -1;
370     }
371     return 0;
372 }
373 
374 void init_cpreg_list(ARMCPU *cpu)
375 {
376     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
377      * Note that we require cpreg_tuples[] to be sorted by key ID.
378      */
379     GList *keys;
380     int arraylen;
381 
382     keys = g_hash_table_get_keys(cpu->cp_regs);
383     keys = g_list_sort(keys, cpreg_key_compare);
384 
385     cpu->cpreg_array_len = 0;
386 
387     g_list_foreach(keys, count_cpreg, cpu);
388 
389     arraylen = cpu->cpreg_array_len;
390     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
391     cpu->cpreg_values = g_new(uint64_t, arraylen);
392     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
393     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
394     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
395     cpu->cpreg_array_len = 0;
396 
397     g_list_foreach(keys, add_cpreg_to_list, cpu);
398 
399     assert(cpu->cpreg_array_len == arraylen);
400 
401     g_list_free(keys);
402 }
403 
404 /*
405  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
406  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
407  *
408  * access_el3_aa32ns: Used to check AArch32 register views.
409  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
410  */
411 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
412                                         const ARMCPRegInfo *ri,
413                                         bool isread)
414 {
415     bool secure = arm_is_secure_below_el3(env);
416 
417     assert(!arm_el_is_aa64(env, 3));
418     if (secure) {
419         return CP_ACCESS_TRAP_UNCATEGORIZED;
420     }
421     return CP_ACCESS_OK;
422 }
423 
424 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
425                                                 const ARMCPRegInfo *ri,
426                                                 bool isread)
427 {
428     if (!arm_el_is_aa64(env, 3)) {
429         return access_el3_aa32ns(env, ri, isread);
430     }
431     return CP_ACCESS_OK;
432 }
433 
434 /* Some secure-only AArch32 registers trap to EL3 if used from
435  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
436  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
437  * We assume that the .access field is set to PL1_RW.
438  */
439 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
440                                             const ARMCPRegInfo *ri,
441                                             bool isread)
442 {
443     if (arm_current_el(env) == 3) {
444         return CP_ACCESS_OK;
445     }
446     if (arm_is_secure_below_el3(env)) {
447         return CP_ACCESS_TRAP_EL3;
448     }
449     /* This will be EL1 NS and EL2 NS, which just UNDEF */
450     return CP_ACCESS_TRAP_UNCATEGORIZED;
451 }
452 
453 /* Check for traps to "powerdown debug" registers, which are controlled
454  * by MDCR.TDOSA
455  */
456 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
457                                    bool isread)
458 {
459     int el = arm_current_el(env);
460     bool mdcr_el2_tdosa = (env->cp15.mdcr_el2 & MDCR_TDOSA) ||
461         (env->cp15.mdcr_el2 & MDCR_TDE) ||
462         (arm_hcr_el2_eff(env) & HCR_TGE);
463 
464     if (el < 2 && mdcr_el2_tdosa && !arm_is_secure_below_el3(env)) {
465         return CP_ACCESS_TRAP_EL2;
466     }
467     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
468         return CP_ACCESS_TRAP_EL3;
469     }
470     return CP_ACCESS_OK;
471 }
472 
473 /* Check for traps to "debug ROM" registers, which are controlled
474  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
475  */
476 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
477                                   bool isread)
478 {
479     int el = arm_current_el(env);
480     bool mdcr_el2_tdra = (env->cp15.mdcr_el2 & MDCR_TDRA) ||
481         (env->cp15.mdcr_el2 & MDCR_TDE) ||
482         (arm_hcr_el2_eff(env) & HCR_TGE);
483 
484     if (el < 2 && mdcr_el2_tdra && !arm_is_secure_below_el3(env)) {
485         return CP_ACCESS_TRAP_EL2;
486     }
487     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
488         return CP_ACCESS_TRAP_EL3;
489     }
490     return CP_ACCESS_OK;
491 }
492 
493 /* Check for traps to general debug registers, which are controlled
494  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
495  */
496 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
497                                   bool isread)
498 {
499     int el = arm_current_el(env);
500     bool mdcr_el2_tda = (env->cp15.mdcr_el2 & MDCR_TDA) ||
501         (env->cp15.mdcr_el2 & MDCR_TDE) ||
502         (arm_hcr_el2_eff(env) & HCR_TGE);
503 
504     if (el < 2 && mdcr_el2_tda && !arm_is_secure_below_el3(env)) {
505         return CP_ACCESS_TRAP_EL2;
506     }
507     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
508         return CP_ACCESS_TRAP_EL3;
509     }
510     return CP_ACCESS_OK;
511 }
512 
513 /* Check for traps to performance monitor registers, which are controlled
514  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
515  */
516 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
517                                  bool isread)
518 {
519     int el = arm_current_el(env);
520 
521     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
522         && !arm_is_secure_below_el3(env)) {
523         return CP_ACCESS_TRAP_EL2;
524     }
525     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
526         return CP_ACCESS_TRAP_EL3;
527     }
528     return CP_ACCESS_OK;
529 }
530 
531 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
532 {
533     ARMCPU *cpu = env_archcpu(env);
534 
535     raw_write(env, ri, value);
536     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
537 }
538 
539 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
540 {
541     ARMCPU *cpu = env_archcpu(env);
542 
543     if (raw_read(env, ri) != value) {
544         /* Unlike real hardware the qemu TLB uses virtual addresses,
545          * not modified virtual addresses, so this causes a TLB flush.
546          */
547         tlb_flush(CPU(cpu));
548         raw_write(env, ri, value);
549     }
550 }
551 
552 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
553                              uint64_t value)
554 {
555     ARMCPU *cpu = env_archcpu(env);
556 
557     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
558         && !extended_addresses_enabled(env)) {
559         /* For VMSA (when not using the LPAE long descriptor page table
560          * format) this register includes the ASID, so do a TLB flush.
561          * For PMSA it is purely a process ID and no action is needed.
562          */
563         tlb_flush(CPU(cpu));
564     }
565     raw_write(env, ri, value);
566 }
567 
568 /* IS variants of TLB operations must affect all cores */
569 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
570                              uint64_t value)
571 {
572     CPUState *cs = env_cpu(env);
573 
574     tlb_flush_all_cpus_synced(cs);
575 }
576 
577 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
578                              uint64_t value)
579 {
580     CPUState *cs = env_cpu(env);
581 
582     tlb_flush_all_cpus_synced(cs);
583 }
584 
585 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
586                              uint64_t value)
587 {
588     CPUState *cs = env_cpu(env);
589 
590     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
591 }
592 
593 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
594                              uint64_t value)
595 {
596     CPUState *cs = env_cpu(env);
597 
598     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
599 }
600 
601 /*
602  * Non-IS variants of TLB operations are upgraded to
603  * IS versions if we are at NS EL1 and HCR_EL2.FB is set to
604  * force broadcast of these operations.
605  */
606 static bool tlb_force_broadcast(CPUARMState *env)
607 {
608     return (env->cp15.hcr_el2 & HCR_FB) &&
609         arm_current_el(env) == 1 && arm_is_secure_below_el3(env);
610 }
611 
612 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
613                           uint64_t value)
614 {
615     /* Invalidate all (TLBIALL) */
616     ARMCPU *cpu = env_archcpu(env);
617 
618     if (tlb_force_broadcast(env)) {
619         tlbiall_is_write(env, NULL, value);
620         return;
621     }
622 
623     tlb_flush(CPU(cpu));
624 }
625 
626 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
627                           uint64_t value)
628 {
629     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
630     ARMCPU *cpu = env_archcpu(env);
631 
632     if (tlb_force_broadcast(env)) {
633         tlbimva_is_write(env, NULL, value);
634         return;
635     }
636 
637     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
638 }
639 
640 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
641                            uint64_t value)
642 {
643     /* Invalidate by ASID (TLBIASID) */
644     ARMCPU *cpu = env_archcpu(env);
645 
646     if (tlb_force_broadcast(env)) {
647         tlbiasid_is_write(env, NULL, value);
648         return;
649     }
650 
651     tlb_flush(CPU(cpu));
652 }
653 
654 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
655                            uint64_t value)
656 {
657     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
658     ARMCPU *cpu = env_archcpu(env);
659 
660     if (tlb_force_broadcast(env)) {
661         tlbimvaa_is_write(env, NULL, value);
662         return;
663     }
664 
665     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
666 }
667 
668 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
669                                uint64_t value)
670 {
671     CPUState *cs = env_cpu(env);
672 
673     tlb_flush_by_mmuidx(cs,
674                         ARMMMUIdxBit_S12NSE1 |
675                         ARMMMUIdxBit_S12NSE0 |
676                         ARMMMUIdxBit_S2NS);
677 }
678 
679 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
680                                   uint64_t value)
681 {
682     CPUState *cs = env_cpu(env);
683 
684     tlb_flush_by_mmuidx_all_cpus_synced(cs,
685                                         ARMMMUIdxBit_S12NSE1 |
686                                         ARMMMUIdxBit_S12NSE0 |
687                                         ARMMMUIdxBit_S2NS);
688 }
689 
690 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
691                             uint64_t value)
692 {
693     /* Invalidate by IPA. This has to invalidate any structures that
694      * contain only stage 2 translation information, but does not need
695      * to apply to structures that contain combined stage 1 and stage 2
696      * translation information.
697      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
698      */
699     CPUState *cs = env_cpu(env);
700     uint64_t pageaddr;
701 
702     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
703         return;
704     }
705 
706     pageaddr = sextract64(value << 12, 0, 40);
707 
708     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
709 }
710 
711 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
712                                uint64_t value)
713 {
714     CPUState *cs = env_cpu(env);
715     uint64_t pageaddr;
716 
717     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
718         return;
719     }
720 
721     pageaddr = sextract64(value << 12, 0, 40);
722 
723     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
724                                              ARMMMUIdxBit_S2NS);
725 }
726 
727 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
728                               uint64_t value)
729 {
730     CPUState *cs = env_cpu(env);
731 
732     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
733 }
734 
735 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
736                                  uint64_t value)
737 {
738     CPUState *cs = env_cpu(env);
739 
740     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
741 }
742 
743 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
744                               uint64_t value)
745 {
746     CPUState *cs = env_cpu(env);
747     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
748 
749     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
750 }
751 
752 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
753                                  uint64_t value)
754 {
755     CPUState *cs = env_cpu(env);
756     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
757 
758     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
759                                              ARMMMUIdxBit_S1E2);
760 }
761 
762 static const ARMCPRegInfo cp_reginfo[] = {
763     /* Define the secure and non-secure FCSE identifier CP registers
764      * separately because there is no secure bank in V8 (no _EL3).  This allows
765      * the secure register to be properly reset and migrated. There is also no
766      * v8 EL1 version of the register so the non-secure instance stands alone.
767      */
768     { .name = "FCSEIDR",
769       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
770       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
771       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
772       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
773     { .name = "FCSEIDR_S",
774       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
775       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
776       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
777       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
778     /* Define the secure and non-secure context identifier CP registers
779      * separately because there is no secure bank in V8 (no _EL3).  This allows
780      * the secure register to be properly reset and migrated.  In the
781      * non-secure case, the 32-bit register will have reset and migration
782      * disabled during registration as it is handled by the 64-bit instance.
783      */
784     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
785       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
786       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
787       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
788       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
789     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
790       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
791       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
792       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
793       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
794     REGINFO_SENTINEL
795 };
796 
797 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
798     /* NB: Some of these registers exist in v8 but with more precise
799      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
800      */
801     /* MMU Domain access control / MPU write buffer control */
802     { .name = "DACR",
803       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
804       .access = PL1_RW, .resetvalue = 0,
805       .writefn = dacr_write, .raw_writefn = raw_write,
806       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
807                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
808     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
809      * For v6 and v5, these mappings are overly broad.
810      */
811     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
812       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
813     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
814       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
815     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
816       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
817     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
818       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
819     /* Cache maintenance ops; some of this space may be overridden later. */
820     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
821       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
822       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
823     REGINFO_SENTINEL
824 };
825 
826 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
827     /* Not all pre-v6 cores implemented this WFI, so this is slightly
828      * over-broad.
829      */
830     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
831       .access = PL1_W, .type = ARM_CP_WFI },
832     REGINFO_SENTINEL
833 };
834 
835 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
836     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
837      * is UNPREDICTABLE; we choose to NOP as most implementations do).
838      */
839     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
840       .access = PL1_W, .type = ARM_CP_WFI },
841     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
842      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
843      * OMAPCP will override this space.
844      */
845     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
846       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
847       .resetvalue = 0 },
848     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
849       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
850       .resetvalue = 0 },
851     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
852     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
853       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
854       .resetvalue = 0 },
855     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
856      * implementing it as RAZ means the "debug architecture version" bits
857      * will read as a reserved value, which should cause Linux to not try
858      * to use the debug hardware.
859      */
860     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
861       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
862     /* MMU TLB control. Note that the wildcarding means we cover not just
863      * the unified TLB ops but also the dside/iside/inner-shareable variants.
864      */
865     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
866       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
867       .type = ARM_CP_NO_RAW },
868     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
869       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
870       .type = ARM_CP_NO_RAW },
871     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
872       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
873       .type = ARM_CP_NO_RAW },
874     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
875       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
876       .type = ARM_CP_NO_RAW },
877     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
878       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
879     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
880       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
881     REGINFO_SENTINEL
882 };
883 
884 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
885                         uint64_t value)
886 {
887     uint32_t mask = 0;
888 
889     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
890     if (!arm_feature(env, ARM_FEATURE_V8)) {
891         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
892          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
893          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
894          */
895         if (arm_feature(env, ARM_FEATURE_VFP)) {
896             /* VFP coprocessor: cp10 & cp11 [23:20] */
897             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
898 
899             if (!arm_feature(env, ARM_FEATURE_NEON)) {
900                 /* ASEDIS [31] bit is RAO/WI */
901                 value |= (1 << 31);
902             }
903 
904             /* VFPv3 and upwards with NEON implement 32 double precision
905              * registers (D0-D31).
906              */
907             if (!arm_feature(env, ARM_FEATURE_NEON) ||
908                     !arm_feature(env, ARM_FEATURE_VFP3)) {
909                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
910                 value |= (1 << 30);
911             }
912         }
913         value &= mask;
914     }
915 
916     /*
917      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
918      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
919      */
920     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
921         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
922         value &= ~(0xf << 20);
923         value |= env->cp15.cpacr_el1 & (0xf << 20);
924     }
925 
926     env->cp15.cpacr_el1 = value;
927 }
928 
929 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
930 {
931     /*
932      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
933      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
934      */
935     uint64_t value = env->cp15.cpacr_el1;
936 
937     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
938         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
939         value &= ~(0xf << 20);
940     }
941     return value;
942 }
943 
944 
945 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
946 {
947     /* Call cpacr_write() so that we reset with the correct RAO bits set
948      * for our CPU features.
949      */
950     cpacr_write(env, ri, 0);
951 }
952 
953 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
954                                    bool isread)
955 {
956     if (arm_feature(env, ARM_FEATURE_V8)) {
957         /* Check if CPACR accesses are to be trapped to EL2 */
958         if (arm_current_el(env) == 1 &&
959             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
960             return CP_ACCESS_TRAP_EL2;
961         /* Check if CPACR accesses are to be trapped to EL3 */
962         } else if (arm_current_el(env) < 3 &&
963                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
964             return CP_ACCESS_TRAP_EL3;
965         }
966     }
967 
968     return CP_ACCESS_OK;
969 }
970 
971 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
972                                   bool isread)
973 {
974     /* Check if CPTR accesses are set to trap to EL3 */
975     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
976         return CP_ACCESS_TRAP_EL3;
977     }
978 
979     return CP_ACCESS_OK;
980 }
981 
982 static const ARMCPRegInfo v6_cp_reginfo[] = {
983     /* prefetch by MVA in v6, NOP in v7 */
984     { .name = "MVA_prefetch",
985       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
986       .access = PL1_W, .type = ARM_CP_NOP },
987     /* We need to break the TB after ISB to execute self-modifying code
988      * correctly and also to take any pending interrupts immediately.
989      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
990      */
991     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
992       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
993     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
994       .access = PL0_W, .type = ARM_CP_NOP },
995     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
996       .access = PL0_W, .type = ARM_CP_NOP },
997     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
998       .access = PL1_RW,
999       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
1000                              offsetof(CPUARMState, cp15.ifar_ns) },
1001       .resetvalue = 0, },
1002     /* Watchpoint Fault Address Register : should actually only be present
1003      * for 1136, 1176, 11MPCore.
1004      */
1005     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
1006       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
1007     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
1008       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
1009       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
1010       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
1011     REGINFO_SENTINEL
1012 };
1013 
1014 /* Definitions for the PMU registers */
1015 #define PMCRN_MASK  0xf800
1016 #define PMCRN_SHIFT 11
1017 #define PMCRLC  0x40
1018 #define PMCRDP  0x10
1019 #define PMCRD   0x8
1020 #define PMCRC   0x4
1021 #define PMCRP   0x2
1022 #define PMCRE   0x1
1023 
1024 #define PMXEVTYPER_P          0x80000000
1025 #define PMXEVTYPER_U          0x40000000
1026 #define PMXEVTYPER_NSK        0x20000000
1027 #define PMXEVTYPER_NSU        0x10000000
1028 #define PMXEVTYPER_NSH        0x08000000
1029 #define PMXEVTYPER_M          0x04000000
1030 #define PMXEVTYPER_MT         0x02000000
1031 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1032 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1033                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1034                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1035                                PMXEVTYPER_EVTCOUNT)
1036 
1037 #define PMCCFILTR             0xf8000000
1038 #define PMCCFILTR_M           PMXEVTYPER_M
1039 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1040 
1041 static inline uint32_t pmu_num_counters(CPUARMState *env)
1042 {
1043   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1044 }
1045 
1046 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1047 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1048 {
1049   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1050 }
1051 
1052 typedef struct pm_event {
1053     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1054     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1055     bool (*supported)(CPUARMState *);
1056     /*
1057      * Retrieve the current count of the underlying event. The programmed
1058      * counters hold a difference from the return value from this function
1059      */
1060     uint64_t (*get_count)(CPUARMState *);
1061     /*
1062      * Return how many nanoseconds it will take (at a minimum) for count events
1063      * to occur. A negative value indicates the counter will never overflow, or
1064      * that the counter has otherwise arranged for the overflow bit to be set
1065      * and the PMU interrupt to be raised on overflow.
1066      */
1067     int64_t (*ns_per_count)(uint64_t);
1068 } pm_event;
1069 
1070 static bool event_always_supported(CPUARMState *env)
1071 {
1072     return true;
1073 }
1074 
1075 static uint64_t swinc_get_count(CPUARMState *env)
1076 {
1077     /*
1078      * SW_INCR events are written directly to the pmevcntr's by writes to
1079      * PMSWINC, so there is no underlying count maintained by the PMU itself
1080      */
1081     return 0;
1082 }
1083 
1084 static int64_t swinc_ns_per(uint64_t ignored)
1085 {
1086     return -1;
1087 }
1088 
1089 /*
1090  * Return the underlying cycle count for the PMU cycle counters. If we're in
1091  * usermode, simply return 0.
1092  */
1093 static uint64_t cycles_get_count(CPUARMState *env)
1094 {
1095 #ifndef CONFIG_USER_ONLY
1096     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1097                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1098 #else
1099     return cpu_get_host_ticks();
1100 #endif
1101 }
1102 
1103 #ifndef CONFIG_USER_ONLY
1104 static int64_t cycles_ns_per(uint64_t cycles)
1105 {
1106     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1107 }
1108 
1109 static bool instructions_supported(CPUARMState *env)
1110 {
1111     return use_icount == 1 /* Precise instruction counting */;
1112 }
1113 
1114 static uint64_t instructions_get_count(CPUARMState *env)
1115 {
1116     return (uint64_t)cpu_get_icount_raw();
1117 }
1118 
1119 static int64_t instructions_ns_per(uint64_t icount)
1120 {
1121     return cpu_icount_to_ns((int64_t)icount);
1122 }
1123 #endif
1124 
1125 static const pm_event pm_events[] = {
1126     { .number = 0x000, /* SW_INCR */
1127       .supported = event_always_supported,
1128       .get_count = swinc_get_count,
1129       .ns_per_count = swinc_ns_per,
1130     },
1131 #ifndef CONFIG_USER_ONLY
1132     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1133       .supported = instructions_supported,
1134       .get_count = instructions_get_count,
1135       .ns_per_count = instructions_ns_per,
1136     },
1137     { .number = 0x011, /* CPU_CYCLES, Cycle */
1138       .supported = event_always_supported,
1139       .get_count = cycles_get_count,
1140       .ns_per_count = cycles_ns_per,
1141     }
1142 #endif
1143 };
1144 
1145 /*
1146  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1147  * events (i.e. the statistical profiling extension), this implementation
1148  * should first be updated to something sparse instead of the current
1149  * supported_event_map[] array.
1150  */
1151 #define MAX_EVENT_ID 0x11
1152 #define UNSUPPORTED_EVENT UINT16_MAX
1153 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1154 
1155 /*
1156  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1157  * of ARM event numbers to indices in our pm_events array.
1158  *
1159  * Note: Events in the 0x40XX range are not currently supported.
1160  */
1161 void pmu_init(ARMCPU *cpu)
1162 {
1163     unsigned int i;
1164 
1165     /*
1166      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1167      * events to them
1168      */
1169     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1170         supported_event_map[i] = UNSUPPORTED_EVENT;
1171     }
1172     cpu->pmceid0 = 0;
1173     cpu->pmceid1 = 0;
1174 
1175     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1176         const pm_event *cnt = &pm_events[i];
1177         assert(cnt->number <= MAX_EVENT_ID);
1178         /* We do not currently support events in the 0x40xx range */
1179         assert(cnt->number <= 0x3f);
1180 
1181         if (cnt->supported(&cpu->env)) {
1182             supported_event_map[cnt->number] = i;
1183             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1184             if (cnt->number & 0x20) {
1185                 cpu->pmceid1 |= event_mask;
1186             } else {
1187                 cpu->pmceid0 |= event_mask;
1188             }
1189         }
1190     }
1191 }
1192 
1193 /*
1194  * Check at runtime whether a PMU event is supported for the current machine
1195  */
1196 static bool event_supported(uint16_t number)
1197 {
1198     if (number > MAX_EVENT_ID) {
1199         return false;
1200     }
1201     return supported_event_map[number] != UNSUPPORTED_EVENT;
1202 }
1203 
1204 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1205                                    bool isread)
1206 {
1207     /* Performance monitor registers user accessibility is controlled
1208      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1209      * trapping to EL2 or EL3 for other accesses.
1210      */
1211     int el = arm_current_el(env);
1212 
1213     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1214         return CP_ACCESS_TRAP;
1215     }
1216     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
1217         && !arm_is_secure_below_el3(env)) {
1218         return CP_ACCESS_TRAP_EL2;
1219     }
1220     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1221         return CP_ACCESS_TRAP_EL3;
1222     }
1223 
1224     return CP_ACCESS_OK;
1225 }
1226 
1227 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1228                                            const ARMCPRegInfo *ri,
1229                                            bool isread)
1230 {
1231     /* ER: event counter read trap control */
1232     if (arm_feature(env, ARM_FEATURE_V8)
1233         && arm_current_el(env) == 0
1234         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1235         && isread) {
1236         return CP_ACCESS_OK;
1237     }
1238 
1239     return pmreg_access(env, ri, isread);
1240 }
1241 
1242 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1243                                          const ARMCPRegInfo *ri,
1244                                          bool isread)
1245 {
1246     /* SW: software increment write trap control */
1247     if (arm_feature(env, ARM_FEATURE_V8)
1248         && arm_current_el(env) == 0
1249         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1250         && !isread) {
1251         return CP_ACCESS_OK;
1252     }
1253 
1254     return pmreg_access(env, ri, isread);
1255 }
1256 
1257 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1258                                         const ARMCPRegInfo *ri,
1259                                         bool isread)
1260 {
1261     /* ER: event counter read trap control */
1262     if (arm_feature(env, ARM_FEATURE_V8)
1263         && arm_current_el(env) == 0
1264         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1265         return CP_ACCESS_OK;
1266     }
1267 
1268     return pmreg_access(env, ri, isread);
1269 }
1270 
1271 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1272                                          const ARMCPRegInfo *ri,
1273                                          bool isread)
1274 {
1275     /* CR: cycle counter read trap control */
1276     if (arm_feature(env, ARM_FEATURE_V8)
1277         && arm_current_el(env) == 0
1278         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1279         && isread) {
1280         return CP_ACCESS_OK;
1281     }
1282 
1283     return pmreg_access(env, ri, isread);
1284 }
1285 
1286 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1287  * the current EL, security state, and register configuration.
1288  */
1289 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1290 {
1291     uint64_t filter;
1292     bool e, p, u, nsk, nsu, nsh, m;
1293     bool enabled, prohibited, filtered;
1294     bool secure = arm_is_secure(env);
1295     int el = arm_current_el(env);
1296     uint8_t hpmn = env->cp15.mdcr_el2 & MDCR_HPMN;
1297 
1298     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1299         return false;
1300     }
1301 
1302     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1303             (counter < hpmn || counter == 31)) {
1304         e = env->cp15.c9_pmcr & PMCRE;
1305     } else {
1306         e = env->cp15.mdcr_el2 & MDCR_HPME;
1307     }
1308     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1309 
1310     if (!secure) {
1311         if (el == 2 && (counter < hpmn || counter == 31)) {
1312             prohibited = env->cp15.mdcr_el2 & MDCR_HPMD;
1313         } else {
1314             prohibited = false;
1315         }
1316     } else {
1317         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1318            (env->cp15.mdcr_el3 & MDCR_SPME);
1319     }
1320 
1321     if (prohibited && counter == 31) {
1322         prohibited = env->cp15.c9_pmcr & PMCRDP;
1323     }
1324 
1325     if (counter == 31) {
1326         filter = env->cp15.pmccfiltr_el0;
1327     } else {
1328         filter = env->cp15.c14_pmevtyper[counter];
1329     }
1330 
1331     p   = filter & PMXEVTYPER_P;
1332     u   = filter & PMXEVTYPER_U;
1333     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1334     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1335     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1336     m   = arm_el_is_aa64(env, 1) &&
1337               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1338 
1339     if (el == 0) {
1340         filtered = secure ? u : u != nsu;
1341     } else if (el == 1) {
1342         filtered = secure ? p : p != nsk;
1343     } else if (el == 2) {
1344         filtered = !nsh;
1345     } else { /* EL3 */
1346         filtered = m != p;
1347     }
1348 
1349     if (counter != 31) {
1350         /*
1351          * If not checking PMCCNTR, ensure the counter is setup to an event we
1352          * support
1353          */
1354         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1355         if (!event_supported(event)) {
1356             return false;
1357         }
1358     }
1359 
1360     return enabled && !prohibited && !filtered;
1361 }
1362 
1363 static void pmu_update_irq(CPUARMState *env)
1364 {
1365     ARMCPU *cpu = env_archcpu(env);
1366     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1367             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1368 }
1369 
1370 /*
1371  * Ensure c15_ccnt is the guest-visible count so that operations such as
1372  * enabling/disabling the counter or filtering, modifying the count itself,
1373  * etc. can be done logically. This is essentially a no-op if the counter is
1374  * not enabled at the time of the call.
1375  */
1376 static void pmccntr_op_start(CPUARMState *env)
1377 {
1378     uint64_t cycles = cycles_get_count(env);
1379 
1380     if (pmu_counter_enabled(env, 31)) {
1381         uint64_t eff_cycles = cycles;
1382         if (env->cp15.c9_pmcr & PMCRD) {
1383             /* Increment once every 64 processor clock cycles */
1384             eff_cycles /= 64;
1385         }
1386 
1387         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1388 
1389         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1390                                  1ull << 63 : 1ull << 31;
1391         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1392             env->cp15.c9_pmovsr |= (1 << 31);
1393             pmu_update_irq(env);
1394         }
1395 
1396         env->cp15.c15_ccnt = new_pmccntr;
1397     }
1398     env->cp15.c15_ccnt_delta = cycles;
1399 }
1400 
1401 /*
1402  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1403  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1404  * pmccntr_op_start.
1405  */
1406 static void pmccntr_op_finish(CPUARMState *env)
1407 {
1408     if (pmu_counter_enabled(env, 31)) {
1409 #ifndef CONFIG_USER_ONLY
1410         /* Calculate when the counter will next overflow */
1411         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1412         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1413             remaining_cycles = (uint32_t)remaining_cycles;
1414         }
1415         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1416 
1417         if (overflow_in > 0) {
1418             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1419                 overflow_in;
1420             ARMCPU *cpu = env_archcpu(env);
1421             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1422         }
1423 #endif
1424 
1425         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1426         if (env->cp15.c9_pmcr & PMCRD) {
1427             /* Increment once every 64 processor clock cycles */
1428             prev_cycles /= 64;
1429         }
1430         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1431     }
1432 }
1433 
1434 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1435 {
1436 
1437     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1438     uint64_t count = 0;
1439     if (event_supported(event)) {
1440         uint16_t event_idx = supported_event_map[event];
1441         count = pm_events[event_idx].get_count(env);
1442     }
1443 
1444     if (pmu_counter_enabled(env, counter)) {
1445         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1446 
1447         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1448             env->cp15.c9_pmovsr |= (1 << counter);
1449             pmu_update_irq(env);
1450         }
1451         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1452     }
1453     env->cp15.c14_pmevcntr_delta[counter] = count;
1454 }
1455 
1456 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1457 {
1458     if (pmu_counter_enabled(env, counter)) {
1459 #ifndef CONFIG_USER_ONLY
1460         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1461         uint16_t event_idx = supported_event_map[event];
1462         uint64_t delta = UINT32_MAX -
1463             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1464         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1465 
1466         if (overflow_in > 0) {
1467             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1468                 overflow_in;
1469             ARMCPU *cpu = env_archcpu(env);
1470             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1471         }
1472 #endif
1473 
1474         env->cp15.c14_pmevcntr_delta[counter] -=
1475             env->cp15.c14_pmevcntr[counter];
1476     }
1477 }
1478 
1479 void pmu_op_start(CPUARMState *env)
1480 {
1481     unsigned int i;
1482     pmccntr_op_start(env);
1483     for (i = 0; i < pmu_num_counters(env); i++) {
1484         pmevcntr_op_start(env, i);
1485     }
1486 }
1487 
1488 void pmu_op_finish(CPUARMState *env)
1489 {
1490     unsigned int i;
1491     pmccntr_op_finish(env);
1492     for (i = 0; i < pmu_num_counters(env); i++) {
1493         pmevcntr_op_finish(env, i);
1494     }
1495 }
1496 
1497 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1498 {
1499     pmu_op_start(&cpu->env);
1500 }
1501 
1502 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1503 {
1504     pmu_op_finish(&cpu->env);
1505 }
1506 
1507 void arm_pmu_timer_cb(void *opaque)
1508 {
1509     ARMCPU *cpu = opaque;
1510 
1511     /*
1512      * Update all the counter values based on the current underlying counts,
1513      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1514      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1515      * counter may expire.
1516      */
1517     pmu_op_start(&cpu->env);
1518     pmu_op_finish(&cpu->env);
1519 }
1520 
1521 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1522                        uint64_t value)
1523 {
1524     pmu_op_start(env);
1525 
1526     if (value & PMCRC) {
1527         /* The counter has been reset */
1528         env->cp15.c15_ccnt = 0;
1529     }
1530 
1531     if (value & PMCRP) {
1532         unsigned int i;
1533         for (i = 0; i < pmu_num_counters(env); i++) {
1534             env->cp15.c14_pmevcntr[i] = 0;
1535         }
1536     }
1537 
1538     /* only the DP, X, D and E bits are writable */
1539     env->cp15.c9_pmcr &= ~0x39;
1540     env->cp15.c9_pmcr |= (value & 0x39);
1541 
1542     pmu_op_finish(env);
1543 }
1544 
1545 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1546                           uint64_t value)
1547 {
1548     unsigned int i;
1549     for (i = 0; i < pmu_num_counters(env); i++) {
1550         /* Increment a counter's count iff: */
1551         if ((value & (1 << i)) && /* counter's bit is set */
1552                 /* counter is enabled and not filtered */
1553                 pmu_counter_enabled(env, i) &&
1554                 /* counter is SW_INCR */
1555                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1556             pmevcntr_op_start(env, i);
1557 
1558             /*
1559              * Detect if this write causes an overflow since we can't predict
1560              * PMSWINC overflows like we can for other events
1561              */
1562             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1563 
1564             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1565                 env->cp15.c9_pmovsr |= (1 << i);
1566                 pmu_update_irq(env);
1567             }
1568 
1569             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1570 
1571             pmevcntr_op_finish(env, i);
1572         }
1573     }
1574 }
1575 
1576 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1577 {
1578     uint64_t ret;
1579     pmccntr_op_start(env);
1580     ret = env->cp15.c15_ccnt;
1581     pmccntr_op_finish(env);
1582     return ret;
1583 }
1584 
1585 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1586                          uint64_t value)
1587 {
1588     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1589      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1590      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1591      * accessed.
1592      */
1593     env->cp15.c9_pmselr = value & 0x1f;
1594 }
1595 
1596 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1597                         uint64_t value)
1598 {
1599     pmccntr_op_start(env);
1600     env->cp15.c15_ccnt = value;
1601     pmccntr_op_finish(env);
1602 }
1603 
1604 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1605                             uint64_t value)
1606 {
1607     uint64_t cur_val = pmccntr_read(env, NULL);
1608 
1609     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1610 }
1611 
1612 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1613                             uint64_t value)
1614 {
1615     pmccntr_op_start(env);
1616     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1617     pmccntr_op_finish(env);
1618 }
1619 
1620 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1621                             uint64_t value)
1622 {
1623     pmccntr_op_start(env);
1624     /* M is not accessible from AArch32 */
1625     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1626         (value & PMCCFILTR);
1627     pmccntr_op_finish(env);
1628 }
1629 
1630 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1631 {
1632     /* M is not visible in AArch32 */
1633     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1634 }
1635 
1636 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1637                             uint64_t value)
1638 {
1639     value &= pmu_counter_mask(env);
1640     env->cp15.c9_pmcnten |= value;
1641 }
1642 
1643 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1644                              uint64_t value)
1645 {
1646     value &= pmu_counter_mask(env);
1647     env->cp15.c9_pmcnten &= ~value;
1648 }
1649 
1650 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1651                          uint64_t value)
1652 {
1653     value &= pmu_counter_mask(env);
1654     env->cp15.c9_pmovsr &= ~value;
1655     pmu_update_irq(env);
1656 }
1657 
1658 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1659                          uint64_t value)
1660 {
1661     value &= pmu_counter_mask(env);
1662     env->cp15.c9_pmovsr |= value;
1663     pmu_update_irq(env);
1664 }
1665 
1666 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1667                              uint64_t value, const uint8_t counter)
1668 {
1669     if (counter == 31) {
1670         pmccfiltr_write(env, ri, value);
1671     } else if (counter < pmu_num_counters(env)) {
1672         pmevcntr_op_start(env, counter);
1673 
1674         /*
1675          * If this counter's event type is changing, store the current
1676          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1677          * pmevcntr_op_finish has the correct baseline when it converts back to
1678          * a delta.
1679          */
1680         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1681             PMXEVTYPER_EVTCOUNT;
1682         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1683         if (old_event != new_event) {
1684             uint64_t count = 0;
1685             if (event_supported(new_event)) {
1686                 uint16_t event_idx = supported_event_map[new_event];
1687                 count = pm_events[event_idx].get_count(env);
1688             }
1689             env->cp15.c14_pmevcntr_delta[counter] = count;
1690         }
1691 
1692         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1693         pmevcntr_op_finish(env, counter);
1694     }
1695     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1696      * PMSELR value is equal to or greater than the number of implemented
1697      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1698      */
1699 }
1700 
1701 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1702                                const uint8_t counter)
1703 {
1704     if (counter == 31) {
1705         return env->cp15.pmccfiltr_el0;
1706     } else if (counter < pmu_num_counters(env)) {
1707         return env->cp15.c14_pmevtyper[counter];
1708     } else {
1709       /*
1710        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1711        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1712        */
1713         return 0;
1714     }
1715 }
1716 
1717 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1718                               uint64_t value)
1719 {
1720     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1721     pmevtyper_write(env, ri, value, counter);
1722 }
1723 
1724 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1725                                uint64_t value)
1726 {
1727     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1728     env->cp15.c14_pmevtyper[counter] = value;
1729 
1730     /*
1731      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1732      * pmu_op_finish calls when loading saved state for a migration. Because
1733      * we're potentially updating the type of event here, the value written to
1734      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1735      * different counter type. Therefore, we need to set this value to the
1736      * current count for the counter type we're writing so that pmu_op_finish
1737      * has the correct count for its calculation.
1738      */
1739     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1740     if (event_supported(event)) {
1741         uint16_t event_idx = supported_event_map[event];
1742         env->cp15.c14_pmevcntr_delta[counter] =
1743             pm_events[event_idx].get_count(env);
1744     }
1745 }
1746 
1747 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1748 {
1749     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1750     return pmevtyper_read(env, ri, counter);
1751 }
1752 
1753 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1754                              uint64_t value)
1755 {
1756     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1757 }
1758 
1759 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1760 {
1761     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1762 }
1763 
1764 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1765                              uint64_t value, uint8_t counter)
1766 {
1767     if (counter < pmu_num_counters(env)) {
1768         pmevcntr_op_start(env, counter);
1769         env->cp15.c14_pmevcntr[counter] = value;
1770         pmevcntr_op_finish(env, counter);
1771     }
1772     /*
1773      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1774      * are CONSTRAINED UNPREDICTABLE.
1775      */
1776 }
1777 
1778 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1779                               uint8_t counter)
1780 {
1781     if (counter < pmu_num_counters(env)) {
1782         uint64_t ret;
1783         pmevcntr_op_start(env, counter);
1784         ret = env->cp15.c14_pmevcntr[counter];
1785         pmevcntr_op_finish(env, counter);
1786         return ret;
1787     } else {
1788       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1789        * are CONSTRAINED UNPREDICTABLE. */
1790         return 0;
1791     }
1792 }
1793 
1794 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1795                              uint64_t value)
1796 {
1797     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1798     pmevcntr_write(env, ri, value, counter);
1799 }
1800 
1801 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1802 {
1803     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1804     return pmevcntr_read(env, ri, counter);
1805 }
1806 
1807 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1808                              uint64_t value)
1809 {
1810     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1811     assert(counter < pmu_num_counters(env));
1812     env->cp15.c14_pmevcntr[counter] = value;
1813     pmevcntr_write(env, ri, value, counter);
1814 }
1815 
1816 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1817 {
1818     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1819     assert(counter < pmu_num_counters(env));
1820     return env->cp15.c14_pmevcntr[counter];
1821 }
1822 
1823 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1824                              uint64_t value)
1825 {
1826     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1827 }
1828 
1829 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1830 {
1831     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1832 }
1833 
1834 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1835                             uint64_t value)
1836 {
1837     if (arm_feature(env, ARM_FEATURE_V8)) {
1838         env->cp15.c9_pmuserenr = value & 0xf;
1839     } else {
1840         env->cp15.c9_pmuserenr = value & 1;
1841     }
1842 }
1843 
1844 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1845                              uint64_t value)
1846 {
1847     /* We have no event counters so only the C bit can be changed */
1848     value &= pmu_counter_mask(env);
1849     env->cp15.c9_pminten |= value;
1850     pmu_update_irq(env);
1851 }
1852 
1853 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1854                              uint64_t value)
1855 {
1856     value &= pmu_counter_mask(env);
1857     env->cp15.c9_pminten &= ~value;
1858     pmu_update_irq(env);
1859 }
1860 
1861 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1862                        uint64_t value)
1863 {
1864     /* Note that even though the AArch64 view of this register has bits
1865      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1866      * architectural requirements for bits which are RES0 only in some
1867      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1868      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1869      */
1870     raw_write(env, ri, value & ~0x1FULL);
1871 }
1872 
1873 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1874 {
1875     /* Begin with base v8.0 state.  */
1876     uint32_t valid_mask = 0x3fff;
1877     ARMCPU *cpu = env_archcpu(env);
1878 
1879     if (arm_el_is_aa64(env, 3)) {
1880         value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1881         valid_mask &= ~SCR_NET;
1882     } else {
1883         valid_mask &= ~(SCR_RW | SCR_ST);
1884     }
1885 
1886     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1887         valid_mask &= ~SCR_HCE;
1888 
1889         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1890          * supported if EL2 exists. The bit is UNK/SBZP when
1891          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1892          * when EL2 is unavailable.
1893          * On ARMv8, this bit is always available.
1894          */
1895         if (arm_feature(env, ARM_FEATURE_V7) &&
1896             !arm_feature(env, ARM_FEATURE_V8)) {
1897             valid_mask &= ~SCR_SMD;
1898         }
1899     }
1900     if (cpu_isar_feature(aa64_lor, cpu)) {
1901         valid_mask |= SCR_TLOR;
1902     }
1903     if (cpu_isar_feature(aa64_pauth, cpu)) {
1904         valid_mask |= SCR_API | SCR_APK;
1905     }
1906 
1907     /* Clear all-context RES0 bits.  */
1908     value &= valid_mask;
1909     raw_write(env, ri, value);
1910 }
1911 
1912 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1913 {
1914     ARMCPU *cpu = env_archcpu(env);
1915 
1916     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1917      * bank
1918      */
1919     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1920                                         ri->secure & ARM_CP_SECSTATE_S);
1921 
1922     return cpu->ccsidr[index];
1923 }
1924 
1925 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1926                          uint64_t value)
1927 {
1928     raw_write(env, ri, value & 0xf);
1929 }
1930 
1931 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1932 {
1933     CPUState *cs = env_cpu(env);
1934     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
1935     uint64_t ret = 0;
1936 
1937     if (hcr_el2 & HCR_IMO) {
1938         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1939             ret |= CPSR_I;
1940         }
1941     } else {
1942         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1943             ret |= CPSR_I;
1944         }
1945     }
1946 
1947     if (hcr_el2 & HCR_FMO) {
1948         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1949             ret |= CPSR_F;
1950         }
1951     } else {
1952         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1953             ret |= CPSR_F;
1954         }
1955     }
1956 
1957     /* External aborts are not possible in QEMU so A bit is always clear */
1958     return ret;
1959 }
1960 
1961 static const ARMCPRegInfo v7_cp_reginfo[] = {
1962     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1963     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1964       .access = PL1_W, .type = ARM_CP_NOP },
1965     /* Performance monitors are implementation defined in v7,
1966      * but with an ARM recommended set of registers, which we
1967      * follow.
1968      *
1969      * Performance registers fall into three categories:
1970      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1971      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1972      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1973      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1974      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1975      */
1976     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1977       .access = PL0_RW, .type = ARM_CP_ALIAS,
1978       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1979       .writefn = pmcntenset_write,
1980       .accessfn = pmreg_access,
1981       .raw_writefn = raw_write },
1982     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1983       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1984       .access = PL0_RW, .accessfn = pmreg_access,
1985       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1986       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1987     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1988       .access = PL0_RW,
1989       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1990       .accessfn = pmreg_access,
1991       .writefn = pmcntenclr_write,
1992       .type = ARM_CP_ALIAS },
1993     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1994       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1995       .access = PL0_RW, .accessfn = pmreg_access,
1996       .type = ARM_CP_ALIAS,
1997       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1998       .writefn = pmcntenclr_write },
1999     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2000       .access = PL0_RW, .type = ARM_CP_IO,
2001       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2002       .accessfn = pmreg_access,
2003       .writefn = pmovsr_write,
2004       .raw_writefn = raw_write },
2005     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2006       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2007       .access = PL0_RW, .accessfn = pmreg_access,
2008       .type = ARM_CP_ALIAS | ARM_CP_IO,
2009       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2010       .writefn = pmovsr_write,
2011       .raw_writefn = raw_write },
2012     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2013       .access = PL0_W, .accessfn = pmreg_access_swinc,
2014       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2015       .writefn = pmswinc_write },
2016     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2017       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2018       .access = PL0_W, .accessfn = pmreg_access_swinc,
2019       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2020       .writefn = pmswinc_write },
2021     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2022       .access = PL0_RW, .type = ARM_CP_ALIAS,
2023       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2024       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2025       .raw_writefn = raw_write},
2026     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2027       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2028       .access = PL0_RW, .accessfn = pmreg_access_selr,
2029       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2030       .writefn = pmselr_write, .raw_writefn = raw_write, },
2031     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2032       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2033       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2034       .accessfn = pmreg_access_ccntr },
2035     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2036       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2037       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2038       .type = ARM_CP_IO,
2039       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2040       .readfn = pmccntr_read, .writefn = pmccntr_write,
2041       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2042     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2043       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2044       .access = PL0_RW, .accessfn = pmreg_access,
2045       .type = ARM_CP_ALIAS | ARM_CP_IO,
2046       .resetvalue = 0, },
2047     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2048       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2049       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2050       .access = PL0_RW, .accessfn = pmreg_access,
2051       .type = ARM_CP_IO,
2052       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2053       .resetvalue = 0, },
2054     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2055       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2056       .accessfn = pmreg_access,
2057       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2058     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2059       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2060       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2061       .accessfn = pmreg_access,
2062       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2063     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2064       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2065       .accessfn = pmreg_access_xevcntr,
2066       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2067     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2068       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2069       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2070       .accessfn = pmreg_access_xevcntr,
2071       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2072     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2073       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2074       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2075       .resetvalue = 0,
2076       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2077     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2078       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2079       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2080       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2081       .resetvalue = 0,
2082       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2083     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2084       .access = PL1_RW, .accessfn = access_tpm,
2085       .type = ARM_CP_ALIAS | ARM_CP_IO,
2086       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2087       .resetvalue = 0,
2088       .writefn = pmintenset_write, .raw_writefn = raw_write },
2089     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2090       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2091       .access = PL1_RW, .accessfn = access_tpm,
2092       .type = ARM_CP_IO,
2093       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2094       .writefn = pmintenset_write, .raw_writefn = raw_write,
2095       .resetvalue = 0x0 },
2096     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2097       .access = PL1_RW, .accessfn = access_tpm,
2098       .type = ARM_CP_ALIAS | ARM_CP_IO,
2099       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2100       .writefn = pmintenclr_write, },
2101     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2102       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2103       .access = PL1_RW, .accessfn = access_tpm,
2104       .type = ARM_CP_ALIAS | ARM_CP_IO,
2105       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2106       .writefn = pmintenclr_write },
2107     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2108       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2109       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2110     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2111       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2112       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
2113       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2114                              offsetof(CPUARMState, cp15.csselr_ns) } },
2115     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2116      * just RAZ for all cores:
2117      */
2118     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2119       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2120       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2121     /* Auxiliary fault status registers: these also are IMPDEF, and we
2122      * choose to RAZ/WI for all cores.
2123      */
2124     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2125       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2126       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2127     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2128       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2129       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2130     /* MAIR can just read-as-written because we don't implement caches
2131      * and so don't need to care about memory attributes.
2132      */
2133     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2134       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2135       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2136       .resetvalue = 0 },
2137     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2138       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2139       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2140       .resetvalue = 0 },
2141     /* For non-long-descriptor page tables these are PRRR and NMRR;
2142      * regardless they still act as reads-as-written for QEMU.
2143      */
2144      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2145       * allows them to assign the correct fieldoffset based on the endianness
2146       * handled in the field definitions.
2147       */
2148     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2149       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
2150       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2151                              offsetof(CPUARMState, cp15.mair0_ns) },
2152       .resetfn = arm_cp_reset_ignore },
2153     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2154       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
2155       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2156                              offsetof(CPUARMState, cp15.mair1_ns) },
2157       .resetfn = arm_cp_reset_ignore },
2158     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2159       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2160       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2161     /* 32 bit ITLB invalidates */
2162     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2163       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2164     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2165       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2166     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2167       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2168     /* 32 bit DTLB invalidates */
2169     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2170       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2171     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2172       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2173     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2174       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2175     /* 32 bit TLB invalidates */
2176     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2177       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2178     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2179       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2180     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2181       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2182     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2183       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
2184     REGINFO_SENTINEL
2185 };
2186 
2187 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2188     /* 32 bit TLB invalidates, Inner Shareable */
2189     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2190       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
2191     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2192       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
2193     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2194       .type = ARM_CP_NO_RAW, .access = PL1_W,
2195       .writefn = tlbiasid_is_write },
2196     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2197       .type = ARM_CP_NO_RAW, .access = PL1_W,
2198       .writefn = tlbimvaa_is_write },
2199     REGINFO_SENTINEL
2200 };
2201 
2202 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2203     /* PMOVSSET is not implemented in v7 before v7ve */
2204     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2205       .access = PL0_RW, .accessfn = pmreg_access,
2206       .type = ARM_CP_ALIAS | ARM_CP_IO,
2207       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2208       .writefn = pmovsset_write,
2209       .raw_writefn = raw_write },
2210     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2211       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2212       .access = PL0_RW, .accessfn = pmreg_access,
2213       .type = ARM_CP_ALIAS | ARM_CP_IO,
2214       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2215       .writefn = pmovsset_write,
2216       .raw_writefn = raw_write },
2217     REGINFO_SENTINEL
2218 };
2219 
2220 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2221                         uint64_t value)
2222 {
2223     value &= 1;
2224     env->teecr = value;
2225 }
2226 
2227 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2228                                     bool isread)
2229 {
2230     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2231         return CP_ACCESS_TRAP;
2232     }
2233     return CP_ACCESS_OK;
2234 }
2235 
2236 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2237     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2238       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2239       .resetvalue = 0,
2240       .writefn = teecr_write },
2241     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2242       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2243       .accessfn = teehbr_access, .resetvalue = 0 },
2244     REGINFO_SENTINEL
2245 };
2246 
2247 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2248     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2249       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2250       .access = PL0_RW,
2251       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2252     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2253       .access = PL0_RW,
2254       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2255                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2256       .resetfn = arm_cp_reset_ignore },
2257     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2258       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2259       .access = PL0_R|PL1_W,
2260       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2261       .resetvalue = 0},
2262     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2263       .access = PL0_R|PL1_W,
2264       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2265                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2266       .resetfn = arm_cp_reset_ignore },
2267     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2268       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2269       .access = PL1_RW,
2270       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2271     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2272       .access = PL1_RW,
2273       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2274                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2275       .resetvalue = 0 },
2276     REGINFO_SENTINEL
2277 };
2278 
2279 #ifndef CONFIG_USER_ONLY
2280 
2281 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2282                                        bool isread)
2283 {
2284     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2285      * Writable only at the highest implemented exception level.
2286      */
2287     int el = arm_current_el(env);
2288 
2289     switch (el) {
2290     case 0:
2291         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
2292             return CP_ACCESS_TRAP;
2293         }
2294         break;
2295     case 1:
2296         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2297             arm_is_secure_below_el3(env)) {
2298             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2299             return CP_ACCESS_TRAP_UNCATEGORIZED;
2300         }
2301         break;
2302     case 2:
2303     case 3:
2304         break;
2305     }
2306 
2307     if (!isread && el < arm_highest_el(env)) {
2308         return CP_ACCESS_TRAP_UNCATEGORIZED;
2309     }
2310 
2311     return CP_ACCESS_OK;
2312 }
2313 
2314 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2315                                         bool isread)
2316 {
2317     unsigned int cur_el = arm_current_el(env);
2318     bool secure = arm_is_secure(env);
2319 
2320     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
2321     if (cur_el == 0 &&
2322         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2323         return CP_ACCESS_TRAP;
2324     }
2325 
2326     if (arm_feature(env, ARM_FEATURE_EL2) &&
2327         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2328         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
2329         return CP_ACCESS_TRAP_EL2;
2330     }
2331     return CP_ACCESS_OK;
2332 }
2333 
2334 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2335                                       bool isread)
2336 {
2337     unsigned int cur_el = arm_current_el(env);
2338     bool secure = arm_is_secure(env);
2339 
2340     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
2341      * EL0[PV]TEN is zero.
2342      */
2343     if (cur_el == 0 &&
2344         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2345         return CP_ACCESS_TRAP;
2346     }
2347 
2348     if (arm_feature(env, ARM_FEATURE_EL2) &&
2349         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2350         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2351         return CP_ACCESS_TRAP_EL2;
2352     }
2353     return CP_ACCESS_OK;
2354 }
2355 
2356 static CPAccessResult gt_pct_access(CPUARMState *env,
2357                                     const ARMCPRegInfo *ri,
2358                                     bool isread)
2359 {
2360     return gt_counter_access(env, GTIMER_PHYS, isread);
2361 }
2362 
2363 static CPAccessResult gt_vct_access(CPUARMState *env,
2364                                     const ARMCPRegInfo *ri,
2365                                     bool isread)
2366 {
2367     return gt_counter_access(env, GTIMER_VIRT, isread);
2368 }
2369 
2370 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2371                                        bool isread)
2372 {
2373     return gt_timer_access(env, GTIMER_PHYS, isread);
2374 }
2375 
2376 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2377                                        bool isread)
2378 {
2379     return gt_timer_access(env, GTIMER_VIRT, isread);
2380 }
2381 
2382 static CPAccessResult gt_stimer_access(CPUARMState *env,
2383                                        const ARMCPRegInfo *ri,
2384                                        bool isread)
2385 {
2386     /* The AArch64 register view of the secure physical timer is
2387      * always accessible from EL3, and configurably accessible from
2388      * Secure EL1.
2389      */
2390     switch (arm_current_el(env)) {
2391     case 1:
2392         if (!arm_is_secure(env)) {
2393             return CP_ACCESS_TRAP;
2394         }
2395         if (!(env->cp15.scr_el3 & SCR_ST)) {
2396             return CP_ACCESS_TRAP_EL3;
2397         }
2398         return CP_ACCESS_OK;
2399     case 0:
2400     case 2:
2401         return CP_ACCESS_TRAP;
2402     case 3:
2403         return CP_ACCESS_OK;
2404     default:
2405         g_assert_not_reached();
2406     }
2407 }
2408 
2409 static uint64_t gt_get_countervalue(CPUARMState *env)
2410 {
2411     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
2412 }
2413 
2414 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2415 {
2416     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2417 
2418     if (gt->ctl & 1) {
2419         /* Timer enabled: calculate and set current ISTATUS, irq, and
2420          * reset timer to when ISTATUS next has to change
2421          */
2422         uint64_t offset = timeridx == GTIMER_VIRT ?
2423                                       cpu->env.cp15.cntvoff_el2 : 0;
2424         uint64_t count = gt_get_countervalue(&cpu->env);
2425         /* Note that this must be unsigned 64 bit arithmetic: */
2426         int istatus = count - offset >= gt->cval;
2427         uint64_t nexttick;
2428         int irqstate;
2429 
2430         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2431 
2432         irqstate = (istatus && !(gt->ctl & 2));
2433         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2434 
2435         if (istatus) {
2436             /* Next transition is when count rolls back over to zero */
2437             nexttick = UINT64_MAX;
2438         } else {
2439             /* Next transition is when we hit cval */
2440             nexttick = gt->cval + offset;
2441         }
2442         /* Note that the desired next expiry time might be beyond the
2443          * signed-64-bit range of a QEMUTimer -- in this case we just
2444          * set the timer for as far in the future as possible. When the
2445          * timer expires we will reset the timer for any remaining period.
2446          */
2447         if (nexttick > INT64_MAX / GTIMER_SCALE) {
2448             nexttick = INT64_MAX / GTIMER_SCALE;
2449         }
2450         timer_mod(cpu->gt_timer[timeridx], nexttick);
2451         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2452     } else {
2453         /* Timer disabled: ISTATUS and timer output always clear */
2454         gt->ctl &= ~4;
2455         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2456         timer_del(cpu->gt_timer[timeridx]);
2457         trace_arm_gt_recalc_disabled(timeridx);
2458     }
2459 }
2460 
2461 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2462                            int timeridx)
2463 {
2464     ARMCPU *cpu = env_archcpu(env);
2465 
2466     timer_del(cpu->gt_timer[timeridx]);
2467 }
2468 
2469 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2470 {
2471     return gt_get_countervalue(env);
2472 }
2473 
2474 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2475 {
2476     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
2477 }
2478 
2479 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2480                           int timeridx,
2481                           uint64_t value)
2482 {
2483     trace_arm_gt_cval_write(timeridx, value);
2484     env->cp15.c14_timer[timeridx].cval = value;
2485     gt_recalc_timer(env_archcpu(env), timeridx);
2486 }
2487 
2488 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2489                              int timeridx)
2490 {
2491     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2492 
2493     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2494                       (gt_get_countervalue(env) - offset));
2495 }
2496 
2497 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2498                           int timeridx,
2499                           uint64_t value)
2500 {
2501     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2502 
2503     trace_arm_gt_tval_write(timeridx, value);
2504     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2505                                          sextract64(value, 0, 32);
2506     gt_recalc_timer(env_archcpu(env), timeridx);
2507 }
2508 
2509 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2510                          int timeridx,
2511                          uint64_t value)
2512 {
2513     ARMCPU *cpu = env_archcpu(env);
2514     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2515 
2516     trace_arm_gt_ctl_write(timeridx, value);
2517     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2518     if ((oldval ^ value) & 1) {
2519         /* Enable toggled */
2520         gt_recalc_timer(cpu, timeridx);
2521     } else if ((oldval ^ value) & 2) {
2522         /* IMASK toggled: don't need to recalculate,
2523          * just set the interrupt line based on ISTATUS
2524          */
2525         int irqstate = (oldval & 4) && !(value & 2);
2526 
2527         trace_arm_gt_imask_toggle(timeridx, irqstate);
2528         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2529     }
2530 }
2531 
2532 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2533 {
2534     gt_timer_reset(env, ri, GTIMER_PHYS);
2535 }
2536 
2537 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2538                                uint64_t value)
2539 {
2540     gt_cval_write(env, ri, GTIMER_PHYS, value);
2541 }
2542 
2543 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2544 {
2545     return gt_tval_read(env, ri, GTIMER_PHYS);
2546 }
2547 
2548 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2549                                uint64_t value)
2550 {
2551     gt_tval_write(env, ri, GTIMER_PHYS, value);
2552 }
2553 
2554 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2555                               uint64_t value)
2556 {
2557     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2558 }
2559 
2560 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2561 {
2562     gt_timer_reset(env, ri, GTIMER_VIRT);
2563 }
2564 
2565 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2566                                uint64_t value)
2567 {
2568     gt_cval_write(env, ri, GTIMER_VIRT, value);
2569 }
2570 
2571 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2572 {
2573     return gt_tval_read(env, ri, GTIMER_VIRT);
2574 }
2575 
2576 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2577                                uint64_t value)
2578 {
2579     gt_tval_write(env, ri, GTIMER_VIRT, value);
2580 }
2581 
2582 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2583                               uint64_t value)
2584 {
2585     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2586 }
2587 
2588 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2589                               uint64_t value)
2590 {
2591     ARMCPU *cpu = env_archcpu(env);
2592 
2593     trace_arm_gt_cntvoff_write(value);
2594     raw_write(env, ri, value);
2595     gt_recalc_timer(cpu, GTIMER_VIRT);
2596 }
2597 
2598 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2599 {
2600     gt_timer_reset(env, ri, GTIMER_HYP);
2601 }
2602 
2603 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2604                               uint64_t value)
2605 {
2606     gt_cval_write(env, ri, GTIMER_HYP, value);
2607 }
2608 
2609 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2610 {
2611     return gt_tval_read(env, ri, GTIMER_HYP);
2612 }
2613 
2614 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2615                               uint64_t value)
2616 {
2617     gt_tval_write(env, ri, GTIMER_HYP, value);
2618 }
2619 
2620 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2621                               uint64_t value)
2622 {
2623     gt_ctl_write(env, ri, GTIMER_HYP, value);
2624 }
2625 
2626 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2627 {
2628     gt_timer_reset(env, ri, GTIMER_SEC);
2629 }
2630 
2631 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2632                               uint64_t value)
2633 {
2634     gt_cval_write(env, ri, GTIMER_SEC, value);
2635 }
2636 
2637 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2638 {
2639     return gt_tval_read(env, ri, GTIMER_SEC);
2640 }
2641 
2642 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2643                               uint64_t value)
2644 {
2645     gt_tval_write(env, ri, GTIMER_SEC, value);
2646 }
2647 
2648 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2649                               uint64_t value)
2650 {
2651     gt_ctl_write(env, ri, GTIMER_SEC, value);
2652 }
2653 
2654 void arm_gt_ptimer_cb(void *opaque)
2655 {
2656     ARMCPU *cpu = opaque;
2657 
2658     gt_recalc_timer(cpu, GTIMER_PHYS);
2659 }
2660 
2661 void arm_gt_vtimer_cb(void *opaque)
2662 {
2663     ARMCPU *cpu = opaque;
2664 
2665     gt_recalc_timer(cpu, GTIMER_VIRT);
2666 }
2667 
2668 void arm_gt_htimer_cb(void *opaque)
2669 {
2670     ARMCPU *cpu = opaque;
2671 
2672     gt_recalc_timer(cpu, GTIMER_HYP);
2673 }
2674 
2675 void arm_gt_stimer_cb(void *opaque)
2676 {
2677     ARMCPU *cpu = opaque;
2678 
2679     gt_recalc_timer(cpu, GTIMER_SEC);
2680 }
2681 
2682 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2683     /* Note that CNTFRQ is purely reads-as-written for the benefit
2684      * of software; writing it doesn't actually change the timer frequency.
2685      * Our reset value matches the fixed frequency we implement the timer at.
2686      */
2687     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2688       .type = ARM_CP_ALIAS,
2689       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2690       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2691     },
2692     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2693       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2694       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2695       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2696       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
2697     },
2698     /* overall control: mostly access permissions */
2699     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2700       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2701       .access = PL1_RW,
2702       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2703       .resetvalue = 0,
2704     },
2705     /* per-timer control */
2706     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2707       .secure = ARM_CP_SECSTATE_NS,
2708       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2709       .accessfn = gt_ptimer_access,
2710       .fieldoffset = offsetoflow32(CPUARMState,
2711                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2712       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2713     },
2714     { .name = "CNTP_CTL_S",
2715       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2716       .secure = ARM_CP_SECSTATE_S,
2717       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2718       .accessfn = gt_ptimer_access,
2719       .fieldoffset = offsetoflow32(CPUARMState,
2720                                    cp15.c14_timer[GTIMER_SEC].ctl),
2721       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2722     },
2723     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2724       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2725       .type = ARM_CP_IO, .access = PL0_RW,
2726       .accessfn = gt_ptimer_access,
2727       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2728       .resetvalue = 0,
2729       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2730     },
2731     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2732       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2733       .accessfn = gt_vtimer_access,
2734       .fieldoffset = offsetoflow32(CPUARMState,
2735                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2736       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2737     },
2738     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2739       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2740       .type = ARM_CP_IO, .access = PL0_RW,
2741       .accessfn = gt_vtimer_access,
2742       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2743       .resetvalue = 0,
2744       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2745     },
2746     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2747     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2748       .secure = ARM_CP_SECSTATE_NS,
2749       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2750       .accessfn = gt_ptimer_access,
2751       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2752     },
2753     { .name = "CNTP_TVAL_S",
2754       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2755       .secure = ARM_CP_SECSTATE_S,
2756       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2757       .accessfn = gt_ptimer_access,
2758       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2759     },
2760     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2761       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2762       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2763       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2764       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2765     },
2766     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2767       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2768       .accessfn = gt_vtimer_access,
2769       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2770     },
2771     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2772       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2773       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2774       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2775       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2776     },
2777     /* The counter itself */
2778     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2779       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2780       .accessfn = gt_pct_access,
2781       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2782     },
2783     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2784       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2785       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2786       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2787     },
2788     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2789       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2790       .accessfn = gt_vct_access,
2791       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2792     },
2793     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2794       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2795       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2796       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2797     },
2798     /* Comparison value, indicating when the timer goes off */
2799     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2800       .secure = ARM_CP_SECSTATE_NS,
2801       .access = PL0_RW,
2802       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2803       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2804       .accessfn = gt_ptimer_access,
2805       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2806     },
2807     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
2808       .secure = ARM_CP_SECSTATE_S,
2809       .access = PL0_RW,
2810       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2811       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2812       .accessfn = gt_ptimer_access,
2813       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2814     },
2815     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2816       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2817       .access = PL0_RW,
2818       .type = ARM_CP_IO,
2819       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2820       .resetvalue = 0, .accessfn = gt_ptimer_access,
2821       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2822     },
2823     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2824       .access = PL0_RW,
2825       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2826       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2827       .accessfn = gt_vtimer_access,
2828       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2829     },
2830     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2831       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2832       .access = PL0_RW,
2833       .type = ARM_CP_IO,
2834       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2835       .resetvalue = 0, .accessfn = gt_vtimer_access,
2836       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2837     },
2838     /* Secure timer -- this is actually restricted to only EL3
2839      * and configurably Secure-EL1 via the accessfn.
2840      */
2841     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2842       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2843       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2844       .accessfn = gt_stimer_access,
2845       .readfn = gt_sec_tval_read,
2846       .writefn = gt_sec_tval_write,
2847       .resetfn = gt_sec_timer_reset,
2848     },
2849     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2850       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2851       .type = ARM_CP_IO, .access = PL1_RW,
2852       .accessfn = gt_stimer_access,
2853       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2854       .resetvalue = 0,
2855       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2856     },
2857     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2858       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2859       .type = ARM_CP_IO, .access = PL1_RW,
2860       .accessfn = gt_stimer_access,
2861       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2862       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2863     },
2864     REGINFO_SENTINEL
2865 };
2866 
2867 #else
2868 
2869 /* In user-mode most of the generic timer registers are inaccessible
2870  * however modern kernels (4.12+) allow access to cntvct_el0
2871  */
2872 
2873 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2874 {
2875     /* Currently we have no support for QEMUTimer in linux-user so we
2876      * can't call gt_get_countervalue(env), instead we directly
2877      * call the lower level functions.
2878      */
2879     return cpu_get_clock() / GTIMER_SCALE;
2880 }
2881 
2882 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2883     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2884       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2885       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
2886       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2887       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
2888     },
2889     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2890       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2891       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2892       .readfn = gt_virt_cnt_read,
2893     },
2894     REGINFO_SENTINEL
2895 };
2896 
2897 #endif
2898 
2899 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2900 {
2901     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2902         raw_write(env, ri, value);
2903     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2904         raw_write(env, ri, value & 0xfffff6ff);
2905     } else {
2906         raw_write(env, ri, value & 0xfffff1ff);
2907     }
2908 }
2909 
2910 #ifndef CONFIG_USER_ONLY
2911 /* get_phys_addr() isn't present for user-mode-only targets */
2912 
2913 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2914                                  bool isread)
2915 {
2916     if (ri->opc2 & 4) {
2917         /* The ATS12NSO* operations must trap to EL3 if executed in
2918          * Secure EL1 (which can only happen if EL3 is AArch64).
2919          * They are simply UNDEF if executed from NS EL1.
2920          * They function normally from EL2 or EL3.
2921          */
2922         if (arm_current_el(env) == 1) {
2923             if (arm_is_secure_below_el3(env)) {
2924                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2925             }
2926             return CP_ACCESS_TRAP_UNCATEGORIZED;
2927         }
2928     }
2929     return CP_ACCESS_OK;
2930 }
2931 
2932 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2933                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2934 {
2935     hwaddr phys_addr;
2936     target_ulong page_size;
2937     int prot;
2938     bool ret;
2939     uint64_t par64;
2940     bool format64 = false;
2941     MemTxAttrs attrs = {};
2942     ARMMMUFaultInfo fi = {};
2943     ARMCacheAttrs cacheattrs = {};
2944 
2945     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2946                         &prot, &page_size, &fi, &cacheattrs);
2947 
2948     if (is_a64(env)) {
2949         format64 = true;
2950     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
2951         /*
2952          * ATS1Cxx:
2953          * * TTBCR.EAE determines whether the result is returned using the
2954          *   32-bit or the 64-bit PAR format
2955          * * Instructions executed in Hyp mode always use the 64bit format
2956          *
2957          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
2958          * * The Non-secure TTBCR.EAE bit is set to 1
2959          * * The implementation includes EL2, and the value of HCR.VM is 1
2960          *
2961          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
2962          *
2963          * ATS1Hx always uses the 64bit format.
2964          */
2965         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
2966 
2967         if (arm_feature(env, ARM_FEATURE_EL2)) {
2968             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
2969                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
2970             } else {
2971                 format64 |= arm_current_el(env) == 2;
2972             }
2973         }
2974     }
2975 
2976     if (format64) {
2977         /* Create a 64-bit PAR */
2978         par64 = (1 << 11); /* LPAE bit always set */
2979         if (!ret) {
2980             par64 |= phys_addr & ~0xfffULL;
2981             if (!attrs.secure) {
2982                 par64 |= (1 << 9); /* NS */
2983             }
2984             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
2985             par64 |= cacheattrs.shareability << 7; /* SH */
2986         } else {
2987             uint32_t fsr = arm_fi_to_lfsc(&fi);
2988 
2989             par64 |= 1; /* F */
2990             par64 |= (fsr & 0x3f) << 1; /* FS */
2991             if (fi.stage2) {
2992                 par64 |= (1 << 9); /* S */
2993             }
2994             if (fi.s1ptw) {
2995                 par64 |= (1 << 8); /* PTW */
2996             }
2997         }
2998     } else {
2999         /* fsr is a DFSR/IFSR value for the short descriptor
3000          * translation table format (with WnR always clear).
3001          * Convert it to a 32-bit PAR.
3002          */
3003         if (!ret) {
3004             /* We do not set any attribute bits in the PAR */
3005             if (page_size == (1 << 24)
3006                 && arm_feature(env, ARM_FEATURE_V7)) {
3007                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3008             } else {
3009                 par64 = phys_addr & 0xfffff000;
3010             }
3011             if (!attrs.secure) {
3012                 par64 |= (1 << 9); /* NS */
3013             }
3014         } else {
3015             uint32_t fsr = arm_fi_to_sfsc(&fi);
3016 
3017             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3018                     ((fsr & 0xf) << 1) | 1;
3019         }
3020     }
3021     return par64;
3022 }
3023 
3024 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3025 {
3026     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3027     uint64_t par64;
3028     ARMMMUIdx mmu_idx;
3029     int el = arm_current_el(env);
3030     bool secure = arm_is_secure_below_el3(env);
3031 
3032     switch (ri->opc2 & 6) {
3033     case 0:
3034         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
3035         switch (el) {
3036         case 3:
3037             mmu_idx = ARMMMUIdx_S1E3;
3038             break;
3039         case 2:
3040             mmu_idx = ARMMMUIdx_S1NSE1;
3041             break;
3042         case 1:
3043             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3044             break;
3045         default:
3046             g_assert_not_reached();
3047         }
3048         break;
3049     case 2:
3050         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3051         switch (el) {
3052         case 3:
3053             mmu_idx = ARMMMUIdx_S1SE0;
3054             break;
3055         case 2:
3056             mmu_idx = ARMMMUIdx_S1NSE0;
3057             break;
3058         case 1:
3059             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3060             break;
3061         default:
3062             g_assert_not_reached();
3063         }
3064         break;
3065     case 4:
3066         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3067         mmu_idx = ARMMMUIdx_S12NSE1;
3068         break;
3069     case 6:
3070         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3071         mmu_idx = ARMMMUIdx_S12NSE0;
3072         break;
3073     default:
3074         g_assert_not_reached();
3075     }
3076 
3077     par64 = do_ats_write(env, value, access_type, mmu_idx);
3078 
3079     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3080 }
3081 
3082 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3083                         uint64_t value)
3084 {
3085     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3086     uint64_t par64;
3087 
3088     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S1E2);
3089 
3090     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3091 }
3092 
3093 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3094                                      bool isread)
3095 {
3096     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
3097         return CP_ACCESS_TRAP;
3098     }
3099     return CP_ACCESS_OK;
3100 }
3101 
3102 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3103                         uint64_t value)
3104 {
3105     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3106     ARMMMUIdx mmu_idx;
3107     int secure = arm_is_secure_below_el3(env);
3108 
3109     switch (ri->opc2 & 6) {
3110     case 0:
3111         switch (ri->opc1) {
3112         case 0: /* AT S1E1R, AT S1E1W */
3113             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3114             break;
3115         case 4: /* AT S1E2R, AT S1E2W */
3116             mmu_idx = ARMMMUIdx_S1E2;
3117             break;
3118         case 6: /* AT S1E3R, AT S1E3W */
3119             mmu_idx = ARMMMUIdx_S1E3;
3120             break;
3121         default:
3122             g_assert_not_reached();
3123         }
3124         break;
3125     case 2: /* AT S1E0R, AT S1E0W */
3126         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3127         break;
3128     case 4: /* AT S12E1R, AT S12E1W */
3129         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
3130         break;
3131     case 6: /* AT S12E0R, AT S12E0W */
3132         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
3133         break;
3134     default:
3135         g_assert_not_reached();
3136     }
3137 
3138     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3139 }
3140 #endif
3141 
3142 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3143     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3144       .access = PL1_RW, .resetvalue = 0,
3145       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3146                              offsetoflow32(CPUARMState, cp15.par_ns) },
3147       .writefn = par_write },
3148 #ifndef CONFIG_USER_ONLY
3149     /* This underdecoding is safe because the reginfo is NO_RAW. */
3150     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3151       .access = PL1_W, .accessfn = ats_access,
3152       .writefn = ats_write, .type = ARM_CP_NO_RAW },
3153 #endif
3154     REGINFO_SENTINEL
3155 };
3156 
3157 /* Return basic MPU access permission bits.  */
3158 static uint32_t simple_mpu_ap_bits(uint32_t val)
3159 {
3160     uint32_t ret;
3161     uint32_t mask;
3162     int i;
3163     ret = 0;
3164     mask = 3;
3165     for (i = 0; i < 16; i += 2) {
3166         ret |= (val >> i) & mask;
3167         mask <<= 2;
3168     }
3169     return ret;
3170 }
3171 
3172 /* Pad basic MPU access permission bits to extended format.  */
3173 static uint32_t extended_mpu_ap_bits(uint32_t val)
3174 {
3175     uint32_t ret;
3176     uint32_t mask;
3177     int i;
3178     ret = 0;
3179     mask = 3;
3180     for (i = 0; i < 16; i += 2) {
3181         ret |= (val & mask) << i;
3182         mask <<= 2;
3183     }
3184     return ret;
3185 }
3186 
3187 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3188                                  uint64_t value)
3189 {
3190     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3191 }
3192 
3193 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3194 {
3195     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3196 }
3197 
3198 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3199                                  uint64_t value)
3200 {
3201     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3202 }
3203 
3204 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3205 {
3206     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3207 }
3208 
3209 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3210 {
3211     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3212 
3213     if (!u32p) {
3214         return 0;
3215     }
3216 
3217     u32p += env->pmsav7.rnr[M_REG_NS];
3218     return *u32p;
3219 }
3220 
3221 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3222                          uint64_t value)
3223 {
3224     ARMCPU *cpu = env_archcpu(env);
3225     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3226 
3227     if (!u32p) {
3228         return;
3229     }
3230 
3231     u32p += env->pmsav7.rnr[M_REG_NS];
3232     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3233     *u32p = value;
3234 }
3235 
3236 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3237                               uint64_t value)
3238 {
3239     ARMCPU *cpu = env_archcpu(env);
3240     uint32_t nrgs = cpu->pmsav7_dregion;
3241 
3242     if (value >= nrgs) {
3243         qemu_log_mask(LOG_GUEST_ERROR,
3244                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3245                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3246         return;
3247     }
3248 
3249     raw_write(env, ri, value);
3250 }
3251 
3252 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3253     /* Reset for all these registers is handled in arm_cpu_reset(),
3254      * because the PMSAv7 is also used by M-profile CPUs, which do
3255      * not register cpregs but still need the state to be reset.
3256      */
3257     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3258       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3259       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3260       .readfn = pmsav7_read, .writefn = pmsav7_write,
3261       .resetfn = arm_cp_reset_ignore },
3262     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3263       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3264       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3265       .readfn = pmsav7_read, .writefn = pmsav7_write,
3266       .resetfn = arm_cp_reset_ignore },
3267     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3268       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3269       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3270       .readfn = pmsav7_read, .writefn = pmsav7_write,
3271       .resetfn = arm_cp_reset_ignore },
3272     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3273       .access = PL1_RW,
3274       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3275       .writefn = pmsav7_rgnr_write,
3276       .resetfn = arm_cp_reset_ignore },
3277     REGINFO_SENTINEL
3278 };
3279 
3280 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3281     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3282       .access = PL1_RW, .type = ARM_CP_ALIAS,
3283       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3284       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3285     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3286       .access = PL1_RW, .type = ARM_CP_ALIAS,
3287       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3288       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3289     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3290       .access = PL1_RW,
3291       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3292       .resetvalue = 0, },
3293     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3294       .access = PL1_RW,
3295       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3296       .resetvalue = 0, },
3297     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3298       .access = PL1_RW,
3299       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3300     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3301       .access = PL1_RW,
3302       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3303     /* Protection region base and size registers */
3304     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3305       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3306       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3307     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3308       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3309       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3310     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3311       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3312       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3313     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3314       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3315       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3316     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3317       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3318       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3319     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3320       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3321       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3322     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3323       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3324       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3325     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3326       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3327       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3328     REGINFO_SENTINEL
3329 };
3330 
3331 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3332                                  uint64_t value)
3333 {
3334     TCR *tcr = raw_ptr(env, ri);
3335     int maskshift = extract32(value, 0, 3);
3336 
3337     if (!arm_feature(env, ARM_FEATURE_V8)) {
3338         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3339             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3340              * using Long-desciptor translation table format */
3341             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3342         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3343             /* In an implementation that includes the Security Extensions
3344              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3345              * Short-descriptor translation table format.
3346              */
3347             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3348         } else {
3349             value &= TTBCR_N;
3350         }
3351     }
3352 
3353     /* Update the masks corresponding to the TCR bank being written
3354      * Note that we always calculate mask and base_mask, but
3355      * they are only used for short-descriptor tables (ie if EAE is 0);
3356      * for long-descriptor tables the TCR fields are used differently
3357      * and the mask and base_mask values are meaningless.
3358      */
3359     tcr->raw_tcr = value;
3360     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3361     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3362 }
3363 
3364 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3365                              uint64_t value)
3366 {
3367     ARMCPU *cpu = env_archcpu(env);
3368     TCR *tcr = raw_ptr(env, ri);
3369 
3370     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3371         /* With LPAE the TTBCR could result in a change of ASID
3372          * via the TTBCR.A1 bit, so do a TLB flush.
3373          */
3374         tlb_flush(CPU(cpu));
3375     }
3376     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3377     value = deposit64(tcr->raw_tcr, 0, 32, value);
3378     vmsa_ttbcr_raw_write(env, ri, value);
3379 }
3380 
3381 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3382 {
3383     TCR *tcr = raw_ptr(env, ri);
3384 
3385     /* Reset both the TCR as well as the masks corresponding to the bank of
3386      * the TCR being reset.
3387      */
3388     tcr->raw_tcr = 0;
3389     tcr->mask = 0;
3390     tcr->base_mask = 0xffffc000u;
3391 }
3392 
3393 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3394                                uint64_t value)
3395 {
3396     ARMCPU *cpu = env_archcpu(env);
3397     TCR *tcr = raw_ptr(env, ri);
3398 
3399     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3400     tlb_flush(CPU(cpu));
3401     tcr->raw_tcr = value;
3402 }
3403 
3404 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3405                             uint64_t value)
3406 {
3407     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3408     if (cpreg_field_is_64bit(ri) &&
3409         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3410         ARMCPU *cpu = env_archcpu(env);
3411         tlb_flush(CPU(cpu));
3412     }
3413     raw_write(env, ri, value);
3414 }
3415 
3416 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3417                         uint64_t value)
3418 {
3419     ARMCPU *cpu = env_archcpu(env);
3420     CPUState *cs = CPU(cpu);
3421 
3422     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
3423     if (raw_read(env, ri) != value) {
3424         tlb_flush_by_mmuidx(cs,
3425                             ARMMMUIdxBit_S12NSE1 |
3426                             ARMMMUIdxBit_S12NSE0 |
3427                             ARMMMUIdxBit_S2NS);
3428         raw_write(env, ri, value);
3429     }
3430 }
3431 
3432 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3433     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3434       .access = PL1_RW, .type = ARM_CP_ALIAS,
3435       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3436                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3437     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3438       .access = PL1_RW, .resetvalue = 0,
3439       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3440                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3441     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3442       .access = PL1_RW, .resetvalue = 0,
3443       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3444                              offsetof(CPUARMState, cp15.dfar_ns) } },
3445     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3446       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3447       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3448       .resetvalue = 0, },
3449     REGINFO_SENTINEL
3450 };
3451 
3452 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3453     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3454       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3455       .access = PL1_RW,
3456       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3457     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3458       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3459       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3460       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3461                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3462     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3463       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3464       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3465       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3466                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3467     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3468       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3469       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
3470       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3471       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3472     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3473       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3474       .raw_writefn = vmsa_ttbcr_raw_write,
3475       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
3476                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
3477     REGINFO_SENTINEL
3478 };
3479 
3480 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3481  * qemu tlbs nor adjusting cached masks.
3482  */
3483 static const ARMCPRegInfo ttbcr2_reginfo = {
3484     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3485     .access = PL1_RW, .type = ARM_CP_ALIAS,
3486     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
3487                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
3488 };
3489 
3490 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3491                                 uint64_t value)
3492 {
3493     env->cp15.c15_ticonfig = value & 0xe7;
3494     /* The OS_TYPE bit in this register changes the reported CPUID! */
3495     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3496         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3497 }
3498 
3499 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3500                                 uint64_t value)
3501 {
3502     env->cp15.c15_threadid = value & 0xffff;
3503 }
3504 
3505 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3506                            uint64_t value)
3507 {
3508     /* Wait-for-interrupt (deprecated) */
3509     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
3510 }
3511 
3512 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3513                                   uint64_t value)
3514 {
3515     /* On OMAP there are registers indicating the max/min index of dcache lines
3516      * containing a dirty line; cache flush operations have to reset these.
3517      */
3518     env->cp15.c15_i_max = 0x000;
3519     env->cp15.c15_i_min = 0xff0;
3520 }
3521 
3522 static const ARMCPRegInfo omap_cp_reginfo[] = {
3523     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3524       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3525       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3526       .resetvalue = 0, },
3527     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3528       .access = PL1_RW, .type = ARM_CP_NOP },
3529     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3530       .access = PL1_RW,
3531       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3532       .writefn = omap_ticonfig_write },
3533     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3534       .access = PL1_RW,
3535       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3536     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3537       .access = PL1_RW, .resetvalue = 0xff0,
3538       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3539     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3540       .access = PL1_RW,
3541       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3542       .writefn = omap_threadid_write },
3543     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3544       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3545       .type = ARM_CP_NO_RAW,
3546       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3547     /* TODO: Peripheral port remap register:
3548      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3549      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3550      * when MMU is off.
3551      */
3552     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3553       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3554       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3555       .writefn = omap_cachemaint_write },
3556     { .name = "C9", .cp = 15, .crn = 9,
3557       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3558       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3559     REGINFO_SENTINEL
3560 };
3561 
3562 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3563                               uint64_t value)
3564 {
3565     env->cp15.c15_cpar = value & 0x3fff;
3566 }
3567 
3568 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3569     { .name = "XSCALE_CPAR",
3570       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3571       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3572       .writefn = xscale_cpar_write, },
3573     { .name = "XSCALE_AUXCR",
3574       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3575       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3576       .resetvalue = 0, },
3577     /* XScale specific cache-lockdown: since we have no cache we NOP these
3578      * and hope the guest does not really rely on cache behaviour.
3579      */
3580     { .name = "XSCALE_LOCK_ICACHE_LINE",
3581       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3582       .access = PL1_W, .type = ARM_CP_NOP },
3583     { .name = "XSCALE_UNLOCK_ICACHE",
3584       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3585       .access = PL1_W, .type = ARM_CP_NOP },
3586     { .name = "XSCALE_DCACHE_LOCK",
3587       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3588       .access = PL1_RW, .type = ARM_CP_NOP },
3589     { .name = "XSCALE_UNLOCK_DCACHE",
3590       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3591       .access = PL1_W, .type = ARM_CP_NOP },
3592     REGINFO_SENTINEL
3593 };
3594 
3595 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3596     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3597      * implementation of this implementation-defined space.
3598      * Ideally this should eventually disappear in favour of actually
3599      * implementing the correct behaviour for all cores.
3600      */
3601     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3602       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3603       .access = PL1_RW,
3604       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3605       .resetvalue = 0 },
3606     REGINFO_SENTINEL
3607 };
3608 
3609 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3610     /* Cache status: RAZ because we have no cache so it's always clean */
3611     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3612       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3613       .resetvalue = 0 },
3614     REGINFO_SENTINEL
3615 };
3616 
3617 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
3618     /* We never have a a block transfer operation in progress */
3619     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
3620       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3621       .resetvalue = 0 },
3622     /* The cache ops themselves: these all NOP for QEMU */
3623     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
3624       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3625     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
3626       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3627     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
3628       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3629     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
3630       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3631     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
3632       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3633     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
3634       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3635     REGINFO_SENTINEL
3636 };
3637 
3638 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
3639     /* The cache test-and-clean instructions always return (1 << 30)
3640      * to indicate that there are no dirty cache lines.
3641      */
3642     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
3643       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3644       .resetvalue = (1 << 30) },
3645     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
3646       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3647       .resetvalue = (1 << 30) },
3648     REGINFO_SENTINEL
3649 };
3650 
3651 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
3652     /* Ignore ReadBuffer accesses */
3653     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
3654       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3655       .access = PL1_RW, .resetvalue = 0,
3656       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
3657     REGINFO_SENTINEL
3658 };
3659 
3660 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3661 {
3662     ARMCPU *cpu = env_archcpu(env);
3663     unsigned int cur_el = arm_current_el(env);
3664     bool secure = arm_is_secure(env);
3665 
3666     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3667         return env->cp15.vpidr_el2;
3668     }
3669     return raw_read(env, ri);
3670 }
3671 
3672 static uint64_t mpidr_read_val(CPUARMState *env)
3673 {
3674     ARMCPU *cpu = env_archcpu(env);
3675     uint64_t mpidr = cpu->mp_affinity;
3676 
3677     if (arm_feature(env, ARM_FEATURE_V7MP)) {
3678         mpidr |= (1U << 31);
3679         /* Cores which are uniprocessor (non-coherent)
3680          * but still implement the MP extensions set
3681          * bit 30. (For instance, Cortex-R5).
3682          */
3683         if (cpu->mp_is_up) {
3684             mpidr |= (1u << 30);
3685         }
3686     }
3687     return mpidr;
3688 }
3689 
3690 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3691 {
3692     unsigned int cur_el = arm_current_el(env);
3693     bool secure = arm_is_secure(env);
3694 
3695     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3696         return env->cp15.vmpidr_el2;
3697     }
3698     return mpidr_read_val(env);
3699 }
3700 
3701 static const ARMCPRegInfo lpae_cp_reginfo[] = {
3702     /* NOP AMAIR0/1 */
3703     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
3704       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
3705       .access = PL1_RW, .type = ARM_CP_CONST,
3706       .resetvalue = 0 },
3707     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
3708     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
3709       .access = PL1_RW, .type = ARM_CP_CONST,
3710       .resetvalue = 0 },
3711     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
3712       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
3713       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
3714                              offsetof(CPUARMState, cp15.par_ns)} },
3715     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
3716       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3717       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3718                              offsetof(CPUARMState, cp15.ttbr0_ns) },
3719       .writefn = vmsa_ttbr_write, },
3720     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
3721       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3722       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3723                              offsetof(CPUARMState, cp15.ttbr1_ns) },
3724       .writefn = vmsa_ttbr_write, },
3725     REGINFO_SENTINEL
3726 };
3727 
3728 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3729 {
3730     return vfp_get_fpcr(env);
3731 }
3732 
3733 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3734                             uint64_t value)
3735 {
3736     vfp_set_fpcr(env, value);
3737 }
3738 
3739 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3740 {
3741     return vfp_get_fpsr(env);
3742 }
3743 
3744 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3745                             uint64_t value)
3746 {
3747     vfp_set_fpsr(env, value);
3748 }
3749 
3750 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
3751                                        bool isread)
3752 {
3753     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
3754         return CP_ACCESS_TRAP;
3755     }
3756     return CP_ACCESS_OK;
3757 }
3758 
3759 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3760                             uint64_t value)
3761 {
3762     env->daif = value & PSTATE_DAIF;
3763 }
3764 
3765 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3766                                           const ARMCPRegInfo *ri,
3767                                           bool isread)
3768 {
3769     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3770      * SCTLR_EL1.UCI is set.
3771      */
3772     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3773         return CP_ACCESS_TRAP;
3774     }
3775     return CP_ACCESS_OK;
3776 }
3777 
3778 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3779  * Page D4-1736 (DDI0487A.b)
3780  */
3781 
3782 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3783                                       uint64_t value)
3784 {
3785     CPUState *cs = env_cpu(env);
3786     bool sec = arm_is_secure_below_el3(env);
3787 
3788     if (sec) {
3789         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3790                                             ARMMMUIdxBit_S1SE1 |
3791                                             ARMMMUIdxBit_S1SE0);
3792     } else {
3793         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3794                                             ARMMMUIdxBit_S12NSE1 |
3795                                             ARMMMUIdxBit_S12NSE0);
3796     }
3797 }
3798 
3799 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3800                                     uint64_t value)
3801 {
3802     CPUState *cs = env_cpu(env);
3803 
3804     if (tlb_force_broadcast(env)) {
3805         tlbi_aa64_vmalle1is_write(env, NULL, value);
3806         return;
3807     }
3808 
3809     if (arm_is_secure_below_el3(env)) {
3810         tlb_flush_by_mmuidx(cs,
3811                             ARMMMUIdxBit_S1SE1 |
3812                             ARMMMUIdxBit_S1SE0);
3813     } else {
3814         tlb_flush_by_mmuidx(cs,
3815                             ARMMMUIdxBit_S12NSE1 |
3816                             ARMMMUIdxBit_S12NSE0);
3817     }
3818 }
3819 
3820 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3821                                   uint64_t value)
3822 {
3823     /* Note that the 'ALL' scope must invalidate both stage 1 and
3824      * stage 2 translations, whereas most other scopes only invalidate
3825      * stage 1 translations.
3826      */
3827     ARMCPU *cpu = env_archcpu(env);
3828     CPUState *cs = CPU(cpu);
3829 
3830     if (arm_is_secure_below_el3(env)) {
3831         tlb_flush_by_mmuidx(cs,
3832                             ARMMMUIdxBit_S1SE1 |
3833                             ARMMMUIdxBit_S1SE0);
3834     } else {
3835         if (arm_feature(env, ARM_FEATURE_EL2)) {
3836             tlb_flush_by_mmuidx(cs,
3837                                 ARMMMUIdxBit_S12NSE1 |
3838                                 ARMMMUIdxBit_S12NSE0 |
3839                                 ARMMMUIdxBit_S2NS);
3840         } else {
3841             tlb_flush_by_mmuidx(cs,
3842                                 ARMMMUIdxBit_S12NSE1 |
3843                                 ARMMMUIdxBit_S12NSE0);
3844         }
3845     }
3846 }
3847 
3848 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3849                                   uint64_t value)
3850 {
3851     ARMCPU *cpu = env_archcpu(env);
3852     CPUState *cs = CPU(cpu);
3853 
3854     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3855 }
3856 
3857 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3858                                   uint64_t value)
3859 {
3860     ARMCPU *cpu = env_archcpu(env);
3861     CPUState *cs = CPU(cpu);
3862 
3863     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3864 }
3865 
3866 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3867                                     uint64_t value)
3868 {
3869     /* Note that the 'ALL' scope must invalidate both stage 1 and
3870      * stage 2 translations, whereas most other scopes only invalidate
3871      * stage 1 translations.
3872      */
3873     CPUState *cs = env_cpu(env);
3874     bool sec = arm_is_secure_below_el3(env);
3875     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3876 
3877     if (sec) {
3878         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3879                                             ARMMMUIdxBit_S1SE1 |
3880                                             ARMMMUIdxBit_S1SE0);
3881     } else if (has_el2) {
3882         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3883                                             ARMMMUIdxBit_S12NSE1 |
3884                                             ARMMMUIdxBit_S12NSE0 |
3885                                             ARMMMUIdxBit_S2NS);
3886     } else {
3887           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3888                                               ARMMMUIdxBit_S12NSE1 |
3889                                               ARMMMUIdxBit_S12NSE0);
3890     }
3891 }
3892 
3893 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3894                                     uint64_t value)
3895 {
3896     CPUState *cs = env_cpu(env);
3897 
3898     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3899 }
3900 
3901 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3902                                     uint64_t value)
3903 {
3904     CPUState *cs = env_cpu(env);
3905 
3906     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3907 }
3908 
3909 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3910                                  uint64_t value)
3911 {
3912     /* Invalidate by VA, EL2
3913      * Currently handles both VAE2 and VALE2, since we don't support
3914      * flush-last-level-only.
3915      */
3916     ARMCPU *cpu = env_archcpu(env);
3917     CPUState *cs = CPU(cpu);
3918     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3919 
3920     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3921 }
3922 
3923 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3924                                  uint64_t value)
3925 {
3926     /* Invalidate by VA, EL3
3927      * Currently handles both VAE3 and VALE3, since we don't support
3928      * flush-last-level-only.
3929      */
3930     ARMCPU *cpu = env_archcpu(env);
3931     CPUState *cs = CPU(cpu);
3932     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3933 
3934     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
3935 }
3936 
3937 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3938                                    uint64_t value)
3939 {
3940     ARMCPU *cpu = env_archcpu(env);
3941     CPUState *cs = CPU(cpu);
3942     bool sec = arm_is_secure_below_el3(env);
3943     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3944 
3945     if (sec) {
3946         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3947                                                  ARMMMUIdxBit_S1SE1 |
3948                                                  ARMMMUIdxBit_S1SE0);
3949     } else {
3950         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3951                                                  ARMMMUIdxBit_S12NSE1 |
3952                                                  ARMMMUIdxBit_S12NSE0);
3953     }
3954 }
3955 
3956 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3957                                  uint64_t value)
3958 {
3959     /* Invalidate by VA, EL1&0 (AArch64 version).
3960      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3961      * since we don't support flush-for-specific-ASID-only or
3962      * flush-last-level-only.
3963      */
3964     ARMCPU *cpu = env_archcpu(env);
3965     CPUState *cs = CPU(cpu);
3966     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3967 
3968     if (tlb_force_broadcast(env)) {
3969         tlbi_aa64_vae1is_write(env, NULL, value);
3970         return;
3971     }
3972 
3973     if (arm_is_secure_below_el3(env)) {
3974         tlb_flush_page_by_mmuidx(cs, pageaddr,
3975                                  ARMMMUIdxBit_S1SE1 |
3976                                  ARMMMUIdxBit_S1SE0);
3977     } else {
3978         tlb_flush_page_by_mmuidx(cs, pageaddr,
3979                                  ARMMMUIdxBit_S12NSE1 |
3980                                  ARMMMUIdxBit_S12NSE0);
3981     }
3982 }
3983 
3984 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3985                                    uint64_t value)
3986 {
3987     CPUState *cs = env_cpu(env);
3988     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3989 
3990     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3991                                              ARMMMUIdxBit_S1E2);
3992 }
3993 
3994 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3995                                    uint64_t value)
3996 {
3997     CPUState *cs = env_cpu(env);
3998     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3999 
4000     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4001                                              ARMMMUIdxBit_S1E3);
4002 }
4003 
4004 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4005                                     uint64_t value)
4006 {
4007     /* Invalidate by IPA. This has to invalidate any structures that
4008      * contain only stage 2 translation information, but does not need
4009      * to apply to structures that contain combined stage 1 and stage 2
4010      * translation information.
4011      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
4012      */
4013     ARMCPU *cpu = env_archcpu(env);
4014     CPUState *cs = CPU(cpu);
4015     uint64_t pageaddr;
4016 
4017     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4018         return;
4019     }
4020 
4021     pageaddr = sextract64(value << 12, 0, 48);
4022 
4023     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
4024 }
4025 
4026 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4027                                       uint64_t value)
4028 {
4029     CPUState *cs = env_cpu(env);
4030     uint64_t pageaddr;
4031 
4032     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4033         return;
4034     }
4035 
4036     pageaddr = sextract64(value << 12, 0, 48);
4037 
4038     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4039                                              ARMMMUIdxBit_S2NS);
4040 }
4041 
4042 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4043                                       bool isread)
4044 {
4045     /* We don't implement EL2, so the only control on DC ZVA is the
4046      * bit in the SCTLR which can prohibit access for EL0.
4047      */
4048     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4049         return CP_ACCESS_TRAP;
4050     }
4051     return CP_ACCESS_OK;
4052 }
4053 
4054 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4055 {
4056     ARMCPU *cpu = env_archcpu(env);
4057     int dzp_bit = 1 << 4;
4058 
4059     /* DZP indicates whether DC ZVA access is allowed */
4060     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4061         dzp_bit = 0;
4062     }
4063     return cpu->dcz_blocksize | dzp_bit;
4064 }
4065 
4066 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4067                                     bool isread)
4068 {
4069     if (!(env->pstate & PSTATE_SP)) {
4070         /* Access to SP_EL0 is undefined if it's being used as
4071          * the stack pointer.
4072          */
4073         return CP_ACCESS_TRAP_UNCATEGORIZED;
4074     }
4075     return CP_ACCESS_OK;
4076 }
4077 
4078 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4079 {
4080     return env->pstate & PSTATE_SP;
4081 }
4082 
4083 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4084 {
4085     update_spsel(env, val);
4086 }
4087 
4088 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4089                         uint64_t value)
4090 {
4091     ARMCPU *cpu = env_archcpu(env);
4092 
4093     if (raw_read(env, ri) == value) {
4094         /* Skip the TLB flush if nothing actually changed; Linux likes
4095          * to do a lot of pointless SCTLR writes.
4096          */
4097         return;
4098     }
4099 
4100     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4101         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4102         value &= ~SCTLR_M;
4103     }
4104 
4105     raw_write(env, ri, value);
4106     /* ??? Lots of these bits are not implemented.  */
4107     /* This may enable/disable the MMU, so do a TLB flush.  */
4108     tlb_flush(CPU(cpu));
4109 }
4110 
4111 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4112                                      bool isread)
4113 {
4114     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4115         return CP_ACCESS_TRAP_FP_EL2;
4116     }
4117     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4118         return CP_ACCESS_TRAP_FP_EL3;
4119     }
4120     return CP_ACCESS_OK;
4121 }
4122 
4123 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4124                        uint64_t value)
4125 {
4126     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4127 }
4128 
4129 static const ARMCPRegInfo v8_cp_reginfo[] = {
4130     /* Minimal set of EL0-visible registers. This will need to be expanded
4131      * significantly for system emulation of AArch64 CPUs.
4132      */
4133     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4134       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4135       .access = PL0_RW, .type = ARM_CP_NZCV },
4136     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4137       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4138       .type = ARM_CP_NO_RAW,
4139       .access = PL0_RW, .accessfn = aa64_daif_access,
4140       .fieldoffset = offsetof(CPUARMState, daif),
4141       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4142     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4143       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4144       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4145       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4146     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4147       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4148       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4149       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4150     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4151       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4152       .access = PL0_R, .type = ARM_CP_NO_RAW,
4153       .readfn = aa64_dczid_read },
4154     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4155       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4156       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4157 #ifndef CONFIG_USER_ONLY
4158       /* Avoid overhead of an access check that always passes in user-mode */
4159       .accessfn = aa64_zva_access,
4160 #endif
4161     },
4162     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4163       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4164       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4165     /* Cache ops: all NOPs since we don't emulate caches */
4166     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4167       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4168       .access = PL1_W, .type = ARM_CP_NOP },
4169     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4170       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4171       .access = PL1_W, .type = ARM_CP_NOP },
4172     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4173       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4174       .access = PL0_W, .type = ARM_CP_NOP,
4175       .accessfn = aa64_cacheop_access },
4176     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4177       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4178       .access = PL1_W, .type = ARM_CP_NOP },
4179     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4180       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4181       .access = PL1_W, .type = ARM_CP_NOP },
4182     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4183       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4184       .access = PL0_W, .type = ARM_CP_NOP,
4185       .accessfn = aa64_cacheop_access },
4186     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4187       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4188       .access = PL1_W, .type = ARM_CP_NOP },
4189     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4190       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4191       .access = PL0_W, .type = ARM_CP_NOP,
4192       .accessfn = aa64_cacheop_access },
4193     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4194       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4195       .access = PL0_W, .type = ARM_CP_NOP,
4196       .accessfn = aa64_cacheop_access },
4197     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4198       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4199       .access = PL1_W, .type = ARM_CP_NOP },
4200     /* TLBI operations */
4201     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4202       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4203       .access = PL1_W, .type = ARM_CP_NO_RAW,
4204       .writefn = tlbi_aa64_vmalle1is_write },
4205     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4206       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4207       .access = PL1_W, .type = ARM_CP_NO_RAW,
4208       .writefn = tlbi_aa64_vae1is_write },
4209     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4210       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4211       .access = PL1_W, .type = ARM_CP_NO_RAW,
4212       .writefn = tlbi_aa64_vmalle1is_write },
4213     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4214       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4215       .access = PL1_W, .type = ARM_CP_NO_RAW,
4216       .writefn = tlbi_aa64_vae1is_write },
4217     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4218       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4219       .access = PL1_W, .type = ARM_CP_NO_RAW,
4220       .writefn = tlbi_aa64_vae1is_write },
4221     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4222       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4223       .access = PL1_W, .type = ARM_CP_NO_RAW,
4224       .writefn = tlbi_aa64_vae1is_write },
4225     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4226       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4227       .access = PL1_W, .type = ARM_CP_NO_RAW,
4228       .writefn = tlbi_aa64_vmalle1_write },
4229     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4230       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4231       .access = PL1_W, .type = ARM_CP_NO_RAW,
4232       .writefn = tlbi_aa64_vae1_write },
4233     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4234       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4235       .access = PL1_W, .type = ARM_CP_NO_RAW,
4236       .writefn = tlbi_aa64_vmalle1_write },
4237     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4238       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4239       .access = PL1_W, .type = ARM_CP_NO_RAW,
4240       .writefn = tlbi_aa64_vae1_write },
4241     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4242       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4243       .access = PL1_W, .type = ARM_CP_NO_RAW,
4244       .writefn = tlbi_aa64_vae1_write },
4245     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4246       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4247       .access = PL1_W, .type = ARM_CP_NO_RAW,
4248       .writefn = tlbi_aa64_vae1_write },
4249     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4250       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4251       .access = PL2_W, .type = ARM_CP_NO_RAW,
4252       .writefn = tlbi_aa64_ipas2e1is_write },
4253     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4254       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4255       .access = PL2_W, .type = ARM_CP_NO_RAW,
4256       .writefn = tlbi_aa64_ipas2e1is_write },
4257     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4258       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4259       .access = PL2_W, .type = ARM_CP_NO_RAW,
4260       .writefn = tlbi_aa64_alle1is_write },
4261     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4262       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4263       .access = PL2_W, .type = ARM_CP_NO_RAW,
4264       .writefn = tlbi_aa64_alle1is_write },
4265     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4266       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4267       .access = PL2_W, .type = ARM_CP_NO_RAW,
4268       .writefn = tlbi_aa64_ipas2e1_write },
4269     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4270       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4271       .access = PL2_W, .type = ARM_CP_NO_RAW,
4272       .writefn = tlbi_aa64_ipas2e1_write },
4273     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4274       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4275       .access = PL2_W, .type = ARM_CP_NO_RAW,
4276       .writefn = tlbi_aa64_alle1_write },
4277     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4278       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4279       .access = PL2_W, .type = ARM_CP_NO_RAW,
4280       .writefn = tlbi_aa64_alle1is_write },
4281 #ifndef CONFIG_USER_ONLY
4282     /* 64 bit address translation operations */
4283     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4284       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4285       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4286     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4287       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4288       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4289     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4290       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4291       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4292     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4293       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4294       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4295     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4296       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4297       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4298     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4299       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4300       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4301     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4302       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4303       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4304     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4305       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4306       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4307     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4308     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4309       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4310       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4311     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4312       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4313       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4314     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4315       .type = ARM_CP_ALIAS,
4316       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4317       .access = PL1_RW, .resetvalue = 0,
4318       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4319       .writefn = par_write },
4320 #endif
4321     /* TLB invalidate last level of translation table walk */
4322     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4323       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
4324     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4325       .type = ARM_CP_NO_RAW, .access = PL1_W,
4326       .writefn = tlbimvaa_is_write },
4327     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4328       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
4329     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4330       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
4331     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4332       .type = ARM_CP_NO_RAW, .access = PL2_W,
4333       .writefn = tlbimva_hyp_write },
4334     { .name = "TLBIMVALHIS",
4335       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4336       .type = ARM_CP_NO_RAW, .access = PL2_W,
4337       .writefn = tlbimva_hyp_is_write },
4338     { .name = "TLBIIPAS2",
4339       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4340       .type = ARM_CP_NO_RAW, .access = PL2_W,
4341       .writefn = tlbiipas2_write },
4342     { .name = "TLBIIPAS2IS",
4343       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4344       .type = ARM_CP_NO_RAW, .access = PL2_W,
4345       .writefn = tlbiipas2_is_write },
4346     { .name = "TLBIIPAS2L",
4347       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4348       .type = ARM_CP_NO_RAW, .access = PL2_W,
4349       .writefn = tlbiipas2_write },
4350     { .name = "TLBIIPAS2LIS",
4351       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4352       .type = ARM_CP_NO_RAW, .access = PL2_W,
4353       .writefn = tlbiipas2_is_write },
4354     /* 32 bit cache operations */
4355     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4356       .type = ARM_CP_NOP, .access = PL1_W },
4357     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
4358       .type = ARM_CP_NOP, .access = PL1_W },
4359     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4360       .type = ARM_CP_NOP, .access = PL1_W },
4361     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
4362       .type = ARM_CP_NOP, .access = PL1_W },
4363     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
4364       .type = ARM_CP_NOP, .access = PL1_W },
4365     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
4366       .type = ARM_CP_NOP, .access = PL1_W },
4367     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4368       .type = ARM_CP_NOP, .access = PL1_W },
4369     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4370       .type = ARM_CP_NOP, .access = PL1_W },
4371     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
4372       .type = ARM_CP_NOP, .access = PL1_W },
4373     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4374       .type = ARM_CP_NOP, .access = PL1_W },
4375     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
4376       .type = ARM_CP_NOP, .access = PL1_W },
4377     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
4378       .type = ARM_CP_NOP, .access = PL1_W },
4379     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4380       .type = ARM_CP_NOP, .access = PL1_W },
4381     /* MMU Domain access control / MPU write buffer control */
4382     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
4383       .access = PL1_RW, .resetvalue = 0,
4384       .writefn = dacr_write, .raw_writefn = raw_write,
4385       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
4386                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
4387     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
4388       .type = ARM_CP_ALIAS,
4389       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
4390       .access = PL1_RW,
4391       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
4392     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
4393       .type = ARM_CP_ALIAS,
4394       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
4395       .access = PL1_RW,
4396       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
4397     /* We rely on the access checks not allowing the guest to write to the
4398      * state field when SPSel indicates that it's being used as the stack
4399      * pointer.
4400      */
4401     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
4402       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
4403       .access = PL1_RW, .accessfn = sp_el0_access,
4404       .type = ARM_CP_ALIAS,
4405       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
4406     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
4407       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
4408       .access = PL2_RW, .type = ARM_CP_ALIAS,
4409       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
4410     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
4411       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
4412       .type = ARM_CP_NO_RAW,
4413       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
4414     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
4415       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
4416       .type = ARM_CP_ALIAS,
4417       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
4418       .access = PL2_RW, .accessfn = fpexc32_access },
4419     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
4420       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
4421       .access = PL2_RW, .resetvalue = 0,
4422       .writefn = dacr_write, .raw_writefn = raw_write,
4423       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
4424     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
4425       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
4426       .access = PL2_RW, .resetvalue = 0,
4427       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
4428     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
4429       .type = ARM_CP_ALIAS,
4430       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
4431       .access = PL2_RW,
4432       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
4433     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
4434       .type = ARM_CP_ALIAS,
4435       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
4436       .access = PL2_RW,
4437       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
4438     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
4439       .type = ARM_CP_ALIAS,
4440       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
4441       .access = PL2_RW,
4442       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
4443     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
4444       .type = ARM_CP_ALIAS,
4445       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
4446       .access = PL2_RW,
4447       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
4448     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
4449       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
4450       .resetvalue = 0,
4451       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
4452     { .name = "SDCR", .type = ARM_CP_ALIAS,
4453       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
4454       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4455       .writefn = sdcr_write,
4456       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
4457     REGINFO_SENTINEL
4458 };
4459 
4460 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
4461 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
4462     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4463       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4464       .access = PL2_RW,
4465       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
4466     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
4467       .type = ARM_CP_NO_RAW,
4468       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4469       .access = PL2_RW,
4470       .type = ARM_CP_CONST, .resetvalue = 0 },
4471     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4472       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4473       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4474     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4475       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4476       .access = PL2_RW,
4477       .type = ARM_CP_CONST, .resetvalue = 0 },
4478     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4479       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4480       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4481     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4482       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4483       .access = PL2_RW, .type = ARM_CP_CONST,
4484       .resetvalue = 0 },
4485     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4486       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4487       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4488     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4489       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4490       .access = PL2_RW, .type = ARM_CP_CONST,
4491       .resetvalue = 0 },
4492     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4493       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4494       .access = PL2_RW, .type = ARM_CP_CONST,
4495       .resetvalue = 0 },
4496     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4497       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4498       .access = PL2_RW, .type = ARM_CP_CONST,
4499       .resetvalue = 0 },
4500     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4501       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4502       .access = PL2_RW, .type = ARM_CP_CONST,
4503       .resetvalue = 0 },
4504     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4505       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4506       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4507     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
4508       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4509       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4510       .type = ARM_CP_CONST, .resetvalue = 0 },
4511     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4512       .cp = 15, .opc1 = 6, .crm = 2,
4513       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4514       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
4515     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4516       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4517       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4518     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4519       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4520       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4521     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4522       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4523       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4524     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4525       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4526       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4527     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4528       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4529       .resetvalue = 0 },
4530     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4531       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4532       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4533     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4534       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4535       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4536     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4537       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4538       .resetvalue = 0 },
4539     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4540       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4541       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4542     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4543       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4544       .resetvalue = 0 },
4545     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4546       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4547       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4548     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4549       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4550       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4551     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4552       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4553       .access = PL2_RW, .accessfn = access_tda,
4554       .type = ARM_CP_CONST, .resetvalue = 0 },
4555     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
4556       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4557       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4558       .type = ARM_CP_CONST, .resetvalue = 0 },
4559     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4560       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4561       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4562     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4563       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4564       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4565     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4566       .type = ARM_CP_CONST,
4567       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4568       .access = PL2_RW, .resetvalue = 0 },
4569     REGINFO_SENTINEL
4570 };
4571 
4572 /* Ditto, but for registers which exist in ARMv8 but not v7 */
4573 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
4574     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4575       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4576       .access = PL2_RW,
4577       .type = ARM_CP_CONST, .resetvalue = 0 },
4578     REGINFO_SENTINEL
4579 };
4580 
4581 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
4582 {
4583     ARMCPU *cpu = env_archcpu(env);
4584     uint64_t valid_mask = HCR_MASK;
4585 
4586     if (arm_feature(env, ARM_FEATURE_EL3)) {
4587         valid_mask &= ~HCR_HCD;
4588     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
4589         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
4590          * However, if we're using the SMC PSCI conduit then QEMU is
4591          * effectively acting like EL3 firmware and so the guest at
4592          * EL2 should retain the ability to prevent EL1 from being
4593          * able to make SMC calls into the ersatz firmware, so in
4594          * that case HCR.TSC should be read/write.
4595          */
4596         valid_mask &= ~HCR_TSC;
4597     }
4598     if (cpu_isar_feature(aa64_lor, cpu)) {
4599         valid_mask |= HCR_TLOR;
4600     }
4601     if (cpu_isar_feature(aa64_pauth, cpu)) {
4602         valid_mask |= HCR_API | HCR_APK;
4603     }
4604 
4605     /* Clear RES0 bits.  */
4606     value &= valid_mask;
4607 
4608     /* These bits change the MMU setup:
4609      * HCR_VM enables stage 2 translation
4610      * HCR_PTW forbids certain page-table setups
4611      * HCR_DC Disables stage1 and enables stage2 translation
4612      */
4613     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
4614         tlb_flush(CPU(cpu));
4615     }
4616     env->cp15.hcr_el2 = value;
4617 
4618     /*
4619      * Updates to VI and VF require us to update the status of
4620      * virtual interrupts, which are the logical OR of these bits
4621      * and the state of the input lines from the GIC. (This requires
4622      * that we have the iothread lock, which is done by marking the
4623      * reginfo structs as ARM_CP_IO.)
4624      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
4625      * possible for it to be taken immediately, because VIRQ and
4626      * VFIQ are masked unless running at EL0 or EL1, and HCR
4627      * can only be written at EL2.
4628      */
4629     g_assert(qemu_mutex_iothread_locked());
4630     arm_cpu_update_virq(cpu);
4631     arm_cpu_update_vfiq(cpu);
4632 }
4633 
4634 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
4635                           uint64_t value)
4636 {
4637     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
4638     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
4639     hcr_write(env, NULL, value);
4640 }
4641 
4642 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
4643                          uint64_t value)
4644 {
4645     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
4646     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
4647     hcr_write(env, NULL, value);
4648 }
4649 
4650 /*
4651  * Return the effective value of HCR_EL2.
4652  * Bits that are not included here:
4653  * RW       (read from SCR_EL3.RW as needed)
4654  */
4655 uint64_t arm_hcr_el2_eff(CPUARMState *env)
4656 {
4657     uint64_t ret = env->cp15.hcr_el2;
4658 
4659     if (arm_is_secure_below_el3(env)) {
4660         /*
4661          * "This register has no effect if EL2 is not enabled in the
4662          * current Security state".  This is ARMv8.4-SecEL2 speak for
4663          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
4664          *
4665          * Prior to that, the language was "In an implementation that
4666          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
4667          * as if this field is 0 for all purposes other than a direct
4668          * read or write access of HCR_EL2".  With lots of enumeration
4669          * on a per-field basis.  In current QEMU, this is condition
4670          * is arm_is_secure_below_el3.
4671          *
4672          * Since the v8.4 language applies to the entire register, and
4673          * appears to be backward compatible, use that.
4674          */
4675         ret = 0;
4676     } else if (ret & HCR_TGE) {
4677         /* These bits are up-to-date as of ARMv8.4.  */
4678         if (ret & HCR_E2H) {
4679             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
4680                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
4681                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
4682                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE);
4683         } else {
4684             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
4685         }
4686         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
4687                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
4688                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
4689                  HCR_TLOR);
4690     }
4691 
4692     return ret;
4693 }
4694 
4695 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4696                            uint64_t value)
4697 {
4698     /*
4699      * For A-profile AArch32 EL3, if NSACR.CP10
4700      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
4701      */
4702     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
4703         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
4704         value &= ~(0x3 << 10);
4705         value |= env->cp15.cptr_el[2] & (0x3 << 10);
4706     }
4707     env->cp15.cptr_el[2] = value;
4708 }
4709 
4710 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
4711 {
4712     /*
4713      * For A-profile AArch32 EL3, if NSACR.CP10
4714      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
4715      */
4716     uint64_t value = env->cp15.cptr_el[2];
4717 
4718     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
4719         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
4720         value |= 0x3 << 10;
4721     }
4722     return value;
4723 }
4724 
4725 static const ARMCPRegInfo el2_cp_reginfo[] = {
4726     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
4727       .type = ARM_CP_IO,
4728       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4729       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4730       .writefn = hcr_write },
4731     { .name = "HCR", .state = ARM_CP_STATE_AA32,
4732       .type = ARM_CP_ALIAS | ARM_CP_IO,
4733       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4734       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4735       .writefn = hcr_writelow },
4736     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4737       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4738       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4739     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
4740       .type = ARM_CP_ALIAS,
4741       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
4742       .access = PL2_RW,
4743       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
4744     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4745       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4746       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
4747     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4748       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4749       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
4750     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4751       .type = ARM_CP_ALIAS,
4752       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4753       .access = PL2_RW,
4754       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
4755     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
4756       .type = ARM_CP_ALIAS,
4757       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
4758       .access = PL2_RW,
4759       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
4760     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4761       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4762       .access = PL2_RW, .writefn = vbar_write,
4763       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
4764       .resetvalue = 0 },
4765     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
4766       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
4767       .access = PL3_RW, .type = ARM_CP_ALIAS,
4768       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
4769     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4770       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4771       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
4772       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
4773       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
4774     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4775       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4776       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
4777       .resetvalue = 0 },
4778     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4779       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4780       .access = PL2_RW, .type = ARM_CP_ALIAS,
4781       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
4782     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4783       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4784       .access = PL2_RW, .type = ARM_CP_CONST,
4785       .resetvalue = 0 },
4786     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
4787     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4788       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4789       .access = PL2_RW, .type = ARM_CP_CONST,
4790       .resetvalue = 0 },
4791     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4792       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4793       .access = PL2_RW, .type = ARM_CP_CONST,
4794       .resetvalue = 0 },
4795     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4796       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4797       .access = PL2_RW, .type = ARM_CP_CONST,
4798       .resetvalue = 0 },
4799     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4800       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4801       .access = PL2_RW,
4802       /* no .writefn needed as this can't cause an ASID change;
4803        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4804        */
4805       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
4806     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
4807       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4808       .type = ARM_CP_ALIAS,
4809       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4810       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4811     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
4812       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4813       .access = PL2_RW,
4814       /* no .writefn needed as this can't cause an ASID change;
4815        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4816        */
4817       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4818     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4819       .cp = 15, .opc1 = 6, .crm = 2,
4820       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4821       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4822       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
4823       .writefn = vttbr_write },
4824     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4825       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4826       .access = PL2_RW, .writefn = vttbr_write,
4827       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
4828     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4829       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4830       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
4831       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
4832     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4833       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4834       .access = PL2_RW, .resetvalue = 0,
4835       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
4836     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4837       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4838       .access = PL2_RW, .resetvalue = 0,
4839       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4840     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4841       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4842       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4843     { .name = "TLBIALLNSNH",
4844       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4845       .type = ARM_CP_NO_RAW, .access = PL2_W,
4846       .writefn = tlbiall_nsnh_write },
4847     { .name = "TLBIALLNSNHIS",
4848       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4849       .type = ARM_CP_NO_RAW, .access = PL2_W,
4850       .writefn = tlbiall_nsnh_is_write },
4851     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4852       .type = ARM_CP_NO_RAW, .access = PL2_W,
4853       .writefn = tlbiall_hyp_write },
4854     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4855       .type = ARM_CP_NO_RAW, .access = PL2_W,
4856       .writefn = tlbiall_hyp_is_write },
4857     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4858       .type = ARM_CP_NO_RAW, .access = PL2_W,
4859       .writefn = tlbimva_hyp_write },
4860     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4861       .type = ARM_CP_NO_RAW, .access = PL2_W,
4862       .writefn = tlbimva_hyp_is_write },
4863     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
4864       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4865       .type = ARM_CP_NO_RAW, .access = PL2_W,
4866       .writefn = tlbi_aa64_alle2_write },
4867     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
4868       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4869       .type = ARM_CP_NO_RAW, .access = PL2_W,
4870       .writefn = tlbi_aa64_vae2_write },
4871     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
4872       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4873       .access = PL2_W, .type = ARM_CP_NO_RAW,
4874       .writefn = tlbi_aa64_vae2_write },
4875     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
4876       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4877       .access = PL2_W, .type = ARM_CP_NO_RAW,
4878       .writefn = tlbi_aa64_alle2is_write },
4879     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
4880       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4881       .type = ARM_CP_NO_RAW, .access = PL2_W,
4882       .writefn = tlbi_aa64_vae2is_write },
4883     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
4884       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4885       .access = PL2_W, .type = ARM_CP_NO_RAW,
4886       .writefn = tlbi_aa64_vae2is_write },
4887 #ifndef CONFIG_USER_ONLY
4888     /* Unlike the other EL2-related AT operations, these must
4889      * UNDEF from EL3 if EL2 is not implemented, which is why we
4890      * define them here rather than with the rest of the AT ops.
4891      */
4892     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
4893       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4894       .access = PL2_W, .accessfn = at_s1e2_access,
4895       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4896     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
4897       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4898       .access = PL2_W, .accessfn = at_s1e2_access,
4899       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4900     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
4901      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
4902      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
4903      * to behave as if SCR.NS was 1.
4904      */
4905     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4906       .access = PL2_W,
4907       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4908     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4909       .access = PL2_W,
4910       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4911     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4912       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4913       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
4914        * reset values as IMPDEF. We choose to reset to 3 to comply with
4915        * both ARMv7 and ARMv8.
4916        */
4917       .access = PL2_RW, .resetvalue = 3,
4918       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
4919     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4920       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4921       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
4922       .writefn = gt_cntvoff_write,
4923       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4924     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4925       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
4926       .writefn = gt_cntvoff_write,
4927       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4928     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4929       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4930       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4931       .type = ARM_CP_IO, .access = PL2_RW,
4932       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4933     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4934       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4935       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
4936       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4937     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4938       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4939       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
4940       .resetfn = gt_hyp_timer_reset,
4941       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
4942     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4943       .type = ARM_CP_IO,
4944       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4945       .access = PL2_RW,
4946       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
4947       .resetvalue = 0,
4948       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
4949 #endif
4950     /* The only field of MDCR_EL2 that has a defined architectural reset value
4951      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
4952      * don't implement any PMU event counters, so using zero as a reset
4953      * value for MDCR_EL2 is okay
4954      */
4955     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4956       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4957       .access = PL2_RW, .resetvalue = 0,
4958       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
4959     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
4960       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4961       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4962       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4963     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
4964       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4965       .access = PL2_RW,
4966       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4967     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4968       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4969       .access = PL2_RW,
4970       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
4971     REGINFO_SENTINEL
4972 };
4973 
4974 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
4975     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4976       .type = ARM_CP_ALIAS | ARM_CP_IO,
4977       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4978       .access = PL2_RW,
4979       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
4980       .writefn = hcr_writehigh },
4981     REGINFO_SENTINEL
4982 };
4983 
4984 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
4985                                    bool isread)
4986 {
4987     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
4988      * At Secure EL1 it traps to EL3.
4989      */
4990     if (arm_current_el(env) == 3) {
4991         return CP_ACCESS_OK;
4992     }
4993     if (arm_is_secure_below_el3(env)) {
4994         return CP_ACCESS_TRAP_EL3;
4995     }
4996     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
4997     if (isread) {
4998         return CP_ACCESS_OK;
4999     }
5000     return CP_ACCESS_TRAP_UNCATEGORIZED;
5001 }
5002 
5003 static const ARMCPRegInfo el3_cp_reginfo[] = {
5004     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5005       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5006       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5007       .resetvalue = 0, .writefn = scr_write },
5008     { .name = "SCR",  .type = ARM_CP_ALIAS,
5009       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5010       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5011       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5012       .writefn = scr_write },
5013     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5014       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5015       .access = PL3_RW, .resetvalue = 0,
5016       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5017     { .name = "SDER",
5018       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5019       .access = PL3_RW, .resetvalue = 0,
5020       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5021     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5022       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5023       .writefn = vbar_write, .resetvalue = 0,
5024       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5025     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5026       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5027       .access = PL3_RW, .resetvalue = 0,
5028       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5029     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5030       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5031       .access = PL3_RW,
5032       /* no .writefn needed as this can't cause an ASID change;
5033        * we must provide a .raw_writefn and .resetfn because we handle
5034        * reset and migration for the AArch32 TTBCR(S), which might be
5035        * using mask and base_mask.
5036        */
5037       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5038       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5039     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5040       .type = ARM_CP_ALIAS,
5041       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5042       .access = PL3_RW,
5043       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5044     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5045       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5046       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5047     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5048       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5049       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5050     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5051       .type = ARM_CP_ALIAS,
5052       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5053       .access = PL3_RW,
5054       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5055     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5056       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5057       .access = PL3_RW, .writefn = vbar_write,
5058       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5059       .resetvalue = 0 },
5060     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5061       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5062       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5063       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5064     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5065       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5066       .access = PL3_RW, .resetvalue = 0,
5067       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5068     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5069       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5070       .access = PL3_RW, .type = ARM_CP_CONST,
5071       .resetvalue = 0 },
5072     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5073       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5074       .access = PL3_RW, .type = ARM_CP_CONST,
5075       .resetvalue = 0 },
5076     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5077       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5078       .access = PL3_RW, .type = ARM_CP_CONST,
5079       .resetvalue = 0 },
5080     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5081       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5082       .access = PL3_W, .type = ARM_CP_NO_RAW,
5083       .writefn = tlbi_aa64_alle3is_write },
5084     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5085       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5086       .access = PL3_W, .type = ARM_CP_NO_RAW,
5087       .writefn = tlbi_aa64_vae3is_write },
5088     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5089       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5090       .access = PL3_W, .type = ARM_CP_NO_RAW,
5091       .writefn = tlbi_aa64_vae3is_write },
5092     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5093       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5094       .access = PL3_W, .type = ARM_CP_NO_RAW,
5095       .writefn = tlbi_aa64_alle3_write },
5096     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5097       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5098       .access = PL3_W, .type = ARM_CP_NO_RAW,
5099       .writefn = tlbi_aa64_vae3_write },
5100     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5101       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5102       .access = PL3_W, .type = ARM_CP_NO_RAW,
5103       .writefn = tlbi_aa64_vae3_write },
5104     REGINFO_SENTINEL
5105 };
5106 
5107 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5108                                      bool isread)
5109 {
5110     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
5111      * but the AArch32 CTR has its own reginfo struct)
5112      */
5113     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5114         return CP_ACCESS_TRAP;
5115     }
5116     return CP_ACCESS_OK;
5117 }
5118 
5119 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5120                         uint64_t value)
5121 {
5122     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5123      * read via a bit in OSLSR_EL1.
5124      */
5125     int oslock;
5126 
5127     if (ri->state == ARM_CP_STATE_AA32) {
5128         oslock = (value == 0xC5ACCE55);
5129     } else {
5130         oslock = value & 1;
5131     }
5132 
5133     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5134 }
5135 
5136 static const ARMCPRegInfo debug_cp_reginfo[] = {
5137     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5138      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5139      * unlike DBGDRAR it is never accessible from EL0.
5140      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5141      * accessor.
5142      */
5143     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5144       .access = PL0_R, .accessfn = access_tdra,
5145       .type = ARM_CP_CONST, .resetvalue = 0 },
5146     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5147       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5148       .access = PL1_R, .accessfn = access_tdra,
5149       .type = ARM_CP_CONST, .resetvalue = 0 },
5150     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5151       .access = PL0_R, .accessfn = access_tdra,
5152       .type = ARM_CP_CONST, .resetvalue = 0 },
5153     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5154     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5155       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5156       .access = PL1_RW, .accessfn = access_tda,
5157       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5158       .resetvalue = 0 },
5159     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
5160      * We don't implement the configurable EL0 access.
5161      */
5162     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
5163       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5164       .type = ARM_CP_ALIAS,
5165       .access = PL1_R, .accessfn = access_tda,
5166       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
5167     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
5168       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
5169       .access = PL1_W, .type = ARM_CP_NO_RAW,
5170       .accessfn = access_tdosa,
5171       .writefn = oslar_write },
5172     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
5173       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
5174       .access = PL1_R, .resetvalue = 10,
5175       .accessfn = access_tdosa,
5176       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
5177     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
5178     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
5179       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
5180       .access = PL1_RW, .accessfn = access_tdosa,
5181       .type = ARM_CP_NOP },
5182     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
5183      * implement vector catch debug events yet.
5184      */
5185     { .name = "DBGVCR",
5186       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5187       .access = PL1_RW, .accessfn = access_tda,
5188       .type = ARM_CP_NOP },
5189     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
5190      * to save and restore a 32-bit guest's DBGVCR)
5191      */
5192     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
5193       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
5194       .access = PL2_RW, .accessfn = access_tda,
5195       .type = ARM_CP_NOP },
5196     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
5197      * Channel but Linux may try to access this register. The 32-bit
5198      * alias is DBGDCCINT.
5199      */
5200     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
5201       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5202       .access = PL1_RW, .accessfn = access_tda,
5203       .type = ARM_CP_NOP },
5204     REGINFO_SENTINEL
5205 };
5206 
5207 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
5208     /* 64 bit access versions of the (dummy) debug registers */
5209     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
5210       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5211     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
5212       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5213     REGINFO_SENTINEL
5214 };
5215 
5216 /* Return the exception level to which exceptions should be taken
5217  * via SVEAccessTrap.  If an exception should be routed through
5218  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
5219  * take care of raising that exception.
5220  * C.f. the ARM pseudocode function CheckSVEEnabled.
5221  */
5222 int sve_exception_el(CPUARMState *env, int el)
5223 {
5224 #ifndef CONFIG_USER_ONLY
5225     if (el <= 1) {
5226         bool disabled = false;
5227 
5228         /* The CPACR.ZEN controls traps to EL1:
5229          * 0, 2 : trap EL0 and EL1 accesses
5230          * 1    : trap only EL0 accesses
5231          * 3    : trap no accesses
5232          */
5233         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
5234             disabled = true;
5235         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
5236             disabled = el == 0;
5237         }
5238         if (disabled) {
5239             /* route_to_el2 */
5240             return (arm_feature(env, ARM_FEATURE_EL2)
5241                     && (arm_hcr_el2_eff(env) & HCR_TGE) ? 2 : 1);
5242         }
5243 
5244         /* Check CPACR.FPEN.  */
5245         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
5246             disabled = true;
5247         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
5248             disabled = el == 0;
5249         }
5250         if (disabled) {
5251             return 0;
5252         }
5253     }
5254 
5255     /* CPTR_EL2.  Since TZ and TFP are positive,
5256      * they will be zero when EL2 is not present.
5257      */
5258     if (el <= 2 && !arm_is_secure_below_el3(env)) {
5259         if (env->cp15.cptr_el[2] & CPTR_TZ) {
5260             return 2;
5261         }
5262         if (env->cp15.cptr_el[2] & CPTR_TFP) {
5263             return 0;
5264         }
5265     }
5266 
5267     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
5268     if (arm_feature(env, ARM_FEATURE_EL3)
5269         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
5270         return 3;
5271     }
5272 #endif
5273     return 0;
5274 }
5275 
5276 /*
5277  * Given that SVE is enabled, return the vector length for EL.
5278  */
5279 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
5280 {
5281     ARMCPU *cpu = env_archcpu(env);
5282     uint32_t zcr_len = cpu->sve_max_vq - 1;
5283 
5284     if (el <= 1) {
5285         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
5286     }
5287     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
5288         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
5289     }
5290     if (arm_feature(env, ARM_FEATURE_EL3)) {
5291         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
5292     }
5293     return zcr_len;
5294 }
5295 
5296 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5297                       uint64_t value)
5298 {
5299     int cur_el = arm_current_el(env);
5300     int old_len = sve_zcr_len_for_el(env, cur_el);
5301     int new_len;
5302 
5303     /* Bits other than [3:0] are RAZ/WI.  */
5304     raw_write(env, ri, value & 0xf);
5305 
5306     /*
5307      * Because we arrived here, we know both FP and SVE are enabled;
5308      * otherwise we would have trapped access to the ZCR_ELn register.
5309      */
5310     new_len = sve_zcr_len_for_el(env, cur_el);
5311     if (new_len < old_len) {
5312         aarch64_sve_narrow_vq(env, new_len + 1);
5313     }
5314 }
5315 
5316 static const ARMCPRegInfo zcr_el1_reginfo = {
5317     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
5318     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
5319     .access = PL1_RW, .type = ARM_CP_SVE,
5320     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
5321     .writefn = zcr_write, .raw_writefn = raw_write
5322 };
5323 
5324 static const ARMCPRegInfo zcr_el2_reginfo = {
5325     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5326     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5327     .access = PL2_RW, .type = ARM_CP_SVE,
5328     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
5329     .writefn = zcr_write, .raw_writefn = raw_write
5330 };
5331 
5332 static const ARMCPRegInfo zcr_no_el2_reginfo = {
5333     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5334     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5335     .access = PL2_RW, .type = ARM_CP_SVE,
5336     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
5337 };
5338 
5339 static const ARMCPRegInfo zcr_el3_reginfo = {
5340     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
5341     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
5342     .access = PL3_RW, .type = ARM_CP_SVE,
5343     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
5344     .writefn = zcr_write, .raw_writefn = raw_write
5345 };
5346 
5347 void hw_watchpoint_update(ARMCPU *cpu, int n)
5348 {
5349     CPUARMState *env = &cpu->env;
5350     vaddr len = 0;
5351     vaddr wvr = env->cp15.dbgwvr[n];
5352     uint64_t wcr = env->cp15.dbgwcr[n];
5353     int mask;
5354     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
5355 
5356     if (env->cpu_watchpoint[n]) {
5357         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
5358         env->cpu_watchpoint[n] = NULL;
5359     }
5360 
5361     if (!extract64(wcr, 0, 1)) {
5362         /* E bit clear : watchpoint disabled */
5363         return;
5364     }
5365 
5366     switch (extract64(wcr, 3, 2)) {
5367     case 0:
5368         /* LSC 00 is reserved and must behave as if the wp is disabled */
5369         return;
5370     case 1:
5371         flags |= BP_MEM_READ;
5372         break;
5373     case 2:
5374         flags |= BP_MEM_WRITE;
5375         break;
5376     case 3:
5377         flags |= BP_MEM_ACCESS;
5378         break;
5379     }
5380 
5381     /* Attempts to use both MASK and BAS fields simultaneously are
5382      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
5383      * thus generating a watchpoint for every byte in the masked region.
5384      */
5385     mask = extract64(wcr, 24, 4);
5386     if (mask == 1 || mask == 2) {
5387         /* Reserved values of MASK; we must act as if the mask value was
5388          * some non-reserved value, or as if the watchpoint were disabled.
5389          * We choose the latter.
5390          */
5391         return;
5392     } else if (mask) {
5393         /* Watchpoint covers an aligned area up to 2GB in size */
5394         len = 1ULL << mask;
5395         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
5396          * whether the watchpoint fires when the unmasked bits match; we opt
5397          * to generate the exceptions.
5398          */
5399         wvr &= ~(len - 1);
5400     } else {
5401         /* Watchpoint covers bytes defined by the byte address select bits */
5402         int bas = extract64(wcr, 5, 8);
5403         int basstart;
5404 
5405         if (bas == 0) {
5406             /* This must act as if the watchpoint is disabled */
5407             return;
5408         }
5409 
5410         if (extract64(wvr, 2, 1)) {
5411             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
5412              * ignored, and BAS[3:0] define which bytes to watch.
5413              */
5414             bas &= 0xf;
5415         }
5416         /* The BAS bits are supposed to be programmed to indicate a contiguous
5417          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
5418          * we fire for each byte in the word/doubleword addressed by the WVR.
5419          * We choose to ignore any non-zero bits after the first range of 1s.
5420          */
5421         basstart = ctz32(bas);
5422         len = cto32(bas >> basstart);
5423         wvr += basstart;
5424     }
5425 
5426     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
5427                           &env->cpu_watchpoint[n]);
5428 }
5429 
5430 void hw_watchpoint_update_all(ARMCPU *cpu)
5431 {
5432     int i;
5433     CPUARMState *env = &cpu->env;
5434 
5435     /* Completely clear out existing QEMU watchpoints and our array, to
5436      * avoid possible stale entries following migration load.
5437      */
5438     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
5439     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
5440 
5441     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
5442         hw_watchpoint_update(cpu, i);
5443     }
5444 }
5445 
5446 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5447                          uint64_t value)
5448 {
5449     ARMCPU *cpu = env_archcpu(env);
5450     int i = ri->crm;
5451 
5452     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
5453      * register reads and behaves as if values written are sign extended.
5454      * Bits [1:0] are RES0.
5455      */
5456     value = sextract64(value, 0, 49) & ~3ULL;
5457 
5458     raw_write(env, ri, value);
5459     hw_watchpoint_update(cpu, i);
5460 }
5461 
5462 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5463                          uint64_t value)
5464 {
5465     ARMCPU *cpu = env_archcpu(env);
5466     int i = ri->crm;
5467 
5468     raw_write(env, ri, value);
5469     hw_watchpoint_update(cpu, i);
5470 }
5471 
5472 void hw_breakpoint_update(ARMCPU *cpu, int n)
5473 {
5474     CPUARMState *env = &cpu->env;
5475     uint64_t bvr = env->cp15.dbgbvr[n];
5476     uint64_t bcr = env->cp15.dbgbcr[n];
5477     vaddr addr;
5478     int bt;
5479     int flags = BP_CPU;
5480 
5481     if (env->cpu_breakpoint[n]) {
5482         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
5483         env->cpu_breakpoint[n] = NULL;
5484     }
5485 
5486     if (!extract64(bcr, 0, 1)) {
5487         /* E bit clear : watchpoint disabled */
5488         return;
5489     }
5490 
5491     bt = extract64(bcr, 20, 4);
5492 
5493     switch (bt) {
5494     case 4: /* unlinked address mismatch (reserved if AArch64) */
5495     case 5: /* linked address mismatch (reserved if AArch64) */
5496         qemu_log_mask(LOG_UNIMP,
5497                       "arm: address mismatch breakpoint types not implemented\n");
5498         return;
5499     case 0: /* unlinked address match */
5500     case 1: /* linked address match */
5501     {
5502         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
5503          * we behave as if the register was sign extended. Bits [1:0] are
5504          * RES0. The BAS field is used to allow setting breakpoints on 16
5505          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
5506          * a bp will fire if the addresses covered by the bp and the addresses
5507          * covered by the insn overlap but the insn doesn't start at the
5508          * start of the bp address range. We choose to require the insn and
5509          * the bp to have the same address. The constraints on writing to
5510          * BAS enforced in dbgbcr_write mean we have only four cases:
5511          *  0b0000  => no breakpoint
5512          *  0b0011  => breakpoint on addr
5513          *  0b1100  => breakpoint on addr + 2
5514          *  0b1111  => breakpoint on addr
5515          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
5516          */
5517         int bas = extract64(bcr, 5, 4);
5518         addr = sextract64(bvr, 0, 49) & ~3ULL;
5519         if (bas == 0) {
5520             return;
5521         }
5522         if (bas == 0xc) {
5523             addr += 2;
5524         }
5525         break;
5526     }
5527     case 2: /* unlinked context ID match */
5528     case 8: /* unlinked VMID match (reserved if no EL2) */
5529     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
5530         qemu_log_mask(LOG_UNIMP,
5531                       "arm: unlinked context breakpoint types not implemented\n");
5532         return;
5533     case 9: /* linked VMID match (reserved if no EL2) */
5534     case 11: /* linked context ID and VMID match (reserved if no EL2) */
5535     case 3: /* linked context ID match */
5536     default:
5537         /* We must generate no events for Linked context matches (unless
5538          * they are linked to by some other bp/wp, which is handled in
5539          * updates for the linking bp/wp). We choose to also generate no events
5540          * for reserved values.
5541          */
5542         return;
5543     }
5544 
5545     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
5546 }
5547 
5548 void hw_breakpoint_update_all(ARMCPU *cpu)
5549 {
5550     int i;
5551     CPUARMState *env = &cpu->env;
5552 
5553     /* Completely clear out existing QEMU breakpoints and our array, to
5554      * avoid possible stale entries following migration load.
5555      */
5556     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
5557     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
5558 
5559     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
5560         hw_breakpoint_update(cpu, i);
5561     }
5562 }
5563 
5564 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5565                          uint64_t value)
5566 {
5567     ARMCPU *cpu = env_archcpu(env);
5568     int i = ri->crm;
5569 
5570     raw_write(env, ri, value);
5571     hw_breakpoint_update(cpu, i);
5572 }
5573 
5574 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5575                          uint64_t value)
5576 {
5577     ARMCPU *cpu = env_archcpu(env);
5578     int i = ri->crm;
5579 
5580     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
5581      * copy of BAS[0].
5582      */
5583     value = deposit64(value, 6, 1, extract64(value, 5, 1));
5584     value = deposit64(value, 8, 1, extract64(value, 7, 1));
5585 
5586     raw_write(env, ri, value);
5587     hw_breakpoint_update(cpu, i);
5588 }
5589 
5590 static void define_debug_regs(ARMCPU *cpu)
5591 {
5592     /* Define v7 and v8 architectural debug registers.
5593      * These are just dummy implementations for now.
5594      */
5595     int i;
5596     int wrps, brps, ctx_cmps;
5597     ARMCPRegInfo dbgdidr = {
5598         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
5599         .access = PL0_R, .accessfn = access_tda,
5600         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
5601     };
5602 
5603     /* Note that all these register fields hold "number of Xs minus 1". */
5604     brps = extract32(cpu->dbgdidr, 24, 4);
5605     wrps = extract32(cpu->dbgdidr, 28, 4);
5606     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
5607 
5608     assert(ctx_cmps <= brps);
5609 
5610     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
5611      * of the debug registers such as number of breakpoints;
5612      * check that if they both exist then they agree.
5613      */
5614     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
5615         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
5616         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
5617         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
5618     }
5619 
5620     define_one_arm_cp_reg(cpu, &dbgdidr);
5621     define_arm_cp_regs(cpu, debug_cp_reginfo);
5622 
5623     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
5624         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
5625     }
5626 
5627     for (i = 0; i < brps + 1; i++) {
5628         ARMCPRegInfo dbgregs[] = {
5629             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
5630               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
5631               .access = PL1_RW, .accessfn = access_tda,
5632               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
5633               .writefn = dbgbvr_write, .raw_writefn = raw_write
5634             },
5635             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
5636               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
5637               .access = PL1_RW, .accessfn = access_tda,
5638               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
5639               .writefn = dbgbcr_write, .raw_writefn = raw_write
5640             },
5641             REGINFO_SENTINEL
5642         };
5643         define_arm_cp_regs(cpu, dbgregs);
5644     }
5645 
5646     for (i = 0; i < wrps + 1; i++) {
5647         ARMCPRegInfo dbgregs[] = {
5648             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
5649               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
5650               .access = PL1_RW, .accessfn = access_tda,
5651               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
5652               .writefn = dbgwvr_write, .raw_writefn = raw_write
5653             },
5654             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
5655               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
5656               .access = PL1_RW, .accessfn = access_tda,
5657               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
5658               .writefn = dbgwcr_write, .raw_writefn = raw_write
5659             },
5660             REGINFO_SENTINEL
5661         };
5662         define_arm_cp_regs(cpu, dbgregs);
5663     }
5664 }
5665 
5666 /* We don't know until after realize whether there's a GICv3
5667  * attached, and that is what registers the gicv3 sysregs.
5668  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
5669  * at runtime.
5670  */
5671 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
5672 {
5673     ARMCPU *cpu = env_archcpu(env);
5674     uint64_t pfr1 = cpu->id_pfr1;
5675 
5676     if (env->gicv3state) {
5677         pfr1 |= 1 << 28;
5678     }
5679     return pfr1;
5680 }
5681 
5682 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
5683 {
5684     ARMCPU *cpu = env_archcpu(env);
5685     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
5686 
5687     if (env->gicv3state) {
5688         pfr0 |= 1 << 24;
5689     }
5690     return pfr0;
5691 }
5692 
5693 /* Shared logic between LORID and the rest of the LOR* registers.
5694  * Secure state has already been delt with.
5695  */
5696 static CPAccessResult access_lor_ns(CPUARMState *env)
5697 {
5698     int el = arm_current_el(env);
5699 
5700     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
5701         return CP_ACCESS_TRAP_EL2;
5702     }
5703     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
5704         return CP_ACCESS_TRAP_EL3;
5705     }
5706     return CP_ACCESS_OK;
5707 }
5708 
5709 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
5710                                    bool isread)
5711 {
5712     if (arm_is_secure_below_el3(env)) {
5713         /* Access ok in secure mode.  */
5714         return CP_ACCESS_OK;
5715     }
5716     return access_lor_ns(env);
5717 }
5718 
5719 static CPAccessResult access_lor_other(CPUARMState *env,
5720                                        const ARMCPRegInfo *ri, bool isread)
5721 {
5722     if (arm_is_secure_below_el3(env)) {
5723         /* Access denied in secure mode.  */
5724         return CP_ACCESS_TRAP;
5725     }
5726     return access_lor_ns(env);
5727 }
5728 
5729 #ifdef TARGET_AARCH64
5730 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
5731                                    bool isread)
5732 {
5733     int el = arm_current_el(env);
5734 
5735     if (el < 2 &&
5736         arm_feature(env, ARM_FEATURE_EL2) &&
5737         !(arm_hcr_el2_eff(env) & HCR_APK)) {
5738         return CP_ACCESS_TRAP_EL2;
5739     }
5740     if (el < 3 &&
5741         arm_feature(env, ARM_FEATURE_EL3) &&
5742         !(env->cp15.scr_el3 & SCR_APK)) {
5743         return CP_ACCESS_TRAP_EL3;
5744     }
5745     return CP_ACCESS_OK;
5746 }
5747 
5748 static const ARMCPRegInfo pauth_reginfo[] = {
5749     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5750       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
5751       .access = PL1_RW, .accessfn = access_pauth,
5752       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
5753     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5754       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
5755       .access = PL1_RW, .accessfn = access_pauth,
5756       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
5757     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5758       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
5759       .access = PL1_RW, .accessfn = access_pauth,
5760       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
5761     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5762       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
5763       .access = PL1_RW, .accessfn = access_pauth,
5764       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
5765     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5766       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
5767       .access = PL1_RW, .accessfn = access_pauth,
5768       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
5769     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5770       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
5771       .access = PL1_RW, .accessfn = access_pauth,
5772       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
5773     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5774       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
5775       .access = PL1_RW, .accessfn = access_pauth,
5776       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
5777     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5778       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
5779       .access = PL1_RW, .accessfn = access_pauth,
5780       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
5781     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5782       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
5783       .access = PL1_RW, .accessfn = access_pauth,
5784       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
5785     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5786       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
5787       .access = PL1_RW, .accessfn = access_pauth,
5788       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
5789     REGINFO_SENTINEL
5790 };
5791 
5792 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
5793 {
5794     Error *err = NULL;
5795     uint64_t ret;
5796 
5797     /* Success sets NZCV = 0000.  */
5798     env->NF = env->CF = env->VF = 0, env->ZF = 1;
5799 
5800     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
5801         /*
5802          * ??? Failed, for unknown reasons in the crypto subsystem.
5803          * The best we can do is log the reason and return the
5804          * timed-out indication to the guest.  There is no reason
5805          * we know to expect this failure to be transitory, so the
5806          * guest may well hang retrying the operation.
5807          */
5808         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
5809                       ri->name, error_get_pretty(err));
5810         error_free(err);
5811 
5812         env->ZF = 0; /* NZCF = 0100 */
5813         return 0;
5814     }
5815     return ret;
5816 }
5817 
5818 /* We do not support re-seeding, so the two registers operate the same.  */
5819 static const ARMCPRegInfo rndr_reginfo[] = {
5820     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
5821       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5822       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
5823       .access = PL0_R, .readfn = rndr_readfn },
5824     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
5825       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5826       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
5827       .access = PL0_R, .readfn = rndr_readfn },
5828     REGINFO_SENTINEL
5829 };
5830 #endif
5831 
5832 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
5833                                      bool isread)
5834 {
5835     int el = arm_current_el(env);
5836 
5837     if (el == 0) {
5838         uint64_t sctlr = arm_sctlr(env, el);
5839         if (!(sctlr & SCTLR_EnRCTX)) {
5840             return CP_ACCESS_TRAP;
5841         }
5842     } else if (el == 1) {
5843         uint64_t hcr = arm_hcr_el2_eff(env);
5844         if (hcr & HCR_NV) {
5845             return CP_ACCESS_TRAP_EL2;
5846         }
5847     }
5848     return CP_ACCESS_OK;
5849 }
5850 
5851 static const ARMCPRegInfo predinv_reginfo[] = {
5852     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
5853       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
5854       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5855     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
5856       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
5857       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5858     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
5859       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
5860       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5861     /*
5862      * Note the AArch32 opcodes have a different OPC1.
5863      */
5864     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
5865       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
5866       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5867     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
5868       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
5869       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5870     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
5871       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
5872       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5873     REGINFO_SENTINEL
5874 };
5875 
5876 void register_cp_regs_for_features(ARMCPU *cpu)
5877 {
5878     /* Register all the coprocessor registers based on feature bits */
5879     CPUARMState *env = &cpu->env;
5880     if (arm_feature(env, ARM_FEATURE_M)) {
5881         /* M profile has no coprocessor registers */
5882         return;
5883     }
5884 
5885     define_arm_cp_regs(cpu, cp_reginfo);
5886     if (!arm_feature(env, ARM_FEATURE_V8)) {
5887         /* Must go early as it is full of wildcards that may be
5888          * overridden by later definitions.
5889          */
5890         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
5891     }
5892 
5893     if (arm_feature(env, ARM_FEATURE_V6)) {
5894         /* The ID registers all have impdef reset values */
5895         ARMCPRegInfo v6_idregs[] = {
5896             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
5897               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5898               .access = PL1_R, .type = ARM_CP_CONST,
5899               .resetvalue = cpu->id_pfr0 },
5900             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
5901              * the value of the GIC field until after we define these regs.
5902              */
5903             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
5904               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
5905               .access = PL1_R, .type = ARM_CP_NO_RAW,
5906               .readfn = id_pfr1_read,
5907               .writefn = arm_cp_write_ignore },
5908             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
5909               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
5910               .access = PL1_R, .type = ARM_CP_CONST,
5911               .resetvalue = cpu->id_dfr0 },
5912             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
5913               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
5914               .access = PL1_R, .type = ARM_CP_CONST,
5915               .resetvalue = cpu->id_afr0 },
5916             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
5917               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
5918               .access = PL1_R, .type = ARM_CP_CONST,
5919               .resetvalue = cpu->id_mmfr0 },
5920             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
5921               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
5922               .access = PL1_R, .type = ARM_CP_CONST,
5923               .resetvalue = cpu->id_mmfr1 },
5924             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
5925               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
5926               .access = PL1_R, .type = ARM_CP_CONST,
5927               .resetvalue = cpu->id_mmfr2 },
5928             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
5929               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
5930               .access = PL1_R, .type = ARM_CP_CONST,
5931               .resetvalue = cpu->id_mmfr3 },
5932             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
5933               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5934               .access = PL1_R, .type = ARM_CP_CONST,
5935               .resetvalue = cpu->isar.id_isar0 },
5936             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
5937               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
5938               .access = PL1_R, .type = ARM_CP_CONST,
5939               .resetvalue = cpu->isar.id_isar1 },
5940             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
5941               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5942               .access = PL1_R, .type = ARM_CP_CONST,
5943               .resetvalue = cpu->isar.id_isar2 },
5944             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
5945               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
5946               .access = PL1_R, .type = ARM_CP_CONST,
5947               .resetvalue = cpu->isar.id_isar3 },
5948             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
5949               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
5950               .access = PL1_R, .type = ARM_CP_CONST,
5951               .resetvalue = cpu->isar.id_isar4 },
5952             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
5953               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
5954               .access = PL1_R, .type = ARM_CP_CONST,
5955               .resetvalue = cpu->isar.id_isar5 },
5956             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
5957               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
5958               .access = PL1_R, .type = ARM_CP_CONST,
5959               .resetvalue = cpu->id_mmfr4 },
5960             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
5961               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
5962               .access = PL1_R, .type = ARM_CP_CONST,
5963               .resetvalue = cpu->isar.id_isar6 },
5964             REGINFO_SENTINEL
5965         };
5966         define_arm_cp_regs(cpu, v6_idregs);
5967         define_arm_cp_regs(cpu, v6_cp_reginfo);
5968     } else {
5969         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
5970     }
5971     if (arm_feature(env, ARM_FEATURE_V6K)) {
5972         define_arm_cp_regs(cpu, v6k_cp_reginfo);
5973     }
5974     if (arm_feature(env, ARM_FEATURE_V7MP) &&
5975         !arm_feature(env, ARM_FEATURE_PMSA)) {
5976         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
5977     }
5978     if (arm_feature(env, ARM_FEATURE_V7VE)) {
5979         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
5980     }
5981     if (arm_feature(env, ARM_FEATURE_V7)) {
5982         /* v7 performance monitor control register: same implementor
5983          * field as main ID register, and we implement four counters in
5984          * addition to the cycle count register.
5985          */
5986         unsigned int i, pmcrn = 4;
5987         ARMCPRegInfo pmcr = {
5988             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
5989             .access = PL0_RW,
5990             .type = ARM_CP_IO | ARM_CP_ALIAS,
5991             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
5992             .accessfn = pmreg_access, .writefn = pmcr_write,
5993             .raw_writefn = raw_write,
5994         };
5995         ARMCPRegInfo pmcr64 = {
5996             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
5997             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
5998             .access = PL0_RW, .accessfn = pmreg_access,
5999             .type = ARM_CP_IO,
6000             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6001             .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT),
6002             .writefn = pmcr_write, .raw_writefn = raw_write,
6003         };
6004         define_one_arm_cp_reg(cpu, &pmcr);
6005         define_one_arm_cp_reg(cpu, &pmcr64);
6006         for (i = 0; i < pmcrn; i++) {
6007             char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6008             char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6009             char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6010             char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6011             ARMCPRegInfo pmev_regs[] = {
6012                 { .name = pmevcntr_name, .cp = 15, .crn = 14,
6013                   .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6014                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6015                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6016                   .accessfn = pmreg_access },
6017                 { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6018                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6019                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6020                   .type = ARM_CP_IO,
6021                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6022                   .raw_readfn = pmevcntr_rawread,
6023                   .raw_writefn = pmevcntr_rawwrite },
6024                 { .name = pmevtyper_name, .cp = 15, .crn = 14,
6025                   .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6026                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6027                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6028                   .accessfn = pmreg_access },
6029                 { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6030                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6031                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6032                   .type = ARM_CP_IO,
6033                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6034                   .raw_writefn = pmevtyper_rawwrite },
6035                 REGINFO_SENTINEL
6036             };
6037             define_arm_cp_regs(cpu, pmev_regs);
6038             g_free(pmevcntr_name);
6039             g_free(pmevcntr_el0_name);
6040             g_free(pmevtyper_name);
6041             g_free(pmevtyper_el0_name);
6042         }
6043         ARMCPRegInfo clidr = {
6044             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
6045             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
6046             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
6047         };
6048         define_one_arm_cp_reg(cpu, &clidr);
6049         define_arm_cp_regs(cpu, v7_cp_reginfo);
6050         define_debug_regs(cpu);
6051     } else {
6052         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
6053     }
6054     if (FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) >= 4 &&
6055             FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) != 0xf) {
6056         ARMCPRegInfo v81_pmu_regs[] = {
6057             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6058               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6059               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6060               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6061             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6062               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6063               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6064               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6065             REGINFO_SENTINEL
6066         };
6067         define_arm_cp_regs(cpu, v81_pmu_regs);
6068     }
6069     if (arm_feature(env, ARM_FEATURE_V8)) {
6070         /* AArch64 ID registers, which all have impdef reset values.
6071          * Note that within the ID register ranges the unused slots
6072          * must all RAZ, not UNDEF; future architecture versions may
6073          * define new registers here.
6074          */
6075         ARMCPRegInfo v8_idregs[] = {
6076             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
6077              * know the right value for the GIC field until after we
6078              * define these regs.
6079              */
6080             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
6081               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
6082               .access = PL1_R, .type = ARM_CP_NO_RAW,
6083               .readfn = id_aa64pfr0_read,
6084               .writefn = arm_cp_write_ignore },
6085             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
6086               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
6087               .access = PL1_R, .type = ARM_CP_CONST,
6088               .resetvalue = cpu->isar.id_aa64pfr1},
6089             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6090               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
6091               .access = PL1_R, .type = ARM_CP_CONST,
6092               .resetvalue = 0 },
6093             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6094               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
6095               .access = PL1_R, .type = ARM_CP_CONST,
6096               .resetvalue = 0 },
6097             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
6098               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
6099               .access = PL1_R, .type = ARM_CP_CONST,
6100               /* At present, only SVEver == 0 is defined anyway.  */
6101               .resetvalue = 0 },
6102             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6103               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
6104               .access = PL1_R, .type = ARM_CP_CONST,
6105               .resetvalue = 0 },
6106             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6107               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
6108               .access = PL1_R, .type = ARM_CP_CONST,
6109               .resetvalue = 0 },
6110             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6111               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
6112               .access = PL1_R, .type = ARM_CP_CONST,
6113               .resetvalue = 0 },
6114             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
6115               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
6116               .access = PL1_R, .type = ARM_CP_CONST,
6117               .resetvalue = cpu->id_aa64dfr0 },
6118             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
6119               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
6120               .access = PL1_R, .type = ARM_CP_CONST,
6121               .resetvalue = cpu->id_aa64dfr1 },
6122             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6123               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
6124               .access = PL1_R, .type = ARM_CP_CONST,
6125               .resetvalue = 0 },
6126             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6127               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
6128               .access = PL1_R, .type = ARM_CP_CONST,
6129               .resetvalue = 0 },
6130             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
6131               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
6132               .access = PL1_R, .type = ARM_CP_CONST,
6133               .resetvalue = cpu->id_aa64afr0 },
6134             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
6135               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
6136               .access = PL1_R, .type = ARM_CP_CONST,
6137               .resetvalue = cpu->id_aa64afr1 },
6138             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6139               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
6140               .access = PL1_R, .type = ARM_CP_CONST,
6141               .resetvalue = 0 },
6142             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6143               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
6144               .access = PL1_R, .type = ARM_CP_CONST,
6145               .resetvalue = 0 },
6146             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
6147               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
6148               .access = PL1_R, .type = ARM_CP_CONST,
6149               .resetvalue = cpu->isar.id_aa64isar0 },
6150             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
6151               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
6152               .access = PL1_R, .type = ARM_CP_CONST,
6153               .resetvalue = cpu->isar.id_aa64isar1 },
6154             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6155               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
6156               .access = PL1_R, .type = ARM_CP_CONST,
6157               .resetvalue = 0 },
6158             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6159               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
6160               .access = PL1_R, .type = ARM_CP_CONST,
6161               .resetvalue = 0 },
6162             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6163               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
6164               .access = PL1_R, .type = ARM_CP_CONST,
6165               .resetvalue = 0 },
6166             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6167               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
6168               .access = PL1_R, .type = ARM_CP_CONST,
6169               .resetvalue = 0 },
6170             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6171               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
6172               .access = PL1_R, .type = ARM_CP_CONST,
6173               .resetvalue = 0 },
6174             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6175               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
6176               .access = PL1_R, .type = ARM_CP_CONST,
6177               .resetvalue = 0 },
6178             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
6179               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6180               .access = PL1_R, .type = ARM_CP_CONST,
6181               .resetvalue = cpu->isar.id_aa64mmfr0 },
6182             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
6183               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
6184               .access = PL1_R, .type = ARM_CP_CONST,
6185               .resetvalue = cpu->isar.id_aa64mmfr1 },
6186             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6187               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
6188               .access = PL1_R, .type = ARM_CP_CONST,
6189               .resetvalue = 0 },
6190             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6191               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
6192               .access = PL1_R, .type = ARM_CP_CONST,
6193               .resetvalue = 0 },
6194             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6195               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
6196               .access = PL1_R, .type = ARM_CP_CONST,
6197               .resetvalue = 0 },
6198             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6199               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
6200               .access = PL1_R, .type = ARM_CP_CONST,
6201               .resetvalue = 0 },
6202             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6203               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
6204               .access = PL1_R, .type = ARM_CP_CONST,
6205               .resetvalue = 0 },
6206             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6207               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
6208               .access = PL1_R, .type = ARM_CP_CONST,
6209               .resetvalue = 0 },
6210             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
6211               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
6212               .access = PL1_R, .type = ARM_CP_CONST,
6213               .resetvalue = cpu->isar.mvfr0 },
6214             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
6215               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
6216               .access = PL1_R, .type = ARM_CP_CONST,
6217               .resetvalue = cpu->isar.mvfr1 },
6218             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
6219               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
6220               .access = PL1_R, .type = ARM_CP_CONST,
6221               .resetvalue = cpu->isar.mvfr2 },
6222             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6223               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
6224               .access = PL1_R, .type = ARM_CP_CONST,
6225               .resetvalue = 0 },
6226             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6227               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
6228               .access = PL1_R, .type = ARM_CP_CONST,
6229               .resetvalue = 0 },
6230             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6231               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
6232               .access = PL1_R, .type = ARM_CP_CONST,
6233               .resetvalue = 0 },
6234             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6235               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
6236               .access = PL1_R, .type = ARM_CP_CONST,
6237               .resetvalue = 0 },
6238             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6239               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
6240               .access = PL1_R, .type = ARM_CP_CONST,
6241               .resetvalue = 0 },
6242             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
6243               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
6244               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6245               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
6246             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
6247               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
6248               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6249               .resetvalue = cpu->pmceid0 },
6250             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
6251               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
6252               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6253               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
6254             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
6255               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
6256               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6257               .resetvalue = cpu->pmceid1 },
6258             REGINFO_SENTINEL
6259         };
6260 #ifdef CONFIG_USER_ONLY
6261         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
6262             { .name = "ID_AA64PFR0_EL1",
6263               .exported_bits = 0x000f000f00ff0000,
6264               .fixed_bits    = 0x0000000000000011 },
6265             { .name = "ID_AA64PFR1_EL1",
6266               .exported_bits = 0x00000000000000f0 },
6267             { .name = "ID_AA64PFR*_EL1_RESERVED",
6268               .is_glob = true                     },
6269             { .name = "ID_AA64ZFR0_EL1"           },
6270             { .name = "ID_AA64MMFR0_EL1",
6271               .fixed_bits    = 0x00000000ff000000 },
6272             { .name = "ID_AA64MMFR1_EL1"          },
6273             { .name = "ID_AA64MMFR*_EL1_RESERVED",
6274               .is_glob = true                     },
6275             { .name = "ID_AA64DFR0_EL1",
6276               .fixed_bits    = 0x0000000000000006 },
6277             { .name = "ID_AA64DFR1_EL1"           },
6278             { .name = "ID_AA64DFR*_EL1_RESERVED",
6279               .is_glob = true                     },
6280             { .name = "ID_AA64AFR*",
6281               .is_glob = true                     },
6282             { .name = "ID_AA64ISAR0_EL1",
6283               .exported_bits = 0x00fffffff0fffff0 },
6284             { .name = "ID_AA64ISAR1_EL1",
6285               .exported_bits = 0x000000f0ffffffff },
6286             { .name = "ID_AA64ISAR*_EL1_RESERVED",
6287               .is_glob = true                     },
6288             REGUSERINFO_SENTINEL
6289         };
6290         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
6291 #endif
6292         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
6293         if (!arm_feature(env, ARM_FEATURE_EL3) &&
6294             !arm_feature(env, ARM_FEATURE_EL2)) {
6295             ARMCPRegInfo rvbar = {
6296                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
6297                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
6298                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
6299             };
6300             define_one_arm_cp_reg(cpu, &rvbar);
6301         }
6302         define_arm_cp_regs(cpu, v8_idregs);
6303         define_arm_cp_regs(cpu, v8_cp_reginfo);
6304     }
6305     if (arm_feature(env, ARM_FEATURE_EL2)) {
6306         uint64_t vmpidr_def = mpidr_read_val(env);
6307         ARMCPRegInfo vpidr_regs[] = {
6308             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
6309               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6310               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6311               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
6312               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
6313             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
6314               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6315               .access = PL2_RW, .resetvalue = cpu->midr,
6316               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6317             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
6318               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6319               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6320               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
6321               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
6322             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
6323               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6324               .access = PL2_RW,
6325               .resetvalue = vmpidr_def,
6326               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
6327             REGINFO_SENTINEL
6328         };
6329         define_arm_cp_regs(cpu, vpidr_regs);
6330         define_arm_cp_regs(cpu, el2_cp_reginfo);
6331         if (arm_feature(env, ARM_FEATURE_V8)) {
6332             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
6333         }
6334         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
6335         if (!arm_feature(env, ARM_FEATURE_EL3)) {
6336             ARMCPRegInfo rvbar = {
6337                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
6338                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
6339                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
6340             };
6341             define_one_arm_cp_reg(cpu, &rvbar);
6342         }
6343     } else {
6344         /* If EL2 is missing but higher ELs are enabled, we need to
6345          * register the no_el2 reginfos.
6346          */
6347         if (arm_feature(env, ARM_FEATURE_EL3)) {
6348             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
6349              * of MIDR_EL1 and MPIDR_EL1.
6350              */
6351             ARMCPRegInfo vpidr_regs[] = {
6352                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6353                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6354                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6355                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
6356                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6357                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6358                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6359                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6360                   .type = ARM_CP_NO_RAW,
6361                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
6362                 REGINFO_SENTINEL
6363             };
6364             define_arm_cp_regs(cpu, vpidr_regs);
6365             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
6366             if (arm_feature(env, ARM_FEATURE_V8)) {
6367                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
6368             }
6369         }
6370     }
6371     if (arm_feature(env, ARM_FEATURE_EL3)) {
6372         define_arm_cp_regs(cpu, el3_cp_reginfo);
6373         ARMCPRegInfo el3_regs[] = {
6374             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
6375               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
6376               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
6377             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
6378               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
6379               .access = PL3_RW,
6380               .raw_writefn = raw_write, .writefn = sctlr_write,
6381               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
6382               .resetvalue = cpu->reset_sctlr },
6383             REGINFO_SENTINEL
6384         };
6385 
6386         define_arm_cp_regs(cpu, el3_regs);
6387     }
6388     /* The behaviour of NSACR is sufficiently various that we don't
6389      * try to describe it in a single reginfo:
6390      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
6391      *     reads as constant 0xc00 from NS EL1 and NS EL2
6392      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
6393      *  if v7 without EL3, register doesn't exist
6394      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
6395      */
6396     if (arm_feature(env, ARM_FEATURE_EL3)) {
6397         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6398             ARMCPRegInfo nsacr = {
6399                 .name = "NSACR", .type = ARM_CP_CONST,
6400                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6401                 .access = PL1_RW, .accessfn = nsacr_access,
6402                 .resetvalue = 0xc00
6403             };
6404             define_one_arm_cp_reg(cpu, &nsacr);
6405         } else {
6406             ARMCPRegInfo nsacr = {
6407                 .name = "NSACR",
6408                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6409                 .access = PL3_RW | PL1_R,
6410                 .resetvalue = 0,
6411                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
6412             };
6413             define_one_arm_cp_reg(cpu, &nsacr);
6414         }
6415     } else {
6416         if (arm_feature(env, ARM_FEATURE_V8)) {
6417             ARMCPRegInfo nsacr = {
6418                 .name = "NSACR", .type = ARM_CP_CONST,
6419                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6420                 .access = PL1_R,
6421                 .resetvalue = 0xc00
6422             };
6423             define_one_arm_cp_reg(cpu, &nsacr);
6424         }
6425     }
6426 
6427     if (arm_feature(env, ARM_FEATURE_PMSA)) {
6428         if (arm_feature(env, ARM_FEATURE_V6)) {
6429             /* PMSAv6 not implemented */
6430             assert(arm_feature(env, ARM_FEATURE_V7));
6431             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6432             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
6433         } else {
6434             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
6435         }
6436     } else {
6437         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6438         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
6439         /* TTCBR2 is introduced with ARMv8.2-A32HPD.  */
6440         if (FIELD_EX32(cpu->id_mmfr4, ID_MMFR4, HPDS) != 0) {
6441             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
6442         }
6443     }
6444     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
6445         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
6446     }
6447     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
6448         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
6449     }
6450     if (arm_feature(env, ARM_FEATURE_VAPA)) {
6451         define_arm_cp_regs(cpu, vapa_cp_reginfo);
6452     }
6453     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
6454         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
6455     }
6456     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
6457         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
6458     }
6459     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
6460         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
6461     }
6462     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
6463         define_arm_cp_regs(cpu, omap_cp_reginfo);
6464     }
6465     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
6466         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
6467     }
6468     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6469         define_arm_cp_regs(cpu, xscale_cp_reginfo);
6470     }
6471     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
6472         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
6473     }
6474     if (arm_feature(env, ARM_FEATURE_LPAE)) {
6475         define_arm_cp_regs(cpu, lpae_cp_reginfo);
6476     }
6477     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
6478      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
6479      * be read-only (ie write causes UNDEF exception).
6480      */
6481     {
6482         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
6483             /* Pre-v8 MIDR space.
6484              * Note that the MIDR isn't a simple constant register because
6485              * of the TI925 behaviour where writes to another register can
6486              * cause the MIDR value to change.
6487              *
6488              * Unimplemented registers in the c15 0 0 0 space default to
6489              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
6490              * and friends override accordingly.
6491              */
6492             { .name = "MIDR",
6493               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
6494               .access = PL1_R, .resetvalue = cpu->midr,
6495               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
6496               .readfn = midr_read,
6497               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6498               .type = ARM_CP_OVERRIDE },
6499             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
6500             { .name = "DUMMY",
6501               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
6502               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6503             { .name = "DUMMY",
6504               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
6505               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6506             { .name = "DUMMY",
6507               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
6508               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6509             { .name = "DUMMY",
6510               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
6511               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6512             { .name = "DUMMY",
6513               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
6514               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6515             REGINFO_SENTINEL
6516         };
6517         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
6518             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
6519               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
6520               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
6521               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6522               .readfn = midr_read },
6523             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
6524             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6525               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6526               .access = PL1_R, .resetvalue = cpu->midr },
6527             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6528               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
6529               .access = PL1_R, .resetvalue = cpu->midr },
6530             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
6531               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
6532               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
6533             REGINFO_SENTINEL
6534         };
6535         ARMCPRegInfo id_cp_reginfo[] = {
6536             /* These are common to v8 and pre-v8 */
6537             { .name = "CTR",
6538               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
6539               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6540             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
6541               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
6542               .access = PL0_R, .accessfn = ctr_el0_access,
6543               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6544             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
6545             { .name = "TCMTR",
6546               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
6547               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6548             REGINFO_SENTINEL
6549         };
6550         /* TLBTR is specific to VMSA */
6551         ARMCPRegInfo id_tlbtr_reginfo = {
6552               .name = "TLBTR",
6553               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
6554               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
6555         };
6556         /* MPUIR is specific to PMSA V6+ */
6557         ARMCPRegInfo id_mpuir_reginfo = {
6558               .name = "MPUIR",
6559               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6560               .access = PL1_R, .type = ARM_CP_CONST,
6561               .resetvalue = cpu->pmsav7_dregion << 8
6562         };
6563         ARMCPRegInfo crn0_wi_reginfo = {
6564             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
6565             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
6566             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
6567         };
6568 #ifdef CONFIG_USER_ONLY
6569         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
6570             { .name = "MIDR_EL1",
6571               .exported_bits = 0x00000000ffffffff },
6572             { .name = "REVIDR_EL1"                },
6573             REGUSERINFO_SENTINEL
6574         };
6575         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
6576 #endif
6577         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
6578             arm_feature(env, ARM_FEATURE_STRONGARM)) {
6579             ARMCPRegInfo *r;
6580             /* Register the blanket "writes ignored" value first to cover the
6581              * whole space. Then update the specific ID registers to allow write
6582              * access, so that they ignore writes rather than causing them to
6583              * UNDEF.
6584              */
6585             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
6586             for (r = id_pre_v8_midr_cp_reginfo;
6587                  r->type != ARM_CP_SENTINEL; r++) {
6588                 r->access = PL1_RW;
6589             }
6590             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
6591                 r->access = PL1_RW;
6592             }
6593             id_mpuir_reginfo.access = PL1_RW;
6594             id_tlbtr_reginfo.access = PL1_RW;
6595         }
6596         if (arm_feature(env, ARM_FEATURE_V8)) {
6597             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
6598         } else {
6599             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
6600         }
6601         define_arm_cp_regs(cpu, id_cp_reginfo);
6602         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
6603             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
6604         } else if (arm_feature(env, ARM_FEATURE_V7)) {
6605             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
6606         }
6607     }
6608 
6609     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
6610         ARMCPRegInfo mpidr_cp_reginfo[] = {
6611             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
6612               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
6613               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
6614             REGINFO_SENTINEL
6615         };
6616 #ifdef CONFIG_USER_ONLY
6617         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
6618             { .name = "MPIDR_EL1",
6619               .fixed_bits = 0x0000000080000000 },
6620             REGUSERINFO_SENTINEL
6621         };
6622         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
6623 #endif
6624         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
6625     }
6626 
6627     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
6628         ARMCPRegInfo auxcr_reginfo[] = {
6629             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
6630               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
6631               .access = PL1_RW, .type = ARM_CP_CONST,
6632               .resetvalue = cpu->reset_auxcr },
6633             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
6634               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
6635               .access = PL2_RW, .type = ARM_CP_CONST,
6636               .resetvalue = 0 },
6637             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
6638               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
6639               .access = PL3_RW, .type = ARM_CP_CONST,
6640               .resetvalue = 0 },
6641             REGINFO_SENTINEL
6642         };
6643         define_arm_cp_regs(cpu, auxcr_reginfo);
6644         if (arm_feature(env, ARM_FEATURE_V8)) {
6645             /* HACTLR2 maps to ACTLR_EL2[63:32] and is not in ARMv7 */
6646             ARMCPRegInfo hactlr2_reginfo = {
6647                 .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
6648                 .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
6649                 .access = PL2_RW, .type = ARM_CP_CONST,
6650                 .resetvalue = 0
6651             };
6652             define_one_arm_cp_reg(cpu, &hactlr2_reginfo);
6653         }
6654     }
6655 
6656     if (arm_feature(env, ARM_FEATURE_CBAR)) {
6657         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6658             /* 32 bit view is [31:18] 0...0 [43:32]. */
6659             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
6660                 | extract64(cpu->reset_cbar, 32, 12);
6661             ARMCPRegInfo cbar_reginfo[] = {
6662                 { .name = "CBAR",
6663                   .type = ARM_CP_CONST,
6664                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
6665                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
6666                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
6667                   .type = ARM_CP_CONST,
6668                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
6669                   .access = PL1_R, .resetvalue = cbar32 },
6670                 REGINFO_SENTINEL
6671             };
6672             /* We don't implement a r/w 64 bit CBAR currently */
6673             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
6674             define_arm_cp_regs(cpu, cbar_reginfo);
6675         } else {
6676             ARMCPRegInfo cbar = {
6677                 .name = "CBAR",
6678                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
6679                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
6680                 .fieldoffset = offsetof(CPUARMState,
6681                                         cp15.c15_config_base_address)
6682             };
6683             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
6684                 cbar.access = PL1_R;
6685                 cbar.fieldoffset = 0;
6686                 cbar.type = ARM_CP_CONST;
6687             }
6688             define_one_arm_cp_reg(cpu, &cbar);
6689         }
6690     }
6691 
6692     if (arm_feature(env, ARM_FEATURE_VBAR)) {
6693         ARMCPRegInfo vbar_cp_reginfo[] = {
6694             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
6695               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
6696               .access = PL1_RW, .writefn = vbar_write,
6697               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
6698                                      offsetof(CPUARMState, cp15.vbar_ns) },
6699               .resetvalue = 0 },
6700             REGINFO_SENTINEL
6701         };
6702         define_arm_cp_regs(cpu, vbar_cp_reginfo);
6703     }
6704 
6705     /* Generic registers whose values depend on the implementation */
6706     {
6707         ARMCPRegInfo sctlr = {
6708             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
6709             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6710             .access = PL1_RW,
6711             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
6712                                    offsetof(CPUARMState, cp15.sctlr_ns) },
6713             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
6714             .raw_writefn = raw_write,
6715         };
6716         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6717             /* Normally we would always end the TB on an SCTLR write, but Linux
6718              * arch/arm/mach-pxa/sleep.S expects two instructions following
6719              * an MMU enable to execute from cache.  Imitate this behaviour.
6720              */
6721             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
6722         }
6723         define_one_arm_cp_reg(cpu, &sctlr);
6724     }
6725 
6726     if (cpu_isar_feature(aa64_lor, cpu)) {
6727         /*
6728          * A trivial implementation of ARMv8.1-LOR leaves all of these
6729          * registers fixed at 0, which indicates that there are zero
6730          * supported Limited Ordering regions.
6731          */
6732         static const ARMCPRegInfo lor_reginfo[] = {
6733             { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6734               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6735               .access = PL1_RW, .accessfn = access_lor_other,
6736               .type = ARM_CP_CONST, .resetvalue = 0 },
6737             { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6738               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6739               .access = PL1_RW, .accessfn = access_lor_other,
6740               .type = ARM_CP_CONST, .resetvalue = 0 },
6741             { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6742               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6743               .access = PL1_RW, .accessfn = access_lor_other,
6744               .type = ARM_CP_CONST, .resetvalue = 0 },
6745             { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6746               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6747               .access = PL1_RW, .accessfn = access_lor_other,
6748               .type = ARM_CP_CONST, .resetvalue = 0 },
6749             { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6750               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6751               .access = PL1_R, .accessfn = access_lorid,
6752               .type = ARM_CP_CONST, .resetvalue = 0 },
6753             REGINFO_SENTINEL
6754         };
6755         define_arm_cp_regs(cpu, lor_reginfo);
6756     }
6757 
6758     if (cpu_isar_feature(aa64_sve, cpu)) {
6759         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
6760         if (arm_feature(env, ARM_FEATURE_EL2)) {
6761             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
6762         } else {
6763             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
6764         }
6765         if (arm_feature(env, ARM_FEATURE_EL3)) {
6766             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
6767         }
6768     }
6769 
6770 #ifdef TARGET_AARCH64
6771     if (cpu_isar_feature(aa64_pauth, cpu)) {
6772         define_arm_cp_regs(cpu, pauth_reginfo);
6773     }
6774     if (cpu_isar_feature(aa64_rndr, cpu)) {
6775         define_arm_cp_regs(cpu, rndr_reginfo);
6776     }
6777 #endif
6778 
6779     /*
6780      * While all v8.0 cpus support aarch64, QEMU does have configurations
6781      * that do not set ID_AA64ISAR1, e.g. user-only qemu-arm -cpu max,
6782      * which will set ID_ISAR6.
6783      */
6784     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)
6785         ? cpu_isar_feature(aa64_predinv, cpu)
6786         : cpu_isar_feature(aa32_predinv, cpu)) {
6787         define_arm_cp_regs(cpu, predinv_reginfo);
6788     }
6789 }
6790 
6791 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
6792 {
6793     CPUState *cs = CPU(cpu);
6794     CPUARMState *env = &cpu->env;
6795 
6796     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6797         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
6798                                  aarch64_fpu_gdb_set_reg,
6799                                  34, "aarch64-fpu.xml", 0);
6800     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
6801         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6802                                  51, "arm-neon.xml", 0);
6803     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
6804         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6805                                  35, "arm-vfp3.xml", 0);
6806     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
6807         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6808                                  19, "arm-vfp.xml", 0);
6809     }
6810     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
6811                              arm_gen_dynamic_xml(cs),
6812                              "system-registers.xml", 0);
6813 }
6814 
6815 /* Sort alphabetically by type name, except for "any". */
6816 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
6817 {
6818     ObjectClass *class_a = (ObjectClass *)a;
6819     ObjectClass *class_b = (ObjectClass *)b;
6820     const char *name_a, *name_b;
6821 
6822     name_a = object_class_get_name(class_a);
6823     name_b = object_class_get_name(class_b);
6824     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
6825         return 1;
6826     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
6827         return -1;
6828     } else {
6829         return strcmp(name_a, name_b);
6830     }
6831 }
6832 
6833 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
6834 {
6835     ObjectClass *oc = data;
6836     const char *typename;
6837     char *name;
6838 
6839     typename = object_class_get_name(oc);
6840     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
6841     qemu_printf("  %s\n", name);
6842     g_free(name);
6843 }
6844 
6845 void arm_cpu_list(void)
6846 {
6847     GSList *list;
6848 
6849     list = object_class_get_list(TYPE_ARM_CPU, false);
6850     list = g_slist_sort(list, arm_cpu_list_compare);
6851     qemu_printf("Available CPUs:\n");
6852     g_slist_foreach(list, arm_cpu_list_entry, NULL);
6853     g_slist_free(list);
6854 }
6855 
6856 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
6857 {
6858     ObjectClass *oc = data;
6859     CpuDefinitionInfoList **cpu_list = user_data;
6860     CpuDefinitionInfoList *entry;
6861     CpuDefinitionInfo *info;
6862     const char *typename;
6863 
6864     typename = object_class_get_name(oc);
6865     info = g_malloc0(sizeof(*info));
6866     info->name = g_strndup(typename,
6867                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
6868     info->q_typename = g_strdup(typename);
6869 
6870     entry = g_malloc0(sizeof(*entry));
6871     entry->value = info;
6872     entry->next = *cpu_list;
6873     *cpu_list = entry;
6874 }
6875 
6876 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
6877 {
6878     CpuDefinitionInfoList *cpu_list = NULL;
6879     GSList *list;
6880 
6881     list = object_class_get_list(TYPE_ARM_CPU, false);
6882     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
6883     g_slist_free(list);
6884 
6885     return cpu_list;
6886 }
6887 
6888 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
6889                                    void *opaque, int state, int secstate,
6890                                    int crm, int opc1, int opc2,
6891                                    const char *name)
6892 {
6893     /* Private utility function for define_one_arm_cp_reg_with_opaque():
6894      * add a single reginfo struct to the hash table.
6895      */
6896     uint32_t *key = g_new(uint32_t, 1);
6897     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
6898     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
6899     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
6900 
6901     r2->name = g_strdup(name);
6902     /* Reset the secure state to the specific incoming state.  This is
6903      * necessary as the register may have been defined with both states.
6904      */
6905     r2->secure = secstate;
6906 
6907     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
6908         /* Register is banked (using both entries in array).
6909          * Overwriting fieldoffset as the array is only used to define
6910          * banked registers but later only fieldoffset is used.
6911          */
6912         r2->fieldoffset = r->bank_fieldoffsets[ns];
6913     }
6914 
6915     if (state == ARM_CP_STATE_AA32) {
6916         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
6917             /* If the register is banked then we don't need to migrate or
6918              * reset the 32-bit instance in certain cases:
6919              *
6920              * 1) If the register has both 32-bit and 64-bit instances then we
6921              *    can count on the 64-bit instance taking care of the
6922              *    non-secure bank.
6923              * 2) If ARMv8 is enabled then we can count on a 64-bit version
6924              *    taking care of the secure bank.  This requires that separate
6925              *    32 and 64-bit definitions are provided.
6926              */
6927             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
6928                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
6929                 r2->type |= ARM_CP_ALIAS;
6930             }
6931         } else if ((secstate != r->secure) && !ns) {
6932             /* The register is not banked so we only want to allow migration of
6933              * the non-secure instance.
6934              */
6935             r2->type |= ARM_CP_ALIAS;
6936         }
6937 
6938         if (r->state == ARM_CP_STATE_BOTH) {
6939             /* We assume it is a cp15 register if the .cp field is left unset.
6940              */
6941             if (r2->cp == 0) {
6942                 r2->cp = 15;
6943             }
6944 
6945 #ifdef HOST_WORDS_BIGENDIAN
6946             if (r2->fieldoffset) {
6947                 r2->fieldoffset += sizeof(uint32_t);
6948             }
6949 #endif
6950         }
6951     }
6952     if (state == ARM_CP_STATE_AA64) {
6953         /* To allow abbreviation of ARMCPRegInfo
6954          * definitions, we treat cp == 0 as equivalent to
6955          * the value for "standard guest-visible sysreg".
6956          * STATE_BOTH definitions are also always "standard
6957          * sysreg" in their AArch64 view (the .cp value may
6958          * be non-zero for the benefit of the AArch32 view).
6959          */
6960         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
6961             r2->cp = CP_REG_ARM64_SYSREG_CP;
6962         }
6963         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
6964                                   r2->opc0, opc1, opc2);
6965     } else {
6966         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
6967     }
6968     if (opaque) {
6969         r2->opaque = opaque;
6970     }
6971     /* reginfo passed to helpers is correct for the actual access,
6972      * and is never ARM_CP_STATE_BOTH:
6973      */
6974     r2->state = state;
6975     /* Make sure reginfo passed to helpers for wildcarded regs
6976      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
6977      */
6978     r2->crm = crm;
6979     r2->opc1 = opc1;
6980     r2->opc2 = opc2;
6981     /* By convention, for wildcarded registers only the first
6982      * entry is used for migration; the others are marked as
6983      * ALIAS so we don't try to transfer the register
6984      * multiple times. Special registers (ie NOP/WFI) are
6985      * never migratable and not even raw-accessible.
6986      */
6987     if ((r->type & ARM_CP_SPECIAL)) {
6988         r2->type |= ARM_CP_NO_RAW;
6989     }
6990     if (((r->crm == CP_ANY) && crm != 0) ||
6991         ((r->opc1 == CP_ANY) && opc1 != 0) ||
6992         ((r->opc2 == CP_ANY) && opc2 != 0)) {
6993         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
6994     }
6995 
6996     /* Check that raw accesses are either forbidden or handled. Note that
6997      * we can't assert this earlier because the setup of fieldoffset for
6998      * banked registers has to be done first.
6999      */
7000     if (!(r2->type & ARM_CP_NO_RAW)) {
7001         assert(!raw_accessors_invalid(r2));
7002     }
7003 
7004     /* Overriding of an existing definition must be explicitly
7005      * requested.
7006      */
7007     if (!(r->type & ARM_CP_OVERRIDE)) {
7008         ARMCPRegInfo *oldreg;
7009         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
7010         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
7011             fprintf(stderr, "Register redefined: cp=%d %d bit "
7012                     "crn=%d crm=%d opc1=%d opc2=%d, "
7013                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
7014                     r2->crn, r2->crm, r2->opc1, r2->opc2,
7015                     oldreg->name, r2->name);
7016             g_assert_not_reached();
7017         }
7018     }
7019     g_hash_table_insert(cpu->cp_regs, key, r2);
7020 }
7021 
7022 
7023 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
7024                                        const ARMCPRegInfo *r, void *opaque)
7025 {
7026     /* Define implementations of coprocessor registers.
7027      * We store these in a hashtable because typically
7028      * there are less than 150 registers in a space which
7029      * is 16*16*16*8*8 = 262144 in size.
7030      * Wildcarding is supported for the crm, opc1 and opc2 fields.
7031      * If a register is defined twice then the second definition is
7032      * used, so this can be used to define some generic registers and
7033      * then override them with implementation specific variations.
7034      * At least one of the original and the second definition should
7035      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
7036      * against accidental use.
7037      *
7038      * The state field defines whether the register is to be
7039      * visible in the AArch32 or AArch64 execution state. If the
7040      * state is set to ARM_CP_STATE_BOTH then we synthesise a
7041      * reginfo structure for the AArch32 view, which sees the lower
7042      * 32 bits of the 64 bit register.
7043      *
7044      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
7045      * be wildcarded. AArch64 registers are always considered to be 64
7046      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
7047      * the register, if any.
7048      */
7049     int crm, opc1, opc2, state;
7050     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
7051     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
7052     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
7053     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
7054     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
7055     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
7056     /* 64 bit registers have only CRm and Opc1 fields */
7057     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
7058     /* op0 only exists in the AArch64 encodings */
7059     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
7060     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
7061     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
7062     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
7063      * encodes a minimum access level for the register. We roll this
7064      * runtime check into our general permission check code, so check
7065      * here that the reginfo's specified permissions are strict enough
7066      * to encompass the generic architectural permission check.
7067      */
7068     if (r->state != ARM_CP_STATE_AA32) {
7069         int mask = 0;
7070         switch (r->opc1) {
7071         case 0:
7072             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
7073             mask = PL0U_R | PL1_RW;
7074             break;
7075         case 1: case 2:
7076             /* min_EL EL1 */
7077             mask = PL1_RW;
7078             break;
7079         case 3:
7080             /* min_EL EL0 */
7081             mask = PL0_RW;
7082             break;
7083         case 4:
7084             /* min_EL EL2 */
7085             mask = PL2_RW;
7086             break;
7087         case 5:
7088             /* unallocated encoding, so not possible */
7089             assert(false);
7090             break;
7091         case 6:
7092             /* min_EL EL3 */
7093             mask = PL3_RW;
7094             break;
7095         case 7:
7096             /* min_EL EL1, secure mode only (we don't check the latter) */
7097             mask = PL1_RW;
7098             break;
7099         default:
7100             /* broken reginfo with out-of-range opc1 */
7101             assert(false);
7102             break;
7103         }
7104         /* assert our permissions are not too lax (stricter is fine) */
7105         assert((r->access & ~mask) == 0);
7106     }
7107 
7108     /* Check that the register definition has enough info to handle
7109      * reads and writes if they are permitted.
7110      */
7111     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
7112         if (r->access & PL3_R) {
7113             assert((r->fieldoffset ||
7114                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7115                    r->readfn);
7116         }
7117         if (r->access & PL3_W) {
7118             assert((r->fieldoffset ||
7119                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7120                    r->writefn);
7121         }
7122     }
7123     /* Bad type field probably means missing sentinel at end of reg list */
7124     assert(cptype_valid(r->type));
7125     for (crm = crmmin; crm <= crmmax; crm++) {
7126         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
7127             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
7128                 for (state = ARM_CP_STATE_AA32;
7129                      state <= ARM_CP_STATE_AA64; state++) {
7130                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
7131                         continue;
7132                     }
7133                     if (state == ARM_CP_STATE_AA32) {
7134                         /* Under AArch32 CP registers can be common
7135                          * (same for secure and non-secure world) or banked.
7136                          */
7137                         char *name;
7138 
7139                         switch (r->secure) {
7140                         case ARM_CP_SECSTATE_S:
7141                         case ARM_CP_SECSTATE_NS:
7142                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7143                                                    r->secure, crm, opc1, opc2,
7144                                                    r->name);
7145                             break;
7146                         default:
7147                             name = g_strdup_printf("%s_S", r->name);
7148                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7149                                                    ARM_CP_SECSTATE_S,
7150                                                    crm, opc1, opc2, name);
7151                             g_free(name);
7152                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7153                                                    ARM_CP_SECSTATE_NS,
7154                                                    crm, opc1, opc2, r->name);
7155                             break;
7156                         }
7157                     } else {
7158                         /* AArch64 registers get mapped to non-secure instance
7159                          * of AArch32 */
7160                         add_cpreg_to_hashtable(cpu, r, opaque, state,
7161                                                ARM_CP_SECSTATE_NS,
7162                                                crm, opc1, opc2, r->name);
7163                     }
7164                 }
7165             }
7166         }
7167     }
7168 }
7169 
7170 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
7171                                     const ARMCPRegInfo *regs, void *opaque)
7172 {
7173     /* Define a whole list of registers */
7174     const ARMCPRegInfo *r;
7175     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7176         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
7177     }
7178 }
7179 
7180 /*
7181  * Modify ARMCPRegInfo for access from userspace.
7182  *
7183  * This is a data driven modification directed by
7184  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
7185  * user-space cannot alter any values and dynamic values pertaining to
7186  * execution state are hidden from user space view anyway.
7187  */
7188 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
7189 {
7190     const ARMCPRegUserSpaceInfo *m;
7191     ARMCPRegInfo *r;
7192 
7193     for (m = mods; m->name; m++) {
7194         GPatternSpec *pat = NULL;
7195         if (m->is_glob) {
7196             pat = g_pattern_spec_new(m->name);
7197         }
7198         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7199             if (pat && g_pattern_match_string(pat, r->name)) {
7200                 r->type = ARM_CP_CONST;
7201                 r->access = PL0U_R;
7202                 r->resetvalue = 0;
7203                 /* continue */
7204             } else if (strcmp(r->name, m->name) == 0) {
7205                 r->type = ARM_CP_CONST;
7206                 r->access = PL0U_R;
7207                 r->resetvalue &= m->exported_bits;
7208                 r->resetvalue |= m->fixed_bits;
7209                 break;
7210             }
7211         }
7212         if (pat) {
7213             g_pattern_spec_free(pat);
7214         }
7215     }
7216 }
7217 
7218 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
7219 {
7220     return g_hash_table_lookup(cpregs, &encoded_cp);
7221 }
7222 
7223 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
7224                          uint64_t value)
7225 {
7226     /* Helper coprocessor write function for write-ignore registers */
7227 }
7228 
7229 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
7230 {
7231     /* Helper coprocessor write function for read-as-zero registers */
7232     return 0;
7233 }
7234 
7235 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
7236 {
7237     /* Helper coprocessor reset function for do-nothing-on-reset registers */
7238 }
7239 
7240 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
7241 {
7242     /* Return true if it is not valid for us to switch to
7243      * this CPU mode (ie all the UNPREDICTABLE cases in
7244      * the ARM ARM CPSRWriteByInstr pseudocode).
7245      */
7246 
7247     /* Changes to or from Hyp via MSR and CPS are illegal. */
7248     if (write_type == CPSRWriteByInstr &&
7249         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
7250          mode == ARM_CPU_MODE_HYP)) {
7251         return 1;
7252     }
7253 
7254     switch (mode) {
7255     case ARM_CPU_MODE_USR:
7256         return 0;
7257     case ARM_CPU_MODE_SYS:
7258     case ARM_CPU_MODE_SVC:
7259     case ARM_CPU_MODE_ABT:
7260     case ARM_CPU_MODE_UND:
7261     case ARM_CPU_MODE_IRQ:
7262     case ARM_CPU_MODE_FIQ:
7263         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
7264          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
7265          */
7266         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
7267          * and CPS are treated as illegal mode changes.
7268          */
7269         if (write_type == CPSRWriteByInstr &&
7270             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
7271             (arm_hcr_el2_eff(env) & HCR_TGE)) {
7272             return 1;
7273         }
7274         return 0;
7275     case ARM_CPU_MODE_HYP:
7276         return !arm_feature(env, ARM_FEATURE_EL2)
7277             || arm_current_el(env) < 2 || arm_is_secure_below_el3(env);
7278     case ARM_CPU_MODE_MON:
7279         return arm_current_el(env) < 3;
7280     default:
7281         return 1;
7282     }
7283 }
7284 
7285 uint32_t cpsr_read(CPUARMState *env)
7286 {
7287     int ZF;
7288     ZF = (env->ZF == 0);
7289     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
7290         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
7291         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
7292         | ((env->condexec_bits & 0xfc) << 8)
7293         | (env->GE << 16) | (env->daif & CPSR_AIF);
7294 }
7295 
7296 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
7297                 CPSRWriteType write_type)
7298 {
7299     uint32_t changed_daif;
7300 
7301     if (mask & CPSR_NZCV) {
7302         env->ZF = (~val) & CPSR_Z;
7303         env->NF = val;
7304         env->CF = (val >> 29) & 1;
7305         env->VF = (val << 3) & 0x80000000;
7306     }
7307     if (mask & CPSR_Q)
7308         env->QF = ((val & CPSR_Q) != 0);
7309     if (mask & CPSR_T)
7310         env->thumb = ((val & CPSR_T) != 0);
7311     if (mask & CPSR_IT_0_1) {
7312         env->condexec_bits &= ~3;
7313         env->condexec_bits |= (val >> 25) & 3;
7314     }
7315     if (mask & CPSR_IT_2_7) {
7316         env->condexec_bits &= 3;
7317         env->condexec_bits |= (val >> 8) & 0xfc;
7318     }
7319     if (mask & CPSR_GE) {
7320         env->GE = (val >> 16) & 0xf;
7321     }
7322 
7323     /* In a V7 implementation that includes the security extensions but does
7324      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
7325      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
7326      * bits respectively.
7327      *
7328      * In a V8 implementation, it is permitted for privileged software to
7329      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
7330      */
7331     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
7332         arm_feature(env, ARM_FEATURE_EL3) &&
7333         !arm_feature(env, ARM_FEATURE_EL2) &&
7334         !arm_is_secure(env)) {
7335 
7336         changed_daif = (env->daif ^ val) & mask;
7337 
7338         if (changed_daif & CPSR_A) {
7339             /* Check to see if we are allowed to change the masking of async
7340              * abort exceptions from a non-secure state.
7341              */
7342             if (!(env->cp15.scr_el3 & SCR_AW)) {
7343                 qemu_log_mask(LOG_GUEST_ERROR,
7344                               "Ignoring attempt to switch CPSR_A flag from "
7345                               "non-secure world with SCR.AW bit clear\n");
7346                 mask &= ~CPSR_A;
7347             }
7348         }
7349 
7350         if (changed_daif & CPSR_F) {
7351             /* Check to see if we are allowed to change the masking of FIQ
7352              * exceptions from a non-secure state.
7353              */
7354             if (!(env->cp15.scr_el3 & SCR_FW)) {
7355                 qemu_log_mask(LOG_GUEST_ERROR,
7356                               "Ignoring attempt to switch CPSR_F flag from "
7357                               "non-secure world with SCR.FW bit clear\n");
7358                 mask &= ~CPSR_F;
7359             }
7360 
7361             /* Check whether non-maskable FIQ (NMFI) support is enabled.
7362              * If this bit is set software is not allowed to mask
7363              * FIQs, but is allowed to set CPSR_F to 0.
7364              */
7365             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
7366                 (val & CPSR_F)) {
7367                 qemu_log_mask(LOG_GUEST_ERROR,
7368                               "Ignoring attempt to enable CPSR_F flag "
7369                               "(non-maskable FIQ [NMFI] support enabled)\n");
7370                 mask &= ~CPSR_F;
7371             }
7372         }
7373     }
7374 
7375     env->daif &= ~(CPSR_AIF & mask);
7376     env->daif |= val & CPSR_AIF & mask;
7377 
7378     if (write_type != CPSRWriteRaw &&
7379         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
7380         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
7381             /* Note that we can only get here in USR mode if this is a
7382              * gdb stub write; for this case we follow the architectural
7383              * behaviour for guest writes in USR mode of ignoring an attempt
7384              * to switch mode. (Those are caught by translate.c for writes
7385              * triggered by guest instructions.)
7386              */
7387             mask &= ~CPSR_M;
7388         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
7389             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
7390              * v7, and has defined behaviour in v8:
7391              *  + leave CPSR.M untouched
7392              *  + allow changes to the other CPSR fields
7393              *  + set PSTATE.IL
7394              * For user changes via the GDB stub, we don't set PSTATE.IL,
7395              * as this would be unnecessarily harsh for a user error.
7396              */
7397             mask &= ~CPSR_M;
7398             if (write_type != CPSRWriteByGDBStub &&
7399                 arm_feature(env, ARM_FEATURE_V8)) {
7400                 mask |= CPSR_IL;
7401                 val |= CPSR_IL;
7402             }
7403             qemu_log_mask(LOG_GUEST_ERROR,
7404                           "Illegal AArch32 mode switch attempt from %s to %s\n",
7405                           aarch32_mode_name(env->uncached_cpsr),
7406                           aarch32_mode_name(val));
7407         } else {
7408             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
7409                           write_type == CPSRWriteExceptionReturn ?
7410                           "Exception return from AArch32" :
7411                           "AArch32 mode switch from",
7412                           aarch32_mode_name(env->uncached_cpsr),
7413                           aarch32_mode_name(val), env->regs[15]);
7414             switch_mode(env, val & CPSR_M);
7415         }
7416     }
7417     mask &= ~CACHED_CPSR_BITS;
7418     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
7419 }
7420 
7421 /* Sign/zero extend */
7422 uint32_t HELPER(sxtb16)(uint32_t x)
7423 {
7424     uint32_t res;
7425     res = (uint16_t)(int8_t)x;
7426     res |= (uint32_t)(int8_t)(x >> 16) << 16;
7427     return res;
7428 }
7429 
7430 uint32_t HELPER(uxtb16)(uint32_t x)
7431 {
7432     uint32_t res;
7433     res = (uint16_t)(uint8_t)x;
7434     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
7435     return res;
7436 }
7437 
7438 int32_t HELPER(sdiv)(int32_t num, int32_t den)
7439 {
7440     if (den == 0)
7441       return 0;
7442     if (num == INT_MIN && den == -1)
7443       return INT_MIN;
7444     return num / den;
7445 }
7446 
7447 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
7448 {
7449     if (den == 0)
7450       return 0;
7451     return num / den;
7452 }
7453 
7454 uint32_t HELPER(rbit)(uint32_t x)
7455 {
7456     return revbit32(x);
7457 }
7458 
7459 #ifdef CONFIG_USER_ONLY
7460 
7461 static void switch_mode(CPUARMState *env, int mode)
7462 {
7463     ARMCPU *cpu = env_archcpu(env);
7464 
7465     if (mode != ARM_CPU_MODE_USR) {
7466         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
7467     }
7468 }
7469 
7470 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7471                                  uint32_t cur_el, bool secure)
7472 {
7473     return 1;
7474 }
7475 
7476 void aarch64_sync_64_to_32(CPUARMState *env)
7477 {
7478     g_assert_not_reached();
7479 }
7480 
7481 #else
7482 
7483 static void switch_mode(CPUARMState *env, int mode)
7484 {
7485     int old_mode;
7486     int i;
7487 
7488     old_mode = env->uncached_cpsr & CPSR_M;
7489     if (mode == old_mode)
7490         return;
7491 
7492     if (old_mode == ARM_CPU_MODE_FIQ) {
7493         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
7494         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
7495     } else if (mode == ARM_CPU_MODE_FIQ) {
7496         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
7497         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
7498     }
7499 
7500     i = bank_number(old_mode);
7501     env->banked_r13[i] = env->regs[13];
7502     env->banked_spsr[i] = env->spsr;
7503 
7504     i = bank_number(mode);
7505     env->regs[13] = env->banked_r13[i];
7506     env->spsr = env->banked_spsr[i];
7507 
7508     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
7509     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
7510 }
7511 
7512 /* Physical Interrupt Target EL Lookup Table
7513  *
7514  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
7515  *
7516  * The below multi-dimensional table is used for looking up the target
7517  * exception level given numerous condition criteria.  Specifically, the
7518  * target EL is based on SCR and HCR routing controls as well as the
7519  * currently executing EL and secure state.
7520  *
7521  *    Dimensions:
7522  *    target_el_table[2][2][2][2][2][4]
7523  *                    |  |  |  |  |  +--- Current EL
7524  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
7525  *                    |  |  |  +--------- HCR mask override
7526  *                    |  |  +------------ SCR exec state control
7527  *                    |  +--------------- SCR mask override
7528  *                    +------------------ 32-bit(0)/64-bit(1) EL3
7529  *
7530  *    The table values are as such:
7531  *    0-3 = EL0-EL3
7532  *     -1 = Cannot occur
7533  *
7534  * The ARM ARM target EL table includes entries indicating that an "exception
7535  * is not taken".  The two cases where this is applicable are:
7536  *    1) An exception is taken from EL3 but the SCR does not have the exception
7537  *    routed to EL3.
7538  *    2) An exception is taken from EL2 but the HCR does not have the exception
7539  *    routed to EL2.
7540  * In these two cases, the below table contain a target of EL1.  This value is
7541  * returned as it is expected that the consumer of the table data will check
7542  * for "target EL >= current EL" to ensure the exception is not taken.
7543  *
7544  *            SCR     HCR
7545  *         64  EA     AMO                 From
7546  *        BIT IRQ     IMO      Non-secure         Secure
7547  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
7548  */
7549 static const int8_t target_el_table[2][2][2][2][2][4] = {
7550     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7551        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
7552       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7553        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
7554      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7555        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
7556       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7557        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
7558     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
7559        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
7560       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
7561        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
7562      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7563        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
7564       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7565        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
7566 };
7567 
7568 /*
7569  * Determine the target EL for physical exceptions
7570  */
7571 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7572                                  uint32_t cur_el, bool secure)
7573 {
7574     CPUARMState *env = cs->env_ptr;
7575     bool rw;
7576     bool scr;
7577     bool hcr;
7578     int target_el;
7579     /* Is the highest EL AArch64? */
7580     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
7581     uint64_t hcr_el2;
7582 
7583     if (arm_feature(env, ARM_FEATURE_EL3)) {
7584         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
7585     } else {
7586         /* Either EL2 is the highest EL (and so the EL2 register width
7587          * is given by is64); or there is no EL2 or EL3, in which case
7588          * the value of 'rw' does not affect the table lookup anyway.
7589          */
7590         rw = is64;
7591     }
7592 
7593     hcr_el2 = arm_hcr_el2_eff(env);
7594     switch (excp_idx) {
7595     case EXCP_IRQ:
7596         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
7597         hcr = hcr_el2 & HCR_IMO;
7598         break;
7599     case EXCP_FIQ:
7600         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
7601         hcr = hcr_el2 & HCR_FMO;
7602         break;
7603     default:
7604         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
7605         hcr = hcr_el2 & HCR_AMO;
7606         break;
7607     };
7608 
7609     /* Perform a table-lookup for the target EL given the current state */
7610     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
7611 
7612     assert(target_el > 0);
7613 
7614     return target_el;
7615 }
7616 
7617 void arm_log_exception(int idx)
7618 {
7619     if (qemu_loglevel_mask(CPU_LOG_INT)) {
7620         const char *exc = NULL;
7621         static const char * const excnames[] = {
7622             [EXCP_UDEF] = "Undefined Instruction",
7623             [EXCP_SWI] = "SVC",
7624             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
7625             [EXCP_DATA_ABORT] = "Data Abort",
7626             [EXCP_IRQ] = "IRQ",
7627             [EXCP_FIQ] = "FIQ",
7628             [EXCP_BKPT] = "Breakpoint",
7629             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
7630             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
7631             [EXCP_HVC] = "Hypervisor Call",
7632             [EXCP_HYP_TRAP] = "Hypervisor Trap",
7633             [EXCP_SMC] = "Secure Monitor Call",
7634             [EXCP_VIRQ] = "Virtual IRQ",
7635             [EXCP_VFIQ] = "Virtual FIQ",
7636             [EXCP_SEMIHOST] = "Semihosting call",
7637             [EXCP_NOCP] = "v7M NOCP UsageFault",
7638             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
7639             [EXCP_STKOF] = "v8M STKOF UsageFault",
7640             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
7641             [EXCP_LSERR] = "v8M LSERR UsageFault",
7642             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
7643         };
7644 
7645         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
7646             exc = excnames[idx];
7647         }
7648         if (!exc) {
7649             exc = "unknown";
7650         }
7651         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
7652     }
7653 }
7654 
7655 /*
7656  * Function used to synchronize QEMU's AArch64 register set with AArch32
7657  * register set.  This is necessary when switching between AArch32 and AArch64
7658  * execution state.
7659  */
7660 void aarch64_sync_32_to_64(CPUARMState *env)
7661 {
7662     int i;
7663     uint32_t mode = env->uncached_cpsr & CPSR_M;
7664 
7665     /* We can blanket copy R[0:7] to X[0:7] */
7666     for (i = 0; i < 8; i++) {
7667         env->xregs[i] = env->regs[i];
7668     }
7669 
7670     /*
7671      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
7672      * Otherwise, they come from the banked user regs.
7673      */
7674     if (mode == ARM_CPU_MODE_FIQ) {
7675         for (i = 8; i < 13; i++) {
7676             env->xregs[i] = env->usr_regs[i - 8];
7677         }
7678     } else {
7679         for (i = 8; i < 13; i++) {
7680             env->xregs[i] = env->regs[i];
7681         }
7682     }
7683 
7684     /*
7685      * Registers x13-x23 are the various mode SP and FP registers. Registers
7686      * r13 and r14 are only copied if we are in that mode, otherwise we copy
7687      * from the mode banked register.
7688      */
7689     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7690         env->xregs[13] = env->regs[13];
7691         env->xregs[14] = env->regs[14];
7692     } else {
7693         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
7694         /* HYP is an exception in that it is copied from r14 */
7695         if (mode == ARM_CPU_MODE_HYP) {
7696             env->xregs[14] = env->regs[14];
7697         } else {
7698             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
7699         }
7700     }
7701 
7702     if (mode == ARM_CPU_MODE_HYP) {
7703         env->xregs[15] = env->regs[13];
7704     } else {
7705         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
7706     }
7707 
7708     if (mode == ARM_CPU_MODE_IRQ) {
7709         env->xregs[16] = env->regs[14];
7710         env->xregs[17] = env->regs[13];
7711     } else {
7712         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
7713         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
7714     }
7715 
7716     if (mode == ARM_CPU_MODE_SVC) {
7717         env->xregs[18] = env->regs[14];
7718         env->xregs[19] = env->regs[13];
7719     } else {
7720         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
7721         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
7722     }
7723 
7724     if (mode == ARM_CPU_MODE_ABT) {
7725         env->xregs[20] = env->regs[14];
7726         env->xregs[21] = env->regs[13];
7727     } else {
7728         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
7729         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
7730     }
7731 
7732     if (mode == ARM_CPU_MODE_UND) {
7733         env->xregs[22] = env->regs[14];
7734         env->xregs[23] = env->regs[13];
7735     } else {
7736         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
7737         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
7738     }
7739 
7740     /*
7741      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7742      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
7743      * FIQ bank for r8-r14.
7744      */
7745     if (mode == ARM_CPU_MODE_FIQ) {
7746         for (i = 24; i < 31; i++) {
7747             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
7748         }
7749     } else {
7750         for (i = 24; i < 29; i++) {
7751             env->xregs[i] = env->fiq_regs[i - 24];
7752         }
7753         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
7754         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
7755     }
7756 
7757     env->pc = env->regs[15];
7758 }
7759 
7760 /*
7761  * Function used to synchronize QEMU's AArch32 register set with AArch64
7762  * register set.  This is necessary when switching between AArch32 and AArch64
7763  * execution state.
7764  */
7765 void aarch64_sync_64_to_32(CPUARMState *env)
7766 {
7767     int i;
7768     uint32_t mode = env->uncached_cpsr & CPSR_M;
7769 
7770     /* We can blanket copy X[0:7] to R[0:7] */
7771     for (i = 0; i < 8; i++) {
7772         env->regs[i] = env->xregs[i];
7773     }
7774 
7775     /*
7776      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
7777      * Otherwise, we copy x8-x12 into the banked user regs.
7778      */
7779     if (mode == ARM_CPU_MODE_FIQ) {
7780         for (i = 8; i < 13; i++) {
7781             env->usr_regs[i - 8] = env->xregs[i];
7782         }
7783     } else {
7784         for (i = 8; i < 13; i++) {
7785             env->regs[i] = env->xregs[i];
7786         }
7787     }
7788 
7789     /*
7790      * Registers r13 & r14 depend on the current mode.
7791      * If we are in a given mode, we copy the corresponding x registers to r13
7792      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
7793      * for the mode.
7794      */
7795     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7796         env->regs[13] = env->xregs[13];
7797         env->regs[14] = env->xregs[14];
7798     } else {
7799         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
7800 
7801         /*
7802          * HYP is an exception in that it does not have its own banked r14 but
7803          * shares the USR r14
7804          */
7805         if (mode == ARM_CPU_MODE_HYP) {
7806             env->regs[14] = env->xregs[14];
7807         } else {
7808             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
7809         }
7810     }
7811 
7812     if (mode == ARM_CPU_MODE_HYP) {
7813         env->regs[13] = env->xregs[15];
7814     } else {
7815         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
7816     }
7817 
7818     if (mode == ARM_CPU_MODE_IRQ) {
7819         env->regs[14] = env->xregs[16];
7820         env->regs[13] = env->xregs[17];
7821     } else {
7822         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
7823         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
7824     }
7825 
7826     if (mode == ARM_CPU_MODE_SVC) {
7827         env->regs[14] = env->xregs[18];
7828         env->regs[13] = env->xregs[19];
7829     } else {
7830         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
7831         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
7832     }
7833 
7834     if (mode == ARM_CPU_MODE_ABT) {
7835         env->regs[14] = env->xregs[20];
7836         env->regs[13] = env->xregs[21];
7837     } else {
7838         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
7839         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
7840     }
7841 
7842     if (mode == ARM_CPU_MODE_UND) {
7843         env->regs[14] = env->xregs[22];
7844         env->regs[13] = env->xregs[23];
7845     } else {
7846         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
7847         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
7848     }
7849 
7850     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7851      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
7852      * FIQ bank for r8-r14.
7853      */
7854     if (mode == ARM_CPU_MODE_FIQ) {
7855         for (i = 24; i < 31; i++) {
7856             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
7857         }
7858     } else {
7859         for (i = 24; i < 29; i++) {
7860             env->fiq_regs[i - 24] = env->xregs[i];
7861         }
7862         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
7863         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
7864     }
7865 
7866     env->regs[15] = env->pc;
7867 }
7868 
7869 static void take_aarch32_exception(CPUARMState *env, int new_mode,
7870                                    uint32_t mask, uint32_t offset,
7871                                    uint32_t newpc)
7872 {
7873     /* Change the CPU state so as to actually take the exception. */
7874     switch_mode(env, new_mode);
7875     /*
7876      * For exceptions taken to AArch32 we must clear the SS bit in both
7877      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
7878      */
7879     env->uncached_cpsr &= ~PSTATE_SS;
7880     env->spsr = cpsr_read(env);
7881     /* Clear IT bits.  */
7882     env->condexec_bits = 0;
7883     /* Switch to the new mode, and to the correct instruction set.  */
7884     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
7885     /* Set new mode endianness */
7886     env->uncached_cpsr &= ~CPSR_E;
7887     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
7888         env->uncached_cpsr |= CPSR_E;
7889     }
7890     /* J and IL must always be cleared for exception entry */
7891     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
7892     env->daif |= mask;
7893 
7894     if (new_mode == ARM_CPU_MODE_HYP) {
7895         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
7896         env->elr_el[2] = env->regs[15];
7897     } else {
7898         /*
7899          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
7900          * and we should just guard the thumb mode on V4
7901          */
7902         if (arm_feature(env, ARM_FEATURE_V4T)) {
7903             env->thumb =
7904                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
7905         }
7906         env->regs[14] = env->regs[15] + offset;
7907     }
7908     env->regs[15] = newpc;
7909 }
7910 
7911 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
7912 {
7913     /*
7914      * Handle exception entry to Hyp mode; this is sufficiently
7915      * different to entry to other AArch32 modes that we handle it
7916      * separately here.
7917      *
7918      * The vector table entry used is always the 0x14 Hyp mode entry point,
7919      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
7920      * The offset applied to the preferred return address is always zero
7921      * (see DDI0487C.a section G1.12.3).
7922      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
7923      */
7924     uint32_t addr, mask;
7925     ARMCPU *cpu = ARM_CPU(cs);
7926     CPUARMState *env = &cpu->env;
7927 
7928     switch (cs->exception_index) {
7929     case EXCP_UDEF:
7930         addr = 0x04;
7931         break;
7932     case EXCP_SWI:
7933         addr = 0x14;
7934         break;
7935     case EXCP_BKPT:
7936         /* Fall through to prefetch abort.  */
7937     case EXCP_PREFETCH_ABORT:
7938         env->cp15.ifar_s = env->exception.vaddress;
7939         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
7940                       (uint32_t)env->exception.vaddress);
7941         addr = 0x0c;
7942         break;
7943     case EXCP_DATA_ABORT:
7944         env->cp15.dfar_s = env->exception.vaddress;
7945         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
7946                       (uint32_t)env->exception.vaddress);
7947         addr = 0x10;
7948         break;
7949     case EXCP_IRQ:
7950         addr = 0x18;
7951         break;
7952     case EXCP_FIQ:
7953         addr = 0x1c;
7954         break;
7955     case EXCP_HVC:
7956         addr = 0x08;
7957         break;
7958     case EXCP_HYP_TRAP:
7959         addr = 0x14;
7960         break;
7961     default:
7962         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
7963     }
7964 
7965     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
7966         if (!arm_feature(env, ARM_FEATURE_V8)) {
7967             /*
7968              * QEMU syndrome values are v8-style. v7 has the IL bit
7969              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
7970              * If this is a v7 CPU, squash the IL bit in those cases.
7971              */
7972             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
7973                 (cs->exception_index == EXCP_DATA_ABORT &&
7974                  !(env->exception.syndrome & ARM_EL_ISV)) ||
7975                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
7976                 env->exception.syndrome &= ~ARM_EL_IL;
7977             }
7978         }
7979         env->cp15.esr_el[2] = env->exception.syndrome;
7980     }
7981 
7982     if (arm_current_el(env) != 2 && addr < 0x14) {
7983         addr = 0x14;
7984     }
7985 
7986     mask = 0;
7987     if (!(env->cp15.scr_el3 & SCR_EA)) {
7988         mask |= CPSR_A;
7989     }
7990     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
7991         mask |= CPSR_I;
7992     }
7993     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
7994         mask |= CPSR_F;
7995     }
7996 
7997     addr += env->cp15.hvbar;
7998 
7999     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
8000 }
8001 
8002 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
8003 {
8004     ARMCPU *cpu = ARM_CPU(cs);
8005     CPUARMState *env = &cpu->env;
8006     uint32_t addr;
8007     uint32_t mask;
8008     int new_mode;
8009     uint32_t offset;
8010     uint32_t moe;
8011 
8012     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
8013     switch (syn_get_ec(env->exception.syndrome)) {
8014     case EC_BREAKPOINT:
8015     case EC_BREAKPOINT_SAME_EL:
8016         moe = 1;
8017         break;
8018     case EC_WATCHPOINT:
8019     case EC_WATCHPOINT_SAME_EL:
8020         moe = 10;
8021         break;
8022     case EC_AA32_BKPT:
8023         moe = 3;
8024         break;
8025     case EC_VECTORCATCH:
8026         moe = 5;
8027         break;
8028     default:
8029         moe = 0;
8030         break;
8031     }
8032 
8033     if (moe) {
8034         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
8035     }
8036 
8037     if (env->exception.target_el == 2) {
8038         arm_cpu_do_interrupt_aarch32_hyp(cs);
8039         return;
8040     }
8041 
8042     switch (cs->exception_index) {
8043     case EXCP_UDEF:
8044         new_mode = ARM_CPU_MODE_UND;
8045         addr = 0x04;
8046         mask = CPSR_I;
8047         if (env->thumb)
8048             offset = 2;
8049         else
8050             offset = 4;
8051         break;
8052     case EXCP_SWI:
8053         new_mode = ARM_CPU_MODE_SVC;
8054         addr = 0x08;
8055         mask = CPSR_I;
8056         /* The PC already points to the next instruction.  */
8057         offset = 0;
8058         break;
8059     case EXCP_BKPT:
8060         /* Fall through to prefetch abort.  */
8061     case EXCP_PREFETCH_ABORT:
8062         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
8063         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
8064         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
8065                       env->exception.fsr, (uint32_t)env->exception.vaddress);
8066         new_mode = ARM_CPU_MODE_ABT;
8067         addr = 0x0c;
8068         mask = CPSR_A | CPSR_I;
8069         offset = 4;
8070         break;
8071     case EXCP_DATA_ABORT:
8072         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
8073         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
8074         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
8075                       env->exception.fsr,
8076                       (uint32_t)env->exception.vaddress);
8077         new_mode = ARM_CPU_MODE_ABT;
8078         addr = 0x10;
8079         mask = CPSR_A | CPSR_I;
8080         offset = 8;
8081         break;
8082     case EXCP_IRQ:
8083         new_mode = ARM_CPU_MODE_IRQ;
8084         addr = 0x18;
8085         /* Disable IRQ and imprecise data aborts.  */
8086         mask = CPSR_A | CPSR_I;
8087         offset = 4;
8088         if (env->cp15.scr_el3 & SCR_IRQ) {
8089             /* IRQ routed to monitor mode */
8090             new_mode = ARM_CPU_MODE_MON;
8091             mask |= CPSR_F;
8092         }
8093         break;
8094     case EXCP_FIQ:
8095         new_mode = ARM_CPU_MODE_FIQ;
8096         addr = 0x1c;
8097         /* Disable FIQ, IRQ and imprecise data aborts.  */
8098         mask = CPSR_A | CPSR_I | CPSR_F;
8099         if (env->cp15.scr_el3 & SCR_FIQ) {
8100             /* FIQ routed to monitor mode */
8101             new_mode = ARM_CPU_MODE_MON;
8102         }
8103         offset = 4;
8104         break;
8105     case EXCP_VIRQ:
8106         new_mode = ARM_CPU_MODE_IRQ;
8107         addr = 0x18;
8108         /* Disable IRQ and imprecise data aborts.  */
8109         mask = CPSR_A | CPSR_I;
8110         offset = 4;
8111         break;
8112     case EXCP_VFIQ:
8113         new_mode = ARM_CPU_MODE_FIQ;
8114         addr = 0x1c;
8115         /* Disable FIQ, IRQ and imprecise data aborts.  */
8116         mask = CPSR_A | CPSR_I | CPSR_F;
8117         offset = 4;
8118         break;
8119     case EXCP_SMC:
8120         new_mode = ARM_CPU_MODE_MON;
8121         addr = 0x08;
8122         mask = CPSR_A | CPSR_I | CPSR_F;
8123         offset = 0;
8124         break;
8125     default:
8126         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8127         return; /* Never happens.  Keep compiler happy.  */
8128     }
8129 
8130     if (new_mode == ARM_CPU_MODE_MON) {
8131         addr += env->cp15.mvbar;
8132     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
8133         /* High vectors. When enabled, base address cannot be remapped. */
8134         addr += 0xffff0000;
8135     } else {
8136         /* ARM v7 architectures provide a vector base address register to remap
8137          * the interrupt vector table.
8138          * This register is only followed in non-monitor mode, and is banked.
8139          * Note: only bits 31:5 are valid.
8140          */
8141         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
8142     }
8143 
8144     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
8145         env->cp15.scr_el3 &= ~SCR_NS;
8146     }
8147 
8148     take_aarch32_exception(env, new_mode, mask, offset, addr);
8149 }
8150 
8151 /* Handle exception entry to a target EL which is using AArch64 */
8152 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
8153 {
8154     ARMCPU *cpu = ARM_CPU(cs);
8155     CPUARMState *env = &cpu->env;
8156     unsigned int new_el = env->exception.target_el;
8157     target_ulong addr = env->cp15.vbar_el[new_el];
8158     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
8159     unsigned int cur_el = arm_current_el(env);
8160 
8161     /*
8162      * Note that new_el can never be 0.  If cur_el is 0, then
8163      * el0_a64 is is_a64(), else el0_a64 is ignored.
8164      */
8165     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
8166 
8167     if (cur_el < new_el) {
8168         /* Entry vector offset depends on whether the implemented EL
8169          * immediately lower than the target level is using AArch32 or AArch64
8170          */
8171         bool is_aa64;
8172 
8173         switch (new_el) {
8174         case 3:
8175             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
8176             break;
8177         case 2:
8178             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
8179             break;
8180         case 1:
8181             is_aa64 = is_a64(env);
8182             break;
8183         default:
8184             g_assert_not_reached();
8185         }
8186 
8187         if (is_aa64) {
8188             addr += 0x400;
8189         } else {
8190             addr += 0x600;
8191         }
8192     } else if (pstate_read(env) & PSTATE_SP) {
8193         addr += 0x200;
8194     }
8195 
8196     switch (cs->exception_index) {
8197     case EXCP_PREFETCH_ABORT:
8198     case EXCP_DATA_ABORT:
8199         env->cp15.far_el[new_el] = env->exception.vaddress;
8200         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
8201                       env->cp15.far_el[new_el]);
8202         /* fall through */
8203     case EXCP_BKPT:
8204     case EXCP_UDEF:
8205     case EXCP_SWI:
8206     case EXCP_HVC:
8207     case EXCP_HYP_TRAP:
8208     case EXCP_SMC:
8209         if (syn_get_ec(env->exception.syndrome) == EC_ADVSIMDFPACCESSTRAP) {
8210             /*
8211              * QEMU internal FP/SIMD syndromes from AArch32 include the
8212              * TA and coproc fields which are only exposed if the exception
8213              * is taken to AArch32 Hyp mode. Mask them out to get a valid
8214              * AArch64 format syndrome.
8215              */
8216             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
8217         }
8218         env->cp15.esr_el[new_el] = env->exception.syndrome;
8219         break;
8220     case EXCP_IRQ:
8221     case EXCP_VIRQ:
8222         addr += 0x80;
8223         break;
8224     case EXCP_FIQ:
8225     case EXCP_VFIQ:
8226         addr += 0x100;
8227         break;
8228     case EXCP_SEMIHOST:
8229         qemu_log_mask(CPU_LOG_INT,
8230                       "...handling as semihosting call 0x%" PRIx64 "\n",
8231                       env->xregs[0]);
8232         env->xregs[0] = do_arm_semihosting(env);
8233         return;
8234     default:
8235         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8236     }
8237 
8238     if (is_a64(env)) {
8239         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
8240         aarch64_save_sp(env, arm_current_el(env));
8241         env->elr_el[new_el] = env->pc;
8242     } else {
8243         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
8244         env->elr_el[new_el] = env->regs[15];
8245 
8246         aarch64_sync_32_to_64(env);
8247 
8248         env->condexec_bits = 0;
8249     }
8250     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
8251                   env->elr_el[new_el]);
8252 
8253     pstate_write(env, PSTATE_DAIF | new_mode);
8254     env->aarch64 = 1;
8255     aarch64_restore_sp(env, new_el);
8256 
8257     env->pc = addr;
8258 
8259     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
8260                   new_el, env->pc, pstate_read(env));
8261 }
8262 
8263 static inline bool check_for_semihosting(CPUState *cs)
8264 {
8265 #ifdef CONFIG_TCG
8266     /* Check whether this exception is a semihosting call; if so
8267      * then handle it and return true; otherwise return false.
8268      */
8269     ARMCPU *cpu = ARM_CPU(cs);
8270     CPUARMState *env = &cpu->env;
8271 
8272     if (is_a64(env)) {
8273         if (cs->exception_index == EXCP_SEMIHOST) {
8274             /* This is always the 64-bit semihosting exception.
8275              * The "is this usermode" and "is semihosting enabled"
8276              * checks have been done at translate time.
8277              */
8278             qemu_log_mask(CPU_LOG_INT,
8279                           "...handling as semihosting call 0x%" PRIx64 "\n",
8280                           env->xregs[0]);
8281             env->xregs[0] = do_arm_semihosting(env);
8282             return true;
8283         }
8284         return false;
8285     } else {
8286         uint32_t imm;
8287 
8288         /* Only intercept calls from privileged modes, to provide some
8289          * semblance of security.
8290          */
8291         if (cs->exception_index != EXCP_SEMIHOST &&
8292             (!semihosting_enabled() ||
8293              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
8294             return false;
8295         }
8296 
8297         switch (cs->exception_index) {
8298         case EXCP_SEMIHOST:
8299             /* This is always a semihosting call; the "is this usermode"
8300              * and "is semihosting enabled" checks have been done at
8301              * translate time.
8302              */
8303             break;
8304         case EXCP_SWI:
8305             /* Check for semihosting interrupt.  */
8306             if (env->thumb) {
8307                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
8308                     & 0xff;
8309                 if (imm == 0xab) {
8310                     break;
8311                 }
8312             } else {
8313                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
8314                     & 0xffffff;
8315                 if (imm == 0x123456) {
8316                     break;
8317                 }
8318             }
8319             return false;
8320         case EXCP_BKPT:
8321             /* See if this is a semihosting syscall.  */
8322             if (env->thumb) {
8323                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
8324                     & 0xff;
8325                 if (imm == 0xab) {
8326                     env->regs[15] += 2;
8327                     break;
8328                 }
8329             }
8330             return false;
8331         default:
8332             return false;
8333         }
8334 
8335         qemu_log_mask(CPU_LOG_INT,
8336                       "...handling as semihosting call 0x%x\n",
8337                       env->regs[0]);
8338         env->regs[0] = do_arm_semihosting(env);
8339         return true;
8340     }
8341 #else
8342     return false;
8343 #endif
8344 }
8345 
8346 /* Handle a CPU exception for A and R profile CPUs.
8347  * Do any appropriate logging, handle PSCI calls, and then hand off
8348  * to the AArch64-entry or AArch32-entry function depending on the
8349  * target exception level's register width.
8350  */
8351 void arm_cpu_do_interrupt(CPUState *cs)
8352 {
8353     ARMCPU *cpu = ARM_CPU(cs);
8354     CPUARMState *env = &cpu->env;
8355     unsigned int new_el = env->exception.target_el;
8356 
8357     assert(!arm_feature(env, ARM_FEATURE_M));
8358 
8359     arm_log_exception(cs->exception_index);
8360     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
8361                   new_el);
8362     if (qemu_loglevel_mask(CPU_LOG_INT)
8363         && !excp_is_internal(cs->exception_index)) {
8364         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
8365                       syn_get_ec(env->exception.syndrome),
8366                       env->exception.syndrome);
8367     }
8368 
8369     if (arm_is_psci_call(cpu, cs->exception_index)) {
8370         arm_handle_psci_call(cpu);
8371         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
8372         return;
8373     }
8374 
8375     /* Semihosting semantics depend on the register width of the
8376      * code that caused the exception, not the target exception level,
8377      * so must be handled here.
8378      */
8379     if (check_for_semihosting(cs)) {
8380         return;
8381     }
8382 
8383     /* Hooks may change global state so BQL should be held, also the
8384      * BQL needs to be held for any modification of
8385      * cs->interrupt_request.
8386      */
8387     g_assert(qemu_mutex_iothread_locked());
8388 
8389     arm_call_pre_el_change_hook(cpu);
8390 
8391     assert(!excp_is_internal(cs->exception_index));
8392     if (arm_el_is_aa64(env, new_el)) {
8393         arm_cpu_do_interrupt_aarch64(cs);
8394     } else {
8395         arm_cpu_do_interrupt_aarch32(cs);
8396     }
8397 
8398     arm_call_el_change_hook(cpu);
8399 
8400     if (!kvm_enabled()) {
8401         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
8402     }
8403 }
8404 #endif /* !CONFIG_USER_ONLY */
8405 
8406 /* Return the exception level which controls this address translation regime */
8407 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
8408 {
8409     switch (mmu_idx) {
8410     case ARMMMUIdx_S2NS:
8411     case ARMMMUIdx_S1E2:
8412         return 2;
8413     case ARMMMUIdx_S1E3:
8414         return 3;
8415     case ARMMMUIdx_S1SE0:
8416         return arm_el_is_aa64(env, 3) ? 1 : 3;
8417     case ARMMMUIdx_S1SE1:
8418     case ARMMMUIdx_S1NSE0:
8419     case ARMMMUIdx_S1NSE1:
8420     case ARMMMUIdx_MPrivNegPri:
8421     case ARMMMUIdx_MUserNegPri:
8422     case ARMMMUIdx_MPriv:
8423     case ARMMMUIdx_MUser:
8424     case ARMMMUIdx_MSPrivNegPri:
8425     case ARMMMUIdx_MSUserNegPri:
8426     case ARMMMUIdx_MSPriv:
8427     case ARMMMUIdx_MSUser:
8428         return 1;
8429     default:
8430         g_assert_not_reached();
8431     }
8432 }
8433 
8434 #ifndef CONFIG_USER_ONLY
8435 
8436 /* Return the SCTLR value which controls this address translation regime */
8437 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
8438 {
8439     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
8440 }
8441 
8442 /* Return true if the specified stage of address translation is disabled */
8443 static inline bool regime_translation_disabled(CPUARMState *env,
8444                                                ARMMMUIdx mmu_idx)
8445 {
8446     if (arm_feature(env, ARM_FEATURE_M)) {
8447         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
8448                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
8449         case R_V7M_MPU_CTRL_ENABLE_MASK:
8450             /* Enabled, but not for HardFault and NMI */
8451             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
8452         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
8453             /* Enabled for all cases */
8454             return false;
8455         case 0:
8456         default:
8457             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
8458              * we warned about that in armv7m_nvic.c when the guest set it.
8459              */
8460             return true;
8461         }
8462     }
8463 
8464     if (mmu_idx == ARMMMUIdx_S2NS) {
8465         /* HCR.DC means HCR.VM behaves as 1 */
8466         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
8467     }
8468 
8469     if (env->cp15.hcr_el2 & HCR_TGE) {
8470         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
8471         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
8472             return true;
8473         }
8474     }
8475 
8476     if ((env->cp15.hcr_el2 & HCR_DC) &&
8477         (mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1)) {
8478         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
8479         return true;
8480     }
8481 
8482     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
8483 }
8484 
8485 static inline bool regime_translation_big_endian(CPUARMState *env,
8486                                                  ARMMMUIdx mmu_idx)
8487 {
8488     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
8489 }
8490 
8491 /* Return the TTBR associated with this translation regime */
8492 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
8493                                    int ttbrn)
8494 {
8495     if (mmu_idx == ARMMMUIdx_S2NS) {
8496         return env->cp15.vttbr_el2;
8497     }
8498     if (ttbrn == 0) {
8499         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
8500     } else {
8501         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
8502     }
8503 }
8504 
8505 #endif /* !CONFIG_USER_ONLY */
8506 
8507 /* Return the TCR controlling this translation regime */
8508 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
8509 {
8510     if (mmu_idx == ARMMMUIdx_S2NS) {
8511         return &env->cp15.vtcr_el2;
8512     }
8513     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
8514 }
8515 
8516 /* Convert a possible stage1+2 MMU index into the appropriate
8517  * stage 1 MMU index
8518  */
8519 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
8520 {
8521     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
8522         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
8523     }
8524     return mmu_idx;
8525 }
8526 
8527 /* Return true if the translation regime is using LPAE format page tables */
8528 static inline bool regime_using_lpae_format(CPUARMState *env,
8529                                             ARMMMUIdx mmu_idx)
8530 {
8531     int el = regime_el(env, mmu_idx);
8532     if (el == 2 || arm_el_is_aa64(env, el)) {
8533         return true;
8534     }
8535     if (arm_feature(env, ARM_FEATURE_LPAE)
8536         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
8537         return true;
8538     }
8539     return false;
8540 }
8541 
8542 /* Returns true if the stage 1 translation regime is using LPAE format page
8543  * tables. Used when raising alignment exceptions, whose FSR changes depending
8544  * on whether the long or short descriptor format is in use. */
8545 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
8546 {
8547     mmu_idx = stage_1_mmu_idx(mmu_idx);
8548 
8549     return regime_using_lpae_format(env, mmu_idx);
8550 }
8551 
8552 #ifndef CONFIG_USER_ONLY
8553 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
8554 {
8555     switch (mmu_idx) {
8556     case ARMMMUIdx_S1SE0:
8557     case ARMMMUIdx_S1NSE0:
8558     case ARMMMUIdx_MUser:
8559     case ARMMMUIdx_MSUser:
8560     case ARMMMUIdx_MUserNegPri:
8561     case ARMMMUIdx_MSUserNegPri:
8562         return true;
8563     default:
8564         return false;
8565     case ARMMMUIdx_S12NSE0:
8566     case ARMMMUIdx_S12NSE1:
8567         g_assert_not_reached();
8568     }
8569 }
8570 
8571 /* Translate section/page access permissions to page
8572  * R/W protection flags
8573  *
8574  * @env:         CPUARMState
8575  * @mmu_idx:     MMU index indicating required translation regime
8576  * @ap:          The 3-bit access permissions (AP[2:0])
8577  * @domain_prot: The 2-bit domain access permissions
8578  */
8579 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
8580                                 int ap, int domain_prot)
8581 {
8582     bool is_user = regime_is_user(env, mmu_idx);
8583 
8584     if (domain_prot == 3) {
8585         return PAGE_READ | PAGE_WRITE;
8586     }
8587 
8588     switch (ap) {
8589     case 0:
8590         if (arm_feature(env, ARM_FEATURE_V7)) {
8591             return 0;
8592         }
8593         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
8594         case SCTLR_S:
8595             return is_user ? 0 : PAGE_READ;
8596         case SCTLR_R:
8597             return PAGE_READ;
8598         default:
8599             return 0;
8600         }
8601     case 1:
8602         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8603     case 2:
8604         if (is_user) {
8605             return PAGE_READ;
8606         } else {
8607             return PAGE_READ | PAGE_WRITE;
8608         }
8609     case 3:
8610         return PAGE_READ | PAGE_WRITE;
8611     case 4: /* Reserved.  */
8612         return 0;
8613     case 5:
8614         return is_user ? 0 : PAGE_READ;
8615     case 6:
8616         return PAGE_READ;
8617     case 7:
8618         if (!arm_feature(env, ARM_FEATURE_V6K)) {
8619             return 0;
8620         }
8621         return PAGE_READ;
8622     default:
8623         g_assert_not_reached();
8624     }
8625 }
8626 
8627 /* Translate section/page access permissions to page
8628  * R/W protection flags.
8629  *
8630  * @ap:      The 2-bit simple AP (AP[2:1])
8631  * @is_user: TRUE if accessing from PL0
8632  */
8633 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
8634 {
8635     switch (ap) {
8636     case 0:
8637         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8638     case 1:
8639         return PAGE_READ | PAGE_WRITE;
8640     case 2:
8641         return is_user ? 0 : PAGE_READ;
8642     case 3:
8643         return PAGE_READ;
8644     default:
8645         g_assert_not_reached();
8646     }
8647 }
8648 
8649 static inline int
8650 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
8651 {
8652     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
8653 }
8654 
8655 /* Translate S2 section/page access permissions to protection flags
8656  *
8657  * @env:     CPUARMState
8658  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
8659  * @xn:      XN (execute-never) bit
8660  */
8661 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
8662 {
8663     int prot = 0;
8664 
8665     if (s2ap & 1) {
8666         prot |= PAGE_READ;
8667     }
8668     if (s2ap & 2) {
8669         prot |= PAGE_WRITE;
8670     }
8671     if (!xn) {
8672         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
8673             prot |= PAGE_EXEC;
8674         }
8675     }
8676     return prot;
8677 }
8678 
8679 /* Translate section/page access permissions to protection flags
8680  *
8681  * @env:     CPUARMState
8682  * @mmu_idx: MMU index indicating required translation regime
8683  * @is_aa64: TRUE if AArch64
8684  * @ap:      The 2-bit simple AP (AP[2:1])
8685  * @ns:      NS (non-secure) bit
8686  * @xn:      XN (execute-never) bit
8687  * @pxn:     PXN (privileged execute-never) bit
8688  */
8689 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
8690                       int ap, int ns, int xn, int pxn)
8691 {
8692     bool is_user = regime_is_user(env, mmu_idx);
8693     int prot_rw, user_rw;
8694     bool have_wxn;
8695     int wxn = 0;
8696 
8697     assert(mmu_idx != ARMMMUIdx_S2NS);
8698 
8699     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
8700     if (is_user) {
8701         prot_rw = user_rw;
8702     } else {
8703         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
8704     }
8705 
8706     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
8707         return prot_rw;
8708     }
8709 
8710     /* TODO have_wxn should be replaced with
8711      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
8712      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
8713      * compatible processors have EL2, which is required for [U]WXN.
8714      */
8715     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
8716 
8717     if (have_wxn) {
8718         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
8719     }
8720 
8721     if (is_aa64) {
8722         switch (regime_el(env, mmu_idx)) {
8723         case 1:
8724             if (!is_user) {
8725                 xn = pxn || (user_rw & PAGE_WRITE);
8726             }
8727             break;
8728         case 2:
8729         case 3:
8730             break;
8731         }
8732     } else if (arm_feature(env, ARM_FEATURE_V7)) {
8733         switch (regime_el(env, mmu_idx)) {
8734         case 1:
8735         case 3:
8736             if (is_user) {
8737                 xn = xn || !(user_rw & PAGE_READ);
8738             } else {
8739                 int uwxn = 0;
8740                 if (have_wxn) {
8741                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
8742                 }
8743                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
8744                      (uwxn && (user_rw & PAGE_WRITE));
8745             }
8746             break;
8747         case 2:
8748             break;
8749         }
8750     } else {
8751         xn = wxn = 0;
8752     }
8753 
8754     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
8755         return prot_rw;
8756     }
8757     return prot_rw | PAGE_EXEC;
8758 }
8759 
8760 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
8761                                      uint32_t *table, uint32_t address)
8762 {
8763     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
8764     TCR *tcr = regime_tcr(env, mmu_idx);
8765 
8766     if (address & tcr->mask) {
8767         if (tcr->raw_tcr & TTBCR_PD1) {
8768             /* Translation table walk disabled for TTBR1 */
8769             return false;
8770         }
8771         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
8772     } else {
8773         if (tcr->raw_tcr & TTBCR_PD0) {
8774             /* Translation table walk disabled for TTBR0 */
8775             return false;
8776         }
8777         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
8778     }
8779     *table |= (address >> 18) & 0x3ffc;
8780     return true;
8781 }
8782 
8783 /* Translate a S1 pagetable walk through S2 if needed.  */
8784 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
8785                                hwaddr addr, MemTxAttrs txattrs,
8786                                ARMMMUFaultInfo *fi)
8787 {
8788     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
8789         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
8790         target_ulong s2size;
8791         hwaddr s2pa;
8792         int s2prot;
8793         int ret;
8794         ARMCacheAttrs cacheattrs = {};
8795         ARMCacheAttrs *pcacheattrs = NULL;
8796 
8797         if (env->cp15.hcr_el2 & HCR_PTW) {
8798             /*
8799              * PTW means we must fault if this S1 walk touches S2 Device
8800              * memory; otherwise we don't care about the attributes and can
8801              * save the S2 translation the effort of computing them.
8802              */
8803             pcacheattrs = &cacheattrs;
8804         }
8805 
8806         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
8807                                  &txattrs, &s2prot, &s2size, fi, pcacheattrs);
8808         if (ret) {
8809             assert(fi->type != ARMFault_None);
8810             fi->s2addr = addr;
8811             fi->stage2 = true;
8812             fi->s1ptw = true;
8813             return ~0;
8814         }
8815         if (pcacheattrs && (pcacheattrs->attrs & 0xf0) == 0) {
8816             /* Access was to Device memory: generate Permission fault */
8817             fi->type = ARMFault_Permission;
8818             fi->s2addr = addr;
8819             fi->stage2 = true;
8820             fi->s1ptw = true;
8821             return ~0;
8822         }
8823         addr = s2pa;
8824     }
8825     return addr;
8826 }
8827 
8828 /* All loads done in the course of a page table walk go through here. */
8829 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8830                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8831 {
8832     ARMCPU *cpu = ARM_CPU(cs);
8833     CPUARMState *env = &cpu->env;
8834     MemTxAttrs attrs = {};
8835     MemTxResult result = MEMTX_OK;
8836     AddressSpace *as;
8837     uint32_t data;
8838 
8839     attrs.secure = is_secure;
8840     as = arm_addressspace(cs, attrs);
8841     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8842     if (fi->s1ptw) {
8843         return 0;
8844     }
8845     if (regime_translation_big_endian(env, mmu_idx)) {
8846         data = address_space_ldl_be(as, addr, attrs, &result);
8847     } else {
8848         data = address_space_ldl_le(as, addr, attrs, &result);
8849     }
8850     if (result == MEMTX_OK) {
8851         return data;
8852     }
8853     fi->type = ARMFault_SyncExternalOnWalk;
8854     fi->ea = arm_extabort_type(result);
8855     return 0;
8856 }
8857 
8858 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8859                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8860 {
8861     ARMCPU *cpu = ARM_CPU(cs);
8862     CPUARMState *env = &cpu->env;
8863     MemTxAttrs attrs = {};
8864     MemTxResult result = MEMTX_OK;
8865     AddressSpace *as;
8866     uint64_t data;
8867 
8868     attrs.secure = is_secure;
8869     as = arm_addressspace(cs, attrs);
8870     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8871     if (fi->s1ptw) {
8872         return 0;
8873     }
8874     if (regime_translation_big_endian(env, mmu_idx)) {
8875         data = address_space_ldq_be(as, addr, attrs, &result);
8876     } else {
8877         data = address_space_ldq_le(as, addr, attrs, &result);
8878     }
8879     if (result == MEMTX_OK) {
8880         return data;
8881     }
8882     fi->type = ARMFault_SyncExternalOnWalk;
8883     fi->ea = arm_extabort_type(result);
8884     return 0;
8885 }
8886 
8887 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
8888                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8889                              hwaddr *phys_ptr, int *prot,
8890                              target_ulong *page_size,
8891                              ARMMMUFaultInfo *fi)
8892 {
8893     CPUState *cs = env_cpu(env);
8894     int level = 1;
8895     uint32_t table;
8896     uint32_t desc;
8897     int type;
8898     int ap;
8899     int domain = 0;
8900     int domain_prot;
8901     hwaddr phys_addr;
8902     uint32_t dacr;
8903 
8904     /* Pagetable walk.  */
8905     /* Lookup l1 descriptor.  */
8906     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8907         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8908         fi->type = ARMFault_Translation;
8909         goto do_fault;
8910     }
8911     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8912                        mmu_idx, fi);
8913     if (fi->type != ARMFault_None) {
8914         goto do_fault;
8915     }
8916     type = (desc & 3);
8917     domain = (desc >> 5) & 0x0f;
8918     if (regime_el(env, mmu_idx) == 1) {
8919         dacr = env->cp15.dacr_ns;
8920     } else {
8921         dacr = env->cp15.dacr_s;
8922     }
8923     domain_prot = (dacr >> (domain * 2)) & 3;
8924     if (type == 0) {
8925         /* Section translation fault.  */
8926         fi->type = ARMFault_Translation;
8927         goto do_fault;
8928     }
8929     if (type != 2) {
8930         level = 2;
8931     }
8932     if (domain_prot == 0 || domain_prot == 2) {
8933         fi->type = ARMFault_Domain;
8934         goto do_fault;
8935     }
8936     if (type == 2) {
8937         /* 1Mb section.  */
8938         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
8939         ap = (desc >> 10) & 3;
8940         *page_size = 1024 * 1024;
8941     } else {
8942         /* Lookup l2 entry.  */
8943         if (type == 1) {
8944             /* Coarse pagetable.  */
8945             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
8946         } else {
8947             /* Fine pagetable.  */
8948             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
8949         }
8950         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8951                            mmu_idx, fi);
8952         if (fi->type != ARMFault_None) {
8953             goto do_fault;
8954         }
8955         switch (desc & 3) {
8956         case 0: /* Page translation fault.  */
8957             fi->type = ARMFault_Translation;
8958             goto do_fault;
8959         case 1: /* 64k page.  */
8960             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
8961             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
8962             *page_size = 0x10000;
8963             break;
8964         case 2: /* 4k page.  */
8965             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8966             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
8967             *page_size = 0x1000;
8968             break;
8969         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
8970             if (type == 1) {
8971                 /* ARMv6/XScale extended small page format */
8972                 if (arm_feature(env, ARM_FEATURE_XSCALE)
8973                     || arm_feature(env, ARM_FEATURE_V6)) {
8974                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8975                     *page_size = 0x1000;
8976                 } else {
8977                     /* UNPREDICTABLE in ARMv5; we choose to take a
8978                      * page translation fault.
8979                      */
8980                     fi->type = ARMFault_Translation;
8981                     goto do_fault;
8982                 }
8983             } else {
8984                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
8985                 *page_size = 0x400;
8986             }
8987             ap = (desc >> 4) & 3;
8988             break;
8989         default:
8990             /* Never happens, but compiler isn't smart enough to tell.  */
8991             abort();
8992         }
8993     }
8994     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
8995     *prot |= *prot ? PAGE_EXEC : 0;
8996     if (!(*prot & (1 << access_type))) {
8997         /* Access permission fault.  */
8998         fi->type = ARMFault_Permission;
8999         goto do_fault;
9000     }
9001     *phys_ptr = phys_addr;
9002     return false;
9003 do_fault:
9004     fi->domain = domain;
9005     fi->level = level;
9006     return true;
9007 }
9008 
9009 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
9010                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
9011                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
9012                              target_ulong *page_size, ARMMMUFaultInfo *fi)
9013 {
9014     CPUState *cs = env_cpu(env);
9015     int level = 1;
9016     uint32_t table;
9017     uint32_t desc;
9018     uint32_t xn;
9019     uint32_t pxn = 0;
9020     int type;
9021     int ap;
9022     int domain = 0;
9023     int domain_prot;
9024     hwaddr phys_addr;
9025     uint32_t dacr;
9026     bool ns;
9027 
9028     /* Pagetable walk.  */
9029     /* Lookup l1 descriptor.  */
9030     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
9031         /* Section translation fault if page walk is disabled by PD0 or PD1 */
9032         fi->type = ARMFault_Translation;
9033         goto do_fault;
9034     }
9035     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9036                        mmu_idx, fi);
9037     if (fi->type != ARMFault_None) {
9038         goto do_fault;
9039     }
9040     type = (desc & 3);
9041     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
9042         /* Section translation fault, or attempt to use the encoding
9043          * which is Reserved on implementations without PXN.
9044          */
9045         fi->type = ARMFault_Translation;
9046         goto do_fault;
9047     }
9048     if ((type == 1) || !(desc & (1 << 18))) {
9049         /* Page or Section.  */
9050         domain = (desc >> 5) & 0x0f;
9051     }
9052     if (regime_el(env, mmu_idx) == 1) {
9053         dacr = env->cp15.dacr_ns;
9054     } else {
9055         dacr = env->cp15.dacr_s;
9056     }
9057     if (type == 1) {
9058         level = 2;
9059     }
9060     domain_prot = (dacr >> (domain * 2)) & 3;
9061     if (domain_prot == 0 || domain_prot == 2) {
9062         /* Section or Page domain fault */
9063         fi->type = ARMFault_Domain;
9064         goto do_fault;
9065     }
9066     if (type != 1) {
9067         if (desc & (1 << 18)) {
9068             /* Supersection.  */
9069             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
9070             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
9071             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
9072             *page_size = 0x1000000;
9073         } else {
9074             /* Section.  */
9075             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
9076             *page_size = 0x100000;
9077         }
9078         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
9079         xn = desc & (1 << 4);
9080         pxn = desc & 1;
9081         ns = extract32(desc, 19, 1);
9082     } else {
9083         if (arm_feature(env, ARM_FEATURE_PXN)) {
9084             pxn = (desc >> 2) & 1;
9085         }
9086         ns = extract32(desc, 3, 1);
9087         /* Lookup l2 entry.  */
9088         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
9089         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9090                            mmu_idx, fi);
9091         if (fi->type != ARMFault_None) {
9092             goto do_fault;
9093         }
9094         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
9095         switch (desc & 3) {
9096         case 0: /* Page translation fault.  */
9097             fi->type = ARMFault_Translation;
9098             goto do_fault;
9099         case 1: /* 64k page.  */
9100             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
9101             xn = desc & (1 << 15);
9102             *page_size = 0x10000;
9103             break;
9104         case 2: case 3: /* 4k page.  */
9105             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9106             xn = desc & 1;
9107             *page_size = 0x1000;
9108             break;
9109         default:
9110             /* Never happens, but compiler isn't smart enough to tell.  */
9111             abort();
9112         }
9113     }
9114     if (domain_prot == 3) {
9115         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9116     } else {
9117         if (pxn && !regime_is_user(env, mmu_idx)) {
9118             xn = 1;
9119         }
9120         if (xn && access_type == MMU_INST_FETCH) {
9121             fi->type = ARMFault_Permission;
9122             goto do_fault;
9123         }
9124 
9125         if (arm_feature(env, ARM_FEATURE_V6K) &&
9126                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
9127             /* The simplified model uses AP[0] as an access control bit.  */
9128             if ((ap & 1) == 0) {
9129                 /* Access flag fault.  */
9130                 fi->type = ARMFault_AccessFlag;
9131                 goto do_fault;
9132             }
9133             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
9134         } else {
9135             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9136         }
9137         if (*prot && !xn) {
9138             *prot |= PAGE_EXEC;
9139         }
9140         if (!(*prot & (1 << access_type))) {
9141             /* Access permission fault.  */
9142             fi->type = ARMFault_Permission;
9143             goto do_fault;
9144         }
9145     }
9146     if (ns) {
9147         /* The NS bit will (as required by the architecture) have no effect if
9148          * the CPU doesn't support TZ or this is a non-secure translation
9149          * regime, because the attribute will already be non-secure.
9150          */
9151         attrs->secure = false;
9152     }
9153     *phys_ptr = phys_addr;
9154     return false;
9155 do_fault:
9156     fi->domain = domain;
9157     fi->level = level;
9158     return true;
9159 }
9160 
9161 /*
9162  * check_s2_mmu_setup
9163  * @cpu:        ARMCPU
9164  * @is_aa64:    True if the translation regime is in AArch64 state
9165  * @startlevel: Suggested starting level
9166  * @inputsize:  Bitsize of IPAs
9167  * @stride:     Page-table stride (See the ARM ARM)
9168  *
9169  * Returns true if the suggested S2 translation parameters are OK and
9170  * false otherwise.
9171  */
9172 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
9173                                int inputsize, int stride)
9174 {
9175     const int grainsize = stride + 3;
9176     int startsizecheck;
9177 
9178     /* Negative levels are never allowed.  */
9179     if (level < 0) {
9180         return false;
9181     }
9182 
9183     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
9184     if (startsizecheck < 1 || startsizecheck > stride + 4) {
9185         return false;
9186     }
9187 
9188     if (is_aa64) {
9189         CPUARMState *env = &cpu->env;
9190         unsigned int pamax = arm_pamax(cpu);
9191 
9192         switch (stride) {
9193         case 13: /* 64KB Pages.  */
9194             if (level == 0 || (level == 1 && pamax <= 42)) {
9195                 return false;
9196             }
9197             break;
9198         case 11: /* 16KB Pages.  */
9199             if (level == 0 || (level == 1 && pamax <= 40)) {
9200                 return false;
9201             }
9202             break;
9203         case 9: /* 4KB Pages.  */
9204             if (level == 0 && pamax <= 42) {
9205                 return false;
9206             }
9207             break;
9208         default:
9209             g_assert_not_reached();
9210         }
9211 
9212         /* Inputsize checks.  */
9213         if (inputsize > pamax &&
9214             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
9215             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
9216             return false;
9217         }
9218     } else {
9219         /* AArch32 only supports 4KB pages. Assert on that.  */
9220         assert(stride == 9);
9221 
9222         if (level == 0) {
9223             return false;
9224         }
9225     }
9226     return true;
9227 }
9228 
9229 /* Translate from the 4-bit stage 2 representation of
9230  * memory attributes (without cache-allocation hints) to
9231  * the 8-bit representation of the stage 1 MAIR registers
9232  * (which includes allocation hints).
9233  *
9234  * ref: shared/translation/attrs/S2AttrDecode()
9235  *      .../S2ConvertAttrsHints()
9236  */
9237 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
9238 {
9239     uint8_t hiattr = extract32(s2attrs, 2, 2);
9240     uint8_t loattr = extract32(s2attrs, 0, 2);
9241     uint8_t hihint = 0, lohint = 0;
9242 
9243     if (hiattr != 0) { /* normal memory */
9244         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
9245             hiattr = loattr = 1; /* non-cacheable */
9246         } else {
9247             if (hiattr != 1) { /* Write-through or write-back */
9248                 hihint = 3; /* RW allocate */
9249             }
9250             if (loattr != 1) { /* Write-through or write-back */
9251                 lohint = 3; /* RW allocate */
9252             }
9253         }
9254     }
9255 
9256     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
9257 }
9258 #endif /* !CONFIG_USER_ONLY */
9259 
9260 ARMVAParameters aa64_va_parameters_both(CPUARMState *env, uint64_t va,
9261                                         ARMMMUIdx mmu_idx)
9262 {
9263     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
9264     uint32_t el = regime_el(env, mmu_idx);
9265     bool tbi, tbid, epd, hpd, using16k, using64k;
9266     int select, tsz;
9267 
9268     /*
9269      * Bit 55 is always between the two regions, and is canonical for
9270      * determining if address tagging is enabled.
9271      */
9272     select = extract64(va, 55, 1);
9273 
9274     if (el > 1) {
9275         tsz = extract32(tcr, 0, 6);
9276         using64k = extract32(tcr, 14, 1);
9277         using16k = extract32(tcr, 15, 1);
9278         if (mmu_idx == ARMMMUIdx_S2NS) {
9279             /* VTCR_EL2 */
9280             tbi = tbid = hpd = false;
9281         } else {
9282             tbi = extract32(tcr, 20, 1);
9283             hpd = extract32(tcr, 24, 1);
9284             tbid = extract32(tcr, 29, 1);
9285         }
9286         epd = false;
9287     } else if (!select) {
9288         tsz = extract32(tcr, 0, 6);
9289         epd = extract32(tcr, 7, 1);
9290         using64k = extract32(tcr, 14, 1);
9291         using16k = extract32(tcr, 15, 1);
9292         tbi = extract64(tcr, 37, 1);
9293         hpd = extract64(tcr, 41, 1);
9294         tbid = extract64(tcr, 51, 1);
9295     } else {
9296         int tg = extract32(tcr, 30, 2);
9297         using16k = tg == 1;
9298         using64k = tg == 3;
9299         tsz = extract32(tcr, 16, 6);
9300         epd = extract32(tcr, 23, 1);
9301         tbi = extract64(tcr, 38, 1);
9302         hpd = extract64(tcr, 42, 1);
9303         tbid = extract64(tcr, 52, 1);
9304     }
9305     tsz = MIN(tsz, 39);  /* TODO: ARMv8.4-TTST */
9306     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
9307 
9308     return (ARMVAParameters) {
9309         .tsz = tsz,
9310         .select = select,
9311         .tbi = tbi,
9312         .tbid = tbid,
9313         .epd = epd,
9314         .hpd = hpd,
9315         .using16k = using16k,
9316         .using64k = using64k,
9317     };
9318 }
9319 
9320 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
9321                                    ARMMMUIdx mmu_idx, bool data)
9322 {
9323     ARMVAParameters ret = aa64_va_parameters_both(env, va, mmu_idx);
9324 
9325     /* Present TBI as a composite with TBID.  */
9326     ret.tbi &= (data || !ret.tbid);
9327     return ret;
9328 }
9329 
9330 #ifndef CONFIG_USER_ONLY
9331 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
9332                                           ARMMMUIdx mmu_idx)
9333 {
9334     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
9335     uint32_t el = regime_el(env, mmu_idx);
9336     int select, tsz;
9337     bool epd, hpd;
9338 
9339     if (mmu_idx == ARMMMUIdx_S2NS) {
9340         /* VTCR */
9341         bool sext = extract32(tcr, 4, 1);
9342         bool sign = extract32(tcr, 3, 1);
9343 
9344         /*
9345          * If the sign-extend bit is not the same as t0sz[3], the result
9346          * is unpredictable. Flag this as a guest error.
9347          */
9348         if (sign != sext) {
9349             qemu_log_mask(LOG_GUEST_ERROR,
9350                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
9351         }
9352         tsz = sextract32(tcr, 0, 4) + 8;
9353         select = 0;
9354         hpd = false;
9355         epd = false;
9356     } else if (el == 2) {
9357         /* HTCR */
9358         tsz = extract32(tcr, 0, 3);
9359         select = 0;
9360         hpd = extract64(tcr, 24, 1);
9361         epd = false;
9362     } else {
9363         int t0sz = extract32(tcr, 0, 3);
9364         int t1sz = extract32(tcr, 16, 3);
9365 
9366         if (t1sz == 0) {
9367             select = va > (0xffffffffu >> t0sz);
9368         } else {
9369             /* Note that we will detect errors later.  */
9370             select = va >= ~(0xffffffffu >> t1sz);
9371         }
9372         if (!select) {
9373             tsz = t0sz;
9374             epd = extract32(tcr, 7, 1);
9375             hpd = extract64(tcr, 41, 1);
9376         } else {
9377             tsz = t1sz;
9378             epd = extract32(tcr, 23, 1);
9379             hpd = extract64(tcr, 42, 1);
9380         }
9381         /* For aarch32, hpd0 is not enabled without t2e as well.  */
9382         hpd &= extract32(tcr, 6, 1);
9383     }
9384 
9385     return (ARMVAParameters) {
9386         .tsz = tsz,
9387         .select = select,
9388         .epd = epd,
9389         .hpd = hpd,
9390     };
9391 }
9392 
9393 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
9394                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
9395                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
9396                                target_ulong *page_size_ptr,
9397                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
9398 {
9399     ARMCPU *cpu = env_archcpu(env);
9400     CPUState *cs = CPU(cpu);
9401     /* Read an LPAE long-descriptor translation table. */
9402     ARMFaultType fault_type = ARMFault_Translation;
9403     uint32_t level;
9404     ARMVAParameters param;
9405     uint64_t ttbr;
9406     hwaddr descaddr, indexmask, indexmask_grainsize;
9407     uint32_t tableattrs;
9408     target_ulong page_size;
9409     uint32_t attrs;
9410     int32_t stride;
9411     int addrsize, inputsize;
9412     TCR *tcr = regime_tcr(env, mmu_idx);
9413     int ap, ns, xn, pxn;
9414     uint32_t el = regime_el(env, mmu_idx);
9415     bool ttbr1_valid;
9416     uint64_t descaddrmask;
9417     bool aarch64 = arm_el_is_aa64(env, el);
9418     bool guarded = false;
9419 
9420     /* TODO:
9421      * This code does not handle the different format TCR for VTCR_EL2.
9422      * This code also does not support shareability levels.
9423      * Attribute and permission bit handling should also be checked when adding
9424      * support for those page table walks.
9425      */
9426     if (aarch64) {
9427         param = aa64_va_parameters(env, address, mmu_idx,
9428                                    access_type != MMU_INST_FETCH);
9429         level = 0;
9430         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
9431          * invalid.
9432          */
9433         ttbr1_valid = (el < 2);
9434         addrsize = 64 - 8 * param.tbi;
9435         inputsize = 64 - param.tsz;
9436     } else {
9437         param = aa32_va_parameters(env, address, mmu_idx);
9438         level = 1;
9439         /* There is no TTBR1 for EL2 */
9440         ttbr1_valid = (el != 2);
9441         addrsize = (mmu_idx == ARMMMUIdx_S2NS ? 40 : 32);
9442         inputsize = addrsize - param.tsz;
9443     }
9444 
9445     /*
9446      * We determined the region when collecting the parameters, but we
9447      * have not yet validated that the address is valid for the region.
9448      * Extract the top bits and verify that they all match select.
9449      *
9450      * For aa32, if inputsize == addrsize, then we have selected the
9451      * region by exclusion in aa32_va_parameters and there is no more
9452      * validation to do here.
9453      */
9454     if (inputsize < addrsize) {
9455         target_ulong top_bits = sextract64(address, inputsize,
9456                                            addrsize - inputsize);
9457         if (-top_bits != param.select || (param.select && !ttbr1_valid)) {
9458             /* The gap between the two regions is a Translation fault */
9459             fault_type = ARMFault_Translation;
9460             goto do_fault;
9461         }
9462     }
9463 
9464     if (param.using64k) {
9465         stride = 13;
9466     } else if (param.using16k) {
9467         stride = 11;
9468     } else {
9469         stride = 9;
9470     }
9471 
9472     /* Note that QEMU ignores shareability and cacheability attributes,
9473      * so we don't need to do anything with the SH, ORGN, IRGN fields
9474      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
9475      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
9476      * implement any ASID-like capability so we can ignore it (instead
9477      * we will always flush the TLB any time the ASID is changed).
9478      */
9479     ttbr = regime_ttbr(env, mmu_idx, param.select);
9480 
9481     /* Here we should have set up all the parameters for the translation:
9482      * inputsize, ttbr, epd, stride, tbi
9483      */
9484 
9485     if (param.epd) {
9486         /* Translation table walk disabled => Translation fault on TLB miss
9487          * Note: This is always 0 on 64-bit EL2 and EL3.
9488          */
9489         goto do_fault;
9490     }
9491 
9492     if (mmu_idx != ARMMMUIdx_S2NS) {
9493         /* The starting level depends on the virtual address size (which can
9494          * be up to 48 bits) and the translation granule size. It indicates
9495          * the number of strides (stride bits at a time) needed to
9496          * consume the bits of the input address. In the pseudocode this is:
9497          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
9498          * where their 'inputsize' is our 'inputsize', 'grainsize' is
9499          * our 'stride + 3' and 'stride' is our 'stride'.
9500          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
9501          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
9502          * = 4 - (inputsize - 4) / stride;
9503          */
9504         level = 4 - (inputsize - 4) / stride;
9505     } else {
9506         /* For stage 2 translations the starting level is specified by the
9507          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
9508          */
9509         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
9510         uint32_t startlevel;
9511         bool ok;
9512 
9513         if (!aarch64 || stride == 9) {
9514             /* AArch32 or 4KB pages */
9515             startlevel = 2 - sl0;
9516         } else {
9517             /* 16KB or 64KB pages */
9518             startlevel = 3 - sl0;
9519         }
9520 
9521         /* Check that the starting level is valid. */
9522         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
9523                                 inputsize, stride);
9524         if (!ok) {
9525             fault_type = ARMFault_Translation;
9526             goto do_fault;
9527         }
9528         level = startlevel;
9529     }
9530 
9531     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
9532     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
9533 
9534     /* Now we can extract the actual base address from the TTBR */
9535     descaddr = extract64(ttbr, 0, 48);
9536     descaddr &= ~indexmask;
9537 
9538     /* The address field in the descriptor goes up to bit 39 for ARMv7
9539      * but up to bit 47 for ARMv8, but we use the descaddrmask
9540      * up to bit 39 for AArch32, because we don't need other bits in that case
9541      * to construct next descriptor address (anyway they should be all zeroes).
9542      */
9543     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
9544                    ~indexmask_grainsize;
9545 
9546     /* Secure accesses start with the page table in secure memory and
9547      * can be downgraded to non-secure at any step. Non-secure accesses
9548      * remain non-secure. We implement this by just ORing in the NSTable/NS
9549      * bits at each step.
9550      */
9551     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
9552     for (;;) {
9553         uint64_t descriptor;
9554         bool nstable;
9555 
9556         descaddr |= (address >> (stride * (4 - level))) & indexmask;
9557         descaddr &= ~7ULL;
9558         nstable = extract32(tableattrs, 4, 1);
9559         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
9560         if (fi->type != ARMFault_None) {
9561             goto do_fault;
9562         }
9563 
9564         if (!(descriptor & 1) ||
9565             (!(descriptor & 2) && (level == 3))) {
9566             /* Invalid, or the Reserved level 3 encoding */
9567             goto do_fault;
9568         }
9569         descaddr = descriptor & descaddrmask;
9570 
9571         if ((descriptor & 2) && (level < 3)) {
9572             /* Table entry. The top five bits are attributes which may
9573              * propagate down through lower levels of the table (and
9574              * which are all arranged so that 0 means "no effect", so
9575              * we can gather them up by ORing in the bits at each level).
9576              */
9577             tableattrs |= extract64(descriptor, 59, 5);
9578             level++;
9579             indexmask = indexmask_grainsize;
9580             continue;
9581         }
9582         /* Block entry at level 1 or 2, or page entry at level 3.
9583          * These are basically the same thing, although the number
9584          * of bits we pull in from the vaddr varies.
9585          */
9586         page_size = (1ULL << ((stride * (4 - level)) + 3));
9587         descaddr |= (address & (page_size - 1));
9588         /* Extract attributes from the descriptor */
9589         attrs = extract64(descriptor, 2, 10)
9590             | (extract64(descriptor, 52, 12) << 10);
9591 
9592         if (mmu_idx == ARMMMUIdx_S2NS) {
9593             /* Stage 2 table descriptors do not include any attribute fields */
9594             break;
9595         }
9596         /* Merge in attributes from table descriptors */
9597         attrs |= nstable << 3; /* NS */
9598         guarded = extract64(descriptor, 50, 1);  /* GP */
9599         if (param.hpd) {
9600             /* HPD disables all the table attributes except NSTable.  */
9601             break;
9602         }
9603         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
9604         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
9605          * means "force PL1 access only", which means forcing AP[1] to 0.
9606          */
9607         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
9608         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
9609         break;
9610     }
9611     /* Here descaddr is the final physical address, and attributes
9612      * are all in attrs.
9613      */
9614     fault_type = ARMFault_AccessFlag;
9615     if ((attrs & (1 << 8)) == 0) {
9616         /* Access flag */
9617         goto do_fault;
9618     }
9619 
9620     ap = extract32(attrs, 4, 2);
9621     xn = extract32(attrs, 12, 1);
9622 
9623     if (mmu_idx == ARMMMUIdx_S2NS) {
9624         ns = true;
9625         *prot = get_S2prot(env, ap, xn);
9626     } else {
9627         ns = extract32(attrs, 3, 1);
9628         pxn = extract32(attrs, 11, 1);
9629         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
9630     }
9631 
9632     fault_type = ARMFault_Permission;
9633     if (!(*prot & (1 << access_type))) {
9634         goto do_fault;
9635     }
9636 
9637     if (ns) {
9638         /* The NS bit will (as required by the architecture) have no effect if
9639          * the CPU doesn't support TZ or this is a non-secure translation
9640          * regime, because the attribute will already be non-secure.
9641          */
9642         txattrs->secure = false;
9643     }
9644     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
9645     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
9646         txattrs->target_tlb_bit0 = true;
9647     }
9648 
9649     if (cacheattrs != NULL) {
9650         if (mmu_idx == ARMMMUIdx_S2NS) {
9651             cacheattrs->attrs = convert_stage2_attrs(env,
9652                                                      extract32(attrs, 0, 4));
9653         } else {
9654             /* Index into MAIR registers for cache attributes */
9655             uint8_t attrindx = extract32(attrs, 0, 3);
9656             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
9657             assert(attrindx <= 7);
9658             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
9659         }
9660         cacheattrs->shareability = extract32(attrs, 6, 2);
9661     }
9662 
9663     *phys_ptr = descaddr;
9664     *page_size_ptr = page_size;
9665     return false;
9666 
9667 do_fault:
9668     fi->type = fault_type;
9669     fi->level = level;
9670     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
9671     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
9672     return true;
9673 }
9674 
9675 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
9676                                                 ARMMMUIdx mmu_idx,
9677                                                 int32_t address, int *prot)
9678 {
9679     if (!arm_feature(env, ARM_FEATURE_M)) {
9680         *prot = PAGE_READ | PAGE_WRITE;
9681         switch (address) {
9682         case 0xF0000000 ... 0xFFFFFFFF:
9683             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
9684                 /* hivecs execing is ok */
9685                 *prot |= PAGE_EXEC;
9686             }
9687             break;
9688         case 0x00000000 ... 0x7FFFFFFF:
9689             *prot |= PAGE_EXEC;
9690             break;
9691         }
9692     } else {
9693         /* Default system address map for M profile cores.
9694          * The architecture specifies which regions are execute-never;
9695          * at the MPU level no other checks are defined.
9696          */
9697         switch (address) {
9698         case 0x00000000 ... 0x1fffffff: /* ROM */
9699         case 0x20000000 ... 0x3fffffff: /* SRAM */
9700         case 0x60000000 ... 0x7fffffff: /* RAM */
9701         case 0x80000000 ... 0x9fffffff: /* RAM */
9702             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9703             break;
9704         case 0x40000000 ... 0x5fffffff: /* Peripheral */
9705         case 0xa0000000 ... 0xbfffffff: /* Device */
9706         case 0xc0000000 ... 0xdfffffff: /* Device */
9707         case 0xe0000000 ... 0xffffffff: /* System */
9708             *prot = PAGE_READ | PAGE_WRITE;
9709             break;
9710         default:
9711             g_assert_not_reached();
9712         }
9713     }
9714 }
9715 
9716 static bool pmsav7_use_background_region(ARMCPU *cpu,
9717                                          ARMMMUIdx mmu_idx, bool is_user)
9718 {
9719     /* Return true if we should use the default memory map as a
9720      * "background" region if there are no hits against any MPU regions.
9721      */
9722     CPUARMState *env = &cpu->env;
9723 
9724     if (is_user) {
9725         return false;
9726     }
9727 
9728     if (arm_feature(env, ARM_FEATURE_M)) {
9729         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
9730             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
9731     } else {
9732         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
9733     }
9734 }
9735 
9736 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
9737 {
9738     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
9739     return arm_feature(env, ARM_FEATURE_M) &&
9740         extract32(address, 20, 12) == 0xe00;
9741 }
9742 
9743 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
9744 {
9745     /* True if address is in the M profile system region
9746      * 0xe0000000 - 0xffffffff
9747      */
9748     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
9749 }
9750 
9751 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
9752                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9753                                  hwaddr *phys_ptr, int *prot,
9754                                  target_ulong *page_size,
9755                                  ARMMMUFaultInfo *fi)
9756 {
9757     ARMCPU *cpu = env_archcpu(env);
9758     int n;
9759     bool is_user = regime_is_user(env, mmu_idx);
9760 
9761     *phys_ptr = address;
9762     *page_size = TARGET_PAGE_SIZE;
9763     *prot = 0;
9764 
9765     if (regime_translation_disabled(env, mmu_idx) ||
9766         m_is_ppb_region(env, address)) {
9767         /* MPU disabled or M profile PPB access: use default memory map.
9768          * The other case which uses the default memory map in the
9769          * v7M ARM ARM pseudocode is exception vector reads from the vector
9770          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
9771          * which always does a direct read using address_space_ldl(), rather
9772          * than going via this function, so we don't need to check that here.
9773          */
9774         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9775     } else { /* MPU enabled */
9776         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9777             /* region search */
9778             uint32_t base = env->pmsav7.drbar[n];
9779             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
9780             uint32_t rmask;
9781             bool srdis = false;
9782 
9783             if (!(env->pmsav7.drsr[n] & 0x1)) {
9784                 continue;
9785             }
9786 
9787             if (!rsize) {
9788                 qemu_log_mask(LOG_GUEST_ERROR,
9789                               "DRSR[%d]: Rsize field cannot be 0\n", n);
9790                 continue;
9791             }
9792             rsize++;
9793             rmask = (1ull << rsize) - 1;
9794 
9795             if (base & rmask) {
9796                 qemu_log_mask(LOG_GUEST_ERROR,
9797                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
9798                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
9799                               n, base, rmask);
9800                 continue;
9801             }
9802 
9803             if (address < base || address > base + rmask) {
9804                 /*
9805                  * Address not in this region. We must check whether the
9806                  * region covers addresses in the same page as our address.
9807                  * In that case we must not report a size that covers the
9808                  * whole page for a subsequent hit against a different MPU
9809                  * region or the background region, because it would result in
9810                  * incorrect TLB hits for subsequent accesses to addresses that
9811                  * are in this MPU region.
9812                  */
9813                 if (ranges_overlap(base, rmask,
9814                                    address & TARGET_PAGE_MASK,
9815                                    TARGET_PAGE_SIZE)) {
9816                     *page_size = 1;
9817                 }
9818                 continue;
9819             }
9820 
9821             /* Region matched */
9822 
9823             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
9824                 int i, snd;
9825                 uint32_t srdis_mask;
9826 
9827                 rsize -= 3; /* sub region size (power of 2) */
9828                 snd = ((address - base) >> rsize) & 0x7;
9829                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
9830 
9831                 srdis_mask = srdis ? 0x3 : 0x0;
9832                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
9833                     /* This will check in groups of 2, 4 and then 8, whether
9834                      * the subregion bits are consistent. rsize is incremented
9835                      * back up to give the region size, considering consistent
9836                      * adjacent subregions as one region. Stop testing if rsize
9837                      * is already big enough for an entire QEMU page.
9838                      */
9839                     int snd_rounded = snd & ~(i - 1);
9840                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
9841                                                      snd_rounded + 8, i);
9842                     if (srdis_mask ^ srdis_multi) {
9843                         break;
9844                     }
9845                     srdis_mask = (srdis_mask << i) | srdis_mask;
9846                     rsize++;
9847                 }
9848             }
9849             if (srdis) {
9850                 continue;
9851             }
9852             if (rsize < TARGET_PAGE_BITS) {
9853                 *page_size = 1 << rsize;
9854             }
9855             break;
9856         }
9857 
9858         if (n == -1) { /* no hits */
9859             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9860                 /* background fault */
9861                 fi->type = ARMFault_Background;
9862                 return true;
9863             }
9864             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9865         } else { /* a MPU hit! */
9866             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
9867             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
9868 
9869             if (m_is_system_region(env, address)) {
9870                 /* System space is always execute never */
9871                 xn = 1;
9872             }
9873 
9874             if (is_user) { /* User mode AP bit decoding */
9875                 switch (ap) {
9876                 case 0:
9877                 case 1:
9878                 case 5:
9879                     break; /* no access */
9880                 case 3:
9881                     *prot |= PAGE_WRITE;
9882                     /* fall through */
9883                 case 2:
9884                 case 6:
9885                     *prot |= PAGE_READ | PAGE_EXEC;
9886                     break;
9887                 case 7:
9888                     /* for v7M, same as 6; for R profile a reserved value */
9889                     if (arm_feature(env, ARM_FEATURE_M)) {
9890                         *prot |= PAGE_READ | PAGE_EXEC;
9891                         break;
9892                     }
9893                     /* fall through */
9894                 default:
9895                     qemu_log_mask(LOG_GUEST_ERROR,
9896                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9897                                   PRIx32 "\n", n, ap);
9898                 }
9899             } else { /* Priv. mode AP bits decoding */
9900                 switch (ap) {
9901                 case 0:
9902                     break; /* no access */
9903                 case 1:
9904                 case 2:
9905                 case 3:
9906                     *prot |= PAGE_WRITE;
9907                     /* fall through */
9908                 case 5:
9909                 case 6:
9910                     *prot |= PAGE_READ | PAGE_EXEC;
9911                     break;
9912                 case 7:
9913                     /* for v7M, same as 6; for R profile a reserved value */
9914                     if (arm_feature(env, ARM_FEATURE_M)) {
9915                         *prot |= PAGE_READ | PAGE_EXEC;
9916                         break;
9917                     }
9918                     /* fall through */
9919                 default:
9920                     qemu_log_mask(LOG_GUEST_ERROR,
9921                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9922                                   PRIx32 "\n", n, ap);
9923                 }
9924             }
9925 
9926             /* execute never */
9927             if (xn) {
9928                 *prot &= ~PAGE_EXEC;
9929             }
9930         }
9931     }
9932 
9933     fi->type = ARMFault_Permission;
9934     fi->level = 1;
9935     return !(*prot & (1 << access_type));
9936 }
9937 
9938 static bool v8m_is_sau_exempt(CPUARMState *env,
9939                               uint32_t address, MMUAccessType access_type)
9940 {
9941     /* The architecture specifies that certain address ranges are
9942      * exempt from v8M SAU/IDAU checks.
9943      */
9944     return
9945         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
9946         (address >= 0xe0000000 && address <= 0xe0002fff) ||
9947         (address >= 0xe000e000 && address <= 0xe000efff) ||
9948         (address >= 0xe002e000 && address <= 0xe002efff) ||
9949         (address >= 0xe0040000 && address <= 0xe0041fff) ||
9950         (address >= 0xe00ff000 && address <= 0xe00fffff);
9951 }
9952 
9953 void v8m_security_lookup(CPUARMState *env, uint32_t address,
9954                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
9955                                 V8M_SAttributes *sattrs)
9956 {
9957     /* Look up the security attributes for this address. Compare the
9958      * pseudocode SecurityCheck() function.
9959      * We assume the caller has zero-initialized *sattrs.
9960      */
9961     ARMCPU *cpu = env_archcpu(env);
9962     int r;
9963     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
9964     int idau_region = IREGION_NOTVALID;
9965     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
9966     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
9967 
9968     if (cpu->idau) {
9969         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
9970         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
9971 
9972         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
9973                    &idau_nsc);
9974     }
9975 
9976     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
9977         /* 0xf0000000..0xffffffff is always S for insn fetches */
9978         return;
9979     }
9980 
9981     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
9982         sattrs->ns = !regime_is_secure(env, mmu_idx);
9983         return;
9984     }
9985 
9986     if (idau_region != IREGION_NOTVALID) {
9987         sattrs->irvalid = true;
9988         sattrs->iregion = idau_region;
9989     }
9990 
9991     switch (env->sau.ctrl & 3) {
9992     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
9993         break;
9994     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
9995         sattrs->ns = true;
9996         break;
9997     default: /* SAU.ENABLE == 1 */
9998         for (r = 0; r < cpu->sau_sregion; r++) {
9999             if (env->sau.rlar[r] & 1) {
10000                 uint32_t base = env->sau.rbar[r] & ~0x1f;
10001                 uint32_t limit = env->sau.rlar[r] | 0x1f;
10002 
10003                 if (base <= address && limit >= address) {
10004                     if (base > addr_page_base || limit < addr_page_limit) {
10005                         sattrs->subpage = true;
10006                     }
10007                     if (sattrs->srvalid) {
10008                         /* If we hit in more than one region then we must report
10009                          * as Secure, not NS-Callable, with no valid region
10010                          * number info.
10011                          */
10012                         sattrs->ns = false;
10013                         sattrs->nsc = false;
10014                         sattrs->sregion = 0;
10015                         sattrs->srvalid = false;
10016                         break;
10017                     } else {
10018                         if (env->sau.rlar[r] & 2) {
10019                             sattrs->nsc = true;
10020                         } else {
10021                             sattrs->ns = true;
10022                         }
10023                         sattrs->srvalid = true;
10024                         sattrs->sregion = r;
10025                     }
10026                 } else {
10027                     /*
10028                      * Address not in this region. We must check whether the
10029                      * region covers addresses in the same page as our address.
10030                      * In that case we must not report a size that covers the
10031                      * whole page for a subsequent hit against a different MPU
10032                      * region or the background region, because it would result
10033                      * in incorrect TLB hits for subsequent accesses to
10034                      * addresses that are in this MPU region.
10035                      */
10036                     if (limit >= base &&
10037                         ranges_overlap(base, limit - base + 1,
10038                                        addr_page_base,
10039                                        TARGET_PAGE_SIZE)) {
10040                         sattrs->subpage = true;
10041                     }
10042                 }
10043             }
10044         }
10045         break;
10046     }
10047 
10048     /*
10049      * The IDAU will override the SAU lookup results if it specifies
10050      * higher security than the SAU does.
10051      */
10052     if (!idau_ns) {
10053         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
10054             sattrs->ns = false;
10055             sattrs->nsc = idau_nsc;
10056         }
10057     }
10058 }
10059 
10060 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
10061                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
10062                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
10063                               int *prot, bool *is_subpage,
10064                               ARMMMUFaultInfo *fi, uint32_t *mregion)
10065 {
10066     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
10067      * that a full phys-to-virt translation does).
10068      * mregion is (if not NULL) set to the region number which matched,
10069      * or -1 if no region number is returned (MPU off, address did not
10070      * hit a region, address hit in multiple regions).
10071      * We set is_subpage to true if the region hit doesn't cover the
10072      * entire TARGET_PAGE the address is within.
10073      */
10074     ARMCPU *cpu = env_archcpu(env);
10075     bool is_user = regime_is_user(env, mmu_idx);
10076     uint32_t secure = regime_is_secure(env, mmu_idx);
10077     int n;
10078     int matchregion = -1;
10079     bool hit = false;
10080     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
10081     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
10082 
10083     *is_subpage = false;
10084     *phys_ptr = address;
10085     *prot = 0;
10086     if (mregion) {
10087         *mregion = -1;
10088     }
10089 
10090     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
10091      * was an exception vector read from the vector table (which is always
10092      * done using the default system address map), because those accesses
10093      * are done in arm_v7m_load_vector(), which always does a direct
10094      * read using address_space_ldl(), rather than going via this function.
10095      */
10096     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
10097         hit = true;
10098     } else if (m_is_ppb_region(env, address)) {
10099         hit = true;
10100     } else {
10101         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
10102             hit = true;
10103         }
10104 
10105         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
10106             /* region search */
10107             /* Note that the base address is bits [31:5] from the register
10108              * with bits [4:0] all zeroes, but the limit address is bits
10109              * [31:5] from the register with bits [4:0] all ones.
10110              */
10111             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
10112             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
10113 
10114             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
10115                 /* Region disabled */
10116                 continue;
10117             }
10118 
10119             if (address < base || address > limit) {
10120                 /*
10121                  * Address not in this region. We must check whether the
10122                  * region covers addresses in the same page as our address.
10123                  * In that case we must not report a size that covers the
10124                  * whole page for a subsequent hit against a different MPU
10125                  * region or the background region, because it would result in
10126                  * incorrect TLB hits for subsequent accesses to addresses that
10127                  * are in this MPU region.
10128                  */
10129                 if (limit >= base &&
10130                     ranges_overlap(base, limit - base + 1,
10131                                    addr_page_base,
10132                                    TARGET_PAGE_SIZE)) {
10133                     *is_subpage = true;
10134                 }
10135                 continue;
10136             }
10137 
10138             if (base > addr_page_base || limit < addr_page_limit) {
10139                 *is_subpage = true;
10140             }
10141 
10142             if (matchregion != -1) {
10143                 /* Multiple regions match -- always a failure (unlike
10144                  * PMSAv7 where highest-numbered-region wins)
10145                  */
10146                 fi->type = ARMFault_Permission;
10147                 fi->level = 1;
10148                 return true;
10149             }
10150 
10151             matchregion = n;
10152             hit = true;
10153         }
10154     }
10155 
10156     if (!hit) {
10157         /* background fault */
10158         fi->type = ARMFault_Background;
10159         return true;
10160     }
10161 
10162     if (matchregion == -1) {
10163         /* hit using the background region */
10164         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
10165     } else {
10166         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
10167         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
10168 
10169         if (m_is_system_region(env, address)) {
10170             /* System space is always execute never */
10171             xn = 1;
10172         }
10173 
10174         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
10175         if (*prot && !xn) {
10176             *prot |= PAGE_EXEC;
10177         }
10178         /* We don't need to look the attribute up in the MAIR0/MAIR1
10179          * registers because that only tells us about cacheability.
10180          */
10181         if (mregion) {
10182             *mregion = matchregion;
10183         }
10184     }
10185 
10186     fi->type = ARMFault_Permission;
10187     fi->level = 1;
10188     return !(*prot & (1 << access_type));
10189 }
10190 
10191 
10192 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
10193                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10194                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
10195                                  int *prot, target_ulong *page_size,
10196                                  ARMMMUFaultInfo *fi)
10197 {
10198     uint32_t secure = regime_is_secure(env, mmu_idx);
10199     V8M_SAttributes sattrs = {};
10200     bool ret;
10201     bool mpu_is_subpage;
10202 
10203     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10204         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
10205         if (access_type == MMU_INST_FETCH) {
10206             /* Instruction fetches always use the MMU bank and the
10207              * transaction attribute determined by the fetch address,
10208              * regardless of CPU state. This is painful for QEMU
10209              * to handle, because it would mean we need to encode
10210              * into the mmu_idx not just the (user, negpri) information
10211              * for the current security state but also that for the
10212              * other security state, which would balloon the number
10213              * of mmu_idx values needed alarmingly.
10214              * Fortunately we can avoid this because it's not actually
10215              * possible to arbitrarily execute code from memory with
10216              * the wrong security attribute: it will always generate
10217              * an exception of some kind or another, apart from the
10218              * special case of an NS CPU executing an SG instruction
10219              * in S&NSC memory. So we always just fail the translation
10220              * here and sort things out in the exception handler
10221              * (including possibly emulating an SG instruction).
10222              */
10223             if (sattrs.ns != !secure) {
10224                 if (sattrs.nsc) {
10225                     fi->type = ARMFault_QEMU_NSCExec;
10226                 } else {
10227                     fi->type = ARMFault_QEMU_SFault;
10228                 }
10229                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10230                 *phys_ptr = address;
10231                 *prot = 0;
10232                 return true;
10233             }
10234         } else {
10235             /* For data accesses we always use the MMU bank indicated
10236              * by the current CPU state, but the security attributes
10237              * might downgrade a secure access to nonsecure.
10238              */
10239             if (sattrs.ns) {
10240                 txattrs->secure = false;
10241             } else if (!secure) {
10242                 /* NS access to S memory must fault.
10243                  * Architecturally we should first check whether the
10244                  * MPU information for this address indicates that we
10245                  * are doing an unaligned access to Device memory, which
10246                  * should generate a UsageFault instead. QEMU does not
10247                  * currently check for that kind of unaligned access though.
10248                  * If we added it we would need to do so as a special case
10249                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
10250                  */
10251                 fi->type = ARMFault_QEMU_SFault;
10252                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10253                 *phys_ptr = address;
10254                 *prot = 0;
10255                 return true;
10256             }
10257         }
10258     }
10259 
10260     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
10261                             txattrs, prot, &mpu_is_subpage, fi, NULL);
10262     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
10263     return ret;
10264 }
10265 
10266 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
10267                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10268                                  hwaddr *phys_ptr, int *prot,
10269                                  ARMMMUFaultInfo *fi)
10270 {
10271     int n;
10272     uint32_t mask;
10273     uint32_t base;
10274     bool is_user = regime_is_user(env, mmu_idx);
10275 
10276     if (regime_translation_disabled(env, mmu_idx)) {
10277         /* MPU disabled.  */
10278         *phys_ptr = address;
10279         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10280         return false;
10281     }
10282 
10283     *phys_ptr = address;
10284     for (n = 7; n >= 0; n--) {
10285         base = env->cp15.c6_region[n];
10286         if ((base & 1) == 0) {
10287             continue;
10288         }
10289         mask = 1 << ((base >> 1) & 0x1f);
10290         /* Keep this shift separate from the above to avoid an
10291            (undefined) << 32.  */
10292         mask = (mask << 1) - 1;
10293         if (((base ^ address) & ~mask) == 0) {
10294             break;
10295         }
10296     }
10297     if (n < 0) {
10298         fi->type = ARMFault_Background;
10299         return true;
10300     }
10301 
10302     if (access_type == MMU_INST_FETCH) {
10303         mask = env->cp15.pmsav5_insn_ap;
10304     } else {
10305         mask = env->cp15.pmsav5_data_ap;
10306     }
10307     mask = (mask >> (n * 4)) & 0xf;
10308     switch (mask) {
10309     case 0:
10310         fi->type = ARMFault_Permission;
10311         fi->level = 1;
10312         return true;
10313     case 1:
10314         if (is_user) {
10315             fi->type = ARMFault_Permission;
10316             fi->level = 1;
10317             return true;
10318         }
10319         *prot = PAGE_READ | PAGE_WRITE;
10320         break;
10321     case 2:
10322         *prot = PAGE_READ;
10323         if (!is_user) {
10324             *prot |= PAGE_WRITE;
10325         }
10326         break;
10327     case 3:
10328         *prot = PAGE_READ | PAGE_WRITE;
10329         break;
10330     case 5:
10331         if (is_user) {
10332             fi->type = ARMFault_Permission;
10333             fi->level = 1;
10334             return true;
10335         }
10336         *prot = PAGE_READ;
10337         break;
10338     case 6:
10339         *prot = PAGE_READ;
10340         break;
10341     default:
10342         /* Bad permission.  */
10343         fi->type = ARMFault_Permission;
10344         fi->level = 1;
10345         return true;
10346     }
10347     *prot |= PAGE_EXEC;
10348     return false;
10349 }
10350 
10351 /* Combine either inner or outer cacheability attributes for normal
10352  * memory, according to table D4-42 and pseudocode procedure
10353  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
10354  *
10355  * NB: only stage 1 includes allocation hints (RW bits), leading to
10356  * some asymmetry.
10357  */
10358 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
10359 {
10360     if (s1 == 4 || s2 == 4) {
10361         /* non-cacheable has precedence */
10362         return 4;
10363     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
10364         /* stage 1 write-through takes precedence */
10365         return s1;
10366     } else if (extract32(s2, 2, 2) == 2) {
10367         /* stage 2 write-through takes precedence, but the allocation hint
10368          * is still taken from stage 1
10369          */
10370         return (2 << 2) | extract32(s1, 0, 2);
10371     } else { /* write-back */
10372         return s1;
10373     }
10374 }
10375 
10376 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
10377  * and CombineS1S2Desc()
10378  *
10379  * @s1:      Attributes from stage 1 walk
10380  * @s2:      Attributes from stage 2 walk
10381  */
10382 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
10383 {
10384     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
10385     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
10386     ARMCacheAttrs ret;
10387 
10388     /* Combine shareability attributes (table D4-43) */
10389     if (s1.shareability == 2 || s2.shareability == 2) {
10390         /* if either are outer-shareable, the result is outer-shareable */
10391         ret.shareability = 2;
10392     } else if (s1.shareability == 3 || s2.shareability == 3) {
10393         /* if either are inner-shareable, the result is inner-shareable */
10394         ret.shareability = 3;
10395     } else {
10396         /* both non-shareable */
10397         ret.shareability = 0;
10398     }
10399 
10400     /* Combine memory type and cacheability attributes */
10401     if (s1hi == 0 || s2hi == 0) {
10402         /* Device has precedence over normal */
10403         if (s1lo == 0 || s2lo == 0) {
10404             /* nGnRnE has precedence over anything */
10405             ret.attrs = 0;
10406         } else if (s1lo == 4 || s2lo == 4) {
10407             /* non-Reordering has precedence over Reordering */
10408             ret.attrs = 4;  /* nGnRE */
10409         } else if (s1lo == 8 || s2lo == 8) {
10410             /* non-Gathering has precedence over Gathering */
10411             ret.attrs = 8;  /* nGRE */
10412         } else {
10413             ret.attrs = 0xc; /* GRE */
10414         }
10415 
10416         /* Any location for which the resultant memory type is any
10417          * type of Device memory is always treated as Outer Shareable.
10418          */
10419         ret.shareability = 2;
10420     } else { /* Normal memory */
10421         /* Outer/inner cacheability combine independently */
10422         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
10423                   | combine_cacheattr_nibble(s1lo, s2lo);
10424 
10425         if (ret.attrs == 0x44) {
10426             /* Any location for which the resultant memory type is Normal
10427              * Inner Non-cacheable, Outer Non-cacheable is always treated
10428              * as Outer Shareable.
10429              */
10430             ret.shareability = 2;
10431         }
10432     }
10433 
10434     return ret;
10435 }
10436 
10437 
10438 /* get_phys_addr - get the physical address for this virtual address
10439  *
10440  * Find the physical address corresponding to the given virtual address,
10441  * by doing a translation table walk on MMU based systems or using the
10442  * MPU state on MPU based systems.
10443  *
10444  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
10445  * prot and page_size may not be filled in, and the populated fsr value provides
10446  * information on why the translation aborted, in the format of a
10447  * DFSR/IFSR fault register, with the following caveats:
10448  *  * we honour the short vs long DFSR format differences.
10449  *  * the WnR bit is never set (the caller must do this).
10450  *  * for PSMAv5 based systems we don't bother to return a full FSR format
10451  *    value.
10452  *
10453  * @env: CPUARMState
10454  * @address: virtual address to get physical address for
10455  * @access_type: 0 for read, 1 for write, 2 for execute
10456  * @mmu_idx: MMU index indicating required translation regime
10457  * @phys_ptr: set to the physical address corresponding to the virtual address
10458  * @attrs: set to the memory transaction attributes to use
10459  * @prot: set to the permissions for the page containing phys_ptr
10460  * @page_size: set to the size of the page containing phys_ptr
10461  * @fi: set to fault info if the translation fails
10462  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
10463  */
10464 bool get_phys_addr(CPUARMState *env, target_ulong address,
10465                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
10466                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10467                    target_ulong *page_size,
10468                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10469 {
10470     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10471         /* Call ourselves recursively to do the stage 1 and then stage 2
10472          * translations.
10473          */
10474         if (arm_feature(env, ARM_FEATURE_EL2)) {
10475             hwaddr ipa;
10476             int s2_prot;
10477             int ret;
10478             ARMCacheAttrs cacheattrs2 = {};
10479 
10480             ret = get_phys_addr(env, address, access_type,
10481                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
10482                                 prot, page_size, fi, cacheattrs);
10483 
10484             /* If S1 fails or S2 is disabled, return early.  */
10485             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10486                 *phys_ptr = ipa;
10487                 return ret;
10488             }
10489 
10490             /* S1 is done. Now do S2 translation.  */
10491             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
10492                                      phys_ptr, attrs, &s2_prot,
10493                                      page_size, fi,
10494                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
10495             fi->s2addr = ipa;
10496             /* Combine the S1 and S2 perms.  */
10497             *prot &= s2_prot;
10498 
10499             /* Combine the S1 and S2 cache attributes, if needed */
10500             if (!ret && cacheattrs != NULL) {
10501                 if (env->cp15.hcr_el2 & HCR_DC) {
10502                     /*
10503                      * HCR.DC forces the first stage attributes to
10504                      *  Normal Non-Shareable,
10505                      *  Inner Write-Back Read-Allocate Write-Allocate,
10506                      *  Outer Write-Back Read-Allocate Write-Allocate.
10507                      */
10508                     cacheattrs->attrs = 0xff;
10509                     cacheattrs->shareability = 0;
10510                 }
10511                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
10512             }
10513 
10514             return ret;
10515         } else {
10516             /*
10517              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
10518              */
10519             mmu_idx = stage_1_mmu_idx(mmu_idx);
10520         }
10521     }
10522 
10523     /* The page table entries may downgrade secure to non-secure, but
10524      * cannot upgrade an non-secure translation regime's attributes
10525      * to secure.
10526      */
10527     attrs->secure = regime_is_secure(env, mmu_idx);
10528     attrs->user = regime_is_user(env, mmu_idx);
10529 
10530     /* Fast Context Switch Extension. This doesn't exist at all in v8.
10531      * In v7 and earlier it affects all stage 1 translations.
10532      */
10533     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
10534         && !arm_feature(env, ARM_FEATURE_V8)) {
10535         if (regime_el(env, mmu_idx) == 3) {
10536             address += env->cp15.fcseidr_s;
10537         } else {
10538             address += env->cp15.fcseidr_ns;
10539         }
10540     }
10541 
10542     if (arm_feature(env, ARM_FEATURE_PMSA)) {
10543         bool ret;
10544         *page_size = TARGET_PAGE_SIZE;
10545 
10546         if (arm_feature(env, ARM_FEATURE_V8)) {
10547             /* PMSAv8 */
10548             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
10549                                        phys_ptr, attrs, prot, page_size, fi);
10550         } else if (arm_feature(env, ARM_FEATURE_V7)) {
10551             /* PMSAv7 */
10552             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
10553                                        phys_ptr, prot, page_size, fi);
10554         } else {
10555             /* Pre-v7 MPU */
10556             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
10557                                        phys_ptr, prot, fi);
10558         }
10559         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
10560                       " mmu_idx %u -> %s (prot %c%c%c)\n",
10561                       access_type == MMU_DATA_LOAD ? "reading" :
10562                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
10563                       (uint32_t)address, mmu_idx,
10564                       ret ? "Miss" : "Hit",
10565                       *prot & PAGE_READ ? 'r' : '-',
10566                       *prot & PAGE_WRITE ? 'w' : '-',
10567                       *prot & PAGE_EXEC ? 'x' : '-');
10568 
10569         return ret;
10570     }
10571 
10572     /* Definitely a real MMU, not an MPU */
10573 
10574     if (regime_translation_disabled(env, mmu_idx)) {
10575         /* MMU disabled. */
10576         *phys_ptr = address;
10577         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10578         *page_size = TARGET_PAGE_SIZE;
10579         return 0;
10580     }
10581 
10582     if (regime_using_lpae_format(env, mmu_idx)) {
10583         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
10584                                   phys_ptr, attrs, prot, page_size,
10585                                   fi, cacheattrs);
10586     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
10587         return get_phys_addr_v6(env, address, access_type, mmu_idx,
10588                                 phys_ptr, attrs, prot, page_size, fi);
10589     } else {
10590         return get_phys_addr_v5(env, address, access_type, mmu_idx,
10591                                     phys_ptr, prot, page_size, fi);
10592     }
10593 }
10594 
10595 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
10596                                          MemTxAttrs *attrs)
10597 {
10598     ARMCPU *cpu = ARM_CPU(cs);
10599     CPUARMState *env = &cpu->env;
10600     hwaddr phys_addr;
10601     target_ulong page_size;
10602     int prot;
10603     bool ret;
10604     ARMMMUFaultInfo fi = {};
10605     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
10606 
10607     *attrs = (MemTxAttrs) {};
10608 
10609     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
10610                         attrs, &prot, &page_size, &fi, NULL);
10611 
10612     if (ret) {
10613         return -1;
10614     }
10615     return phys_addr;
10616 }
10617 
10618 #endif
10619 
10620 /* Note that signed overflow is undefined in C.  The following routines are
10621    careful to use unsigned types where modulo arithmetic is required.
10622    Failure to do so _will_ break on newer gcc.  */
10623 
10624 /* Signed saturating arithmetic.  */
10625 
10626 /* Perform 16-bit signed saturating addition.  */
10627 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
10628 {
10629     uint16_t res;
10630 
10631     res = a + b;
10632     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
10633         if (a & 0x8000)
10634             res = 0x8000;
10635         else
10636             res = 0x7fff;
10637     }
10638     return res;
10639 }
10640 
10641 /* Perform 8-bit signed saturating addition.  */
10642 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
10643 {
10644     uint8_t res;
10645 
10646     res = a + b;
10647     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
10648         if (a & 0x80)
10649             res = 0x80;
10650         else
10651             res = 0x7f;
10652     }
10653     return res;
10654 }
10655 
10656 /* Perform 16-bit signed saturating subtraction.  */
10657 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
10658 {
10659     uint16_t res;
10660 
10661     res = a - b;
10662     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
10663         if (a & 0x8000)
10664             res = 0x8000;
10665         else
10666             res = 0x7fff;
10667     }
10668     return res;
10669 }
10670 
10671 /* Perform 8-bit signed saturating subtraction.  */
10672 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
10673 {
10674     uint8_t res;
10675 
10676     res = a - b;
10677     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
10678         if (a & 0x80)
10679             res = 0x80;
10680         else
10681             res = 0x7f;
10682     }
10683     return res;
10684 }
10685 
10686 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
10687 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
10688 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
10689 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
10690 #define PFX q
10691 
10692 #include "op_addsub.h"
10693 
10694 /* Unsigned saturating arithmetic.  */
10695 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
10696 {
10697     uint16_t res;
10698     res = a + b;
10699     if (res < a)
10700         res = 0xffff;
10701     return res;
10702 }
10703 
10704 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
10705 {
10706     if (a > b)
10707         return a - b;
10708     else
10709         return 0;
10710 }
10711 
10712 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
10713 {
10714     uint8_t res;
10715     res = a + b;
10716     if (res < a)
10717         res = 0xff;
10718     return res;
10719 }
10720 
10721 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
10722 {
10723     if (a > b)
10724         return a - b;
10725     else
10726         return 0;
10727 }
10728 
10729 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
10730 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
10731 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
10732 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
10733 #define PFX uq
10734 
10735 #include "op_addsub.h"
10736 
10737 /* Signed modulo arithmetic.  */
10738 #define SARITH16(a, b, n, op) do { \
10739     int32_t sum; \
10740     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
10741     RESULT(sum, n, 16); \
10742     if (sum >= 0) \
10743         ge |= 3 << (n * 2); \
10744     } while(0)
10745 
10746 #define SARITH8(a, b, n, op) do { \
10747     int32_t sum; \
10748     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
10749     RESULT(sum, n, 8); \
10750     if (sum >= 0) \
10751         ge |= 1 << n; \
10752     } while(0)
10753 
10754 
10755 #define ADD16(a, b, n) SARITH16(a, b, n, +)
10756 #define SUB16(a, b, n) SARITH16(a, b, n, -)
10757 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
10758 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
10759 #define PFX s
10760 #define ARITH_GE
10761 
10762 #include "op_addsub.h"
10763 
10764 /* Unsigned modulo arithmetic.  */
10765 #define ADD16(a, b, n) do { \
10766     uint32_t sum; \
10767     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
10768     RESULT(sum, n, 16); \
10769     if ((sum >> 16) == 1) \
10770         ge |= 3 << (n * 2); \
10771     } while(0)
10772 
10773 #define ADD8(a, b, n) do { \
10774     uint32_t sum; \
10775     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
10776     RESULT(sum, n, 8); \
10777     if ((sum >> 8) == 1) \
10778         ge |= 1 << n; \
10779     } while(0)
10780 
10781 #define SUB16(a, b, n) do { \
10782     uint32_t sum; \
10783     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
10784     RESULT(sum, n, 16); \
10785     if ((sum >> 16) == 0) \
10786         ge |= 3 << (n * 2); \
10787     } while(0)
10788 
10789 #define SUB8(a, b, n) do { \
10790     uint32_t sum; \
10791     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
10792     RESULT(sum, n, 8); \
10793     if ((sum >> 8) == 0) \
10794         ge |= 1 << n; \
10795     } while(0)
10796 
10797 #define PFX u
10798 #define ARITH_GE
10799 
10800 #include "op_addsub.h"
10801 
10802 /* Halved signed arithmetic.  */
10803 #define ADD16(a, b, n) \
10804   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
10805 #define SUB16(a, b, n) \
10806   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
10807 #define ADD8(a, b, n) \
10808   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
10809 #define SUB8(a, b, n) \
10810   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
10811 #define PFX sh
10812 
10813 #include "op_addsub.h"
10814 
10815 /* Halved unsigned arithmetic.  */
10816 #define ADD16(a, b, n) \
10817   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
10818 #define SUB16(a, b, n) \
10819   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
10820 #define ADD8(a, b, n) \
10821   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
10822 #define SUB8(a, b, n) \
10823   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
10824 #define PFX uh
10825 
10826 #include "op_addsub.h"
10827 
10828 static inline uint8_t do_usad(uint8_t a, uint8_t b)
10829 {
10830     if (a > b)
10831         return a - b;
10832     else
10833         return b - a;
10834 }
10835 
10836 /* Unsigned sum of absolute byte differences.  */
10837 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
10838 {
10839     uint32_t sum;
10840     sum = do_usad(a, b);
10841     sum += do_usad(a >> 8, b >> 8);
10842     sum += do_usad(a >> 16, b >>16);
10843     sum += do_usad(a >> 24, b >> 24);
10844     return sum;
10845 }
10846 
10847 /* For ARMv6 SEL instruction.  */
10848 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
10849 {
10850     uint32_t mask;
10851 
10852     mask = 0;
10853     if (flags & 1)
10854         mask |= 0xff;
10855     if (flags & 2)
10856         mask |= 0xff00;
10857     if (flags & 4)
10858         mask |= 0xff0000;
10859     if (flags & 8)
10860         mask |= 0xff000000;
10861     return (a & mask) | (b & ~mask);
10862 }
10863 
10864 /* CRC helpers.
10865  * The upper bytes of val (above the number specified by 'bytes') must have
10866  * been zeroed out by the caller.
10867  */
10868 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
10869 {
10870     uint8_t buf[4];
10871 
10872     stl_le_p(buf, val);
10873 
10874     /* zlib crc32 converts the accumulator and output to one's complement.  */
10875     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
10876 }
10877 
10878 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
10879 {
10880     uint8_t buf[4];
10881 
10882     stl_le_p(buf, val);
10883 
10884     /* Linux crc32c converts the output to one's complement.  */
10885     return crc32c(acc, buf, bytes) ^ 0xffffffff;
10886 }
10887 
10888 /* Return the exception level to which FP-disabled exceptions should
10889  * be taken, or 0 if FP is enabled.
10890  */
10891 int fp_exception_el(CPUARMState *env, int cur_el)
10892 {
10893 #ifndef CONFIG_USER_ONLY
10894     int fpen;
10895 
10896     /* CPACR and the CPTR registers don't exist before v6, so FP is
10897      * always accessible
10898      */
10899     if (!arm_feature(env, ARM_FEATURE_V6)) {
10900         return 0;
10901     }
10902 
10903     if (arm_feature(env, ARM_FEATURE_M)) {
10904         /* CPACR can cause a NOCP UsageFault taken to current security state */
10905         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
10906             return 1;
10907         }
10908 
10909         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
10910             if (!extract32(env->v7m.nsacr, 10, 1)) {
10911                 /* FP insns cause a NOCP UsageFault taken to Secure */
10912                 return 3;
10913             }
10914         }
10915 
10916         return 0;
10917     }
10918 
10919     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
10920      * 0, 2 : trap EL0 and EL1/PL1 accesses
10921      * 1    : trap only EL0 accesses
10922      * 3    : trap no accesses
10923      */
10924     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
10925     switch (fpen) {
10926     case 0:
10927     case 2:
10928         if (cur_el == 0 || cur_el == 1) {
10929             /* Trap to PL1, which might be EL1 or EL3 */
10930             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
10931                 return 3;
10932             }
10933             return 1;
10934         }
10935         if (cur_el == 3 && !is_a64(env)) {
10936             /* Secure PL1 running at EL3 */
10937             return 3;
10938         }
10939         break;
10940     case 1:
10941         if (cur_el == 0) {
10942             return 1;
10943         }
10944         break;
10945     case 3:
10946         break;
10947     }
10948 
10949     /*
10950      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
10951      * to control non-secure access to the FPU. It doesn't have any
10952      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
10953      */
10954     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
10955          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
10956         if (!extract32(env->cp15.nsacr, 10, 1)) {
10957             /* FP insns act as UNDEF */
10958             return cur_el == 2 ? 2 : 1;
10959         }
10960     }
10961 
10962     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
10963      * check because zero bits in the registers mean "don't trap".
10964      */
10965 
10966     /* CPTR_EL2 : present in v7VE or v8 */
10967     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
10968         && !arm_is_secure_below_el3(env)) {
10969         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
10970         return 2;
10971     }
10972 
10973     /* CPTR_EL3 : present in v8 */
10974     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
10975         /* Trap all FP ops to EL3 */
10976         return 3;
10977     }
10978 #endif
10979     return 0;
10980 }
10981 
10982 #ifndef CONFIG_TCG
10983 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
10984 {
10985     g_assert_not_reached();
10986 }
10987 #endif
10988 
10989 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
10990 {
10991     int el;
10992 
10993     if (arm_feature(env, ARM_FEATURE_M)) {
10994         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
10995     }
10996 
10997     el = arm_current_el(env);
10998     if (el < 2 && arm_is_secure_below_el3(env)) {
10999         return ARMMMUIdx_S1SE0 + el;
11000     } else {
11001         return ARMMMUIdx_S12NSE0 + el;
11002     }
11003 }
11004 
11005 int cpu_mmu_index(CPUARMState *env, bool ifetch)
11006 {
11007     return arm_to_core_mmu_idx(arm_mmu_idx(env));
11008 }
11009 
11010 #ifndef CONFIG_USER_ONLY
11011 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
11012 {
11013     return stage_1_mmu_idx(arm_mmu_idx(env));
11014 }
11015 #endif
11016 
11017 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
11018                           target_ulong *cs_base, uint32_t *pflags)
11019 {
11020     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
11021     int current_el = arm_current_el(env);
11022     int fp_el = fp_exception_el(env, current_el);
11023     uint32_t flags = 0;
11024 
11025     if (is_a64(env)) {
11026         ARMCPU *cpu = env_archcpu(env);
11027         uint64_t sctlr;
11028 
11029         *pc = env->pc;
11030         flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
11031 
11032         /* Get control bits for tagged addresses.  */
11033         {
11034             ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
11035             ARMVAParameters p0 = aa64_va_parameters_both(env, 0, stage1);
11036             int tbii, tbid;
11037 
11038             /* FIXME: ARMv8.1-VHE S2 translation regime.  */
11039             if (regime_el(env, stage1) < 2) {
11040                 ARMVAParameters p1 = aa64_va_parameters_both(env, -1, stage1);
11041                 tbid = (p1.tbi << 1) | p0.tbi;
11042                 tbii = tbid & ~((p1.tbid << 1) | p0.tbid);
11043             } else {
11044                 tbid = p0.tbi;
11045                 tbii = tbid & !p0.tbid;
11046             }
11047 
11048             flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
11049             flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
11050         }
11051 
11052         if (cpu_isar_feature(aa64_sve, cpu)) {
11053             int sve_el = sve_exception_el(env, current_el);
11054             uint32_t zcr_len;
11055 
11056             /* If SVE is disabled, but FP is enabled,
11057              * then the effective len is 0.
11058              */
11059             if (sve_el != 0 && fp_el == 0) {
11060                 zcr_len = 0;
11061             } else {
11062                 zcr_len = sve_zcr_len_for_el(env, current_el);
11063             }
11064             flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
11065             flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
11066         }
11067 
11068         sctlr = arm_sctlr(env, current_el);
11069 
11070         if (cpu_isar_feature(aa64_pauth, cpu)) {
11071             /*
11072              * In order to save space in flags, we record only whether
11073              * pauth is "inactive", meaning all insns are implemented as
11074              * a nop, or "active" when some action must be performed.
11075              * The decision of which action to take is left to a helper.
11076              */
11077             if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
11078                 flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
11079             }
11080         }
11081 
11082         if (cpu_isar_feature(aa64_bti, cpu)) {
11083             /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
11084             if (sctlr & (current_el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
11085                 flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
11086             }
11087             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
11088         }
11089     } else {
11090         *pc = env->regs[15];
11091         flags = FIELD_DP32(flags, TBFLAG_A32, THUMB, env->thumb);
11092         flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN, env->vfp.vec_len);
11093         flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE, env->vfp.vec_stride);
11094         flags = FIELD_DP32(flags, TBFLAG_A32, CONDEXEC, env->condexec_bits);
11095         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, arm_sctlr_b(env));
11096         flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
11097         if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)
11098             || arm_el_is_aa64(env, 1) || arm_feature(env, ARM_FEATURE_M)) {
11099             flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
11100         }
11101         /* Note that XSCALE_CPAR shares bits with VECSTRIDE */
11102         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
11103             flags = FIELD_DP32(flags, TBFLAG_A32,
11104                                XSCALE_CPAR, env->cp15.c15_cpar);
11105         }
11106     }
11107 
11108     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
11109 
11110     /* The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
11111      * states defined in the ARM ARM for software singlestep:
11112      *  SS_ACTIVE   PSTATE.SS   State
11113      *     0            x       Inactive (the TB flag for SS is always 0)
11114      *     1            0       Active-pending
11115      *     1            1       Active-not-pending
11116      */
11117     if (arm_singlestep_active(env)) {
11118         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
11119         if (is_a64(env)) {
11120             if (env->pstate & PSTATE_SS) {
11121                 flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
11122             }
11123         } else {
11124             if (env->uncached_cpsr & PSTATE_SS) {
11125                 flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
11126             }
11127         }
11128     }
11129     if (arm_cpu_data_is_big_endian(env)) {
11130         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
11131     }
11132     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
11133 
11134     if (arm_v7m_is_handler_mode(env)) {
11135         flags = FIELD_DP32(flags, TBFLAG_A32, HANDLER, 1);
11136     }
11137 
11138     /* v8M always applies stack limit checks unless CCR.STKOFHFNMIGN is
11139      * suppressing them because the requested execution priority is less than 0.
11140      */
11141     if (arm_feature(env, ARM_FEATURE_V8) &&
11142         arm_feature(env, ARM_FEATURE_M) &&
11143         !((mmu_idx  & ARM_MMU_IDX_M_NEGPRI) &&
11144           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
11145         flags = FIELD_DP32(flags, TBFLAG_A32, STACKCHECK, 1);
11146     }
11147 
11148     if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
11149         FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S) != env->v7m.secure) {
11150         flags = FIELD_DP32(flags, TBFLAG_A32, FPCCR_S_WRONG, 1);
11151     }
11152 
11153     if (arm_feature(env, ARM_FEATURE_M) &&
11154         (env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
11155         (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
11156          (env->v7m.secure &&
11157           !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
11158         /*
11159          * ASPEN is set, but FPCA/SFPA indicate that there is no active
11160          * FP context; we must create a new FP context before executing
11161          * any FP insn.
11162          */
11163         flags = FIELD_DP32(flags, TBFLAG_A32, NEW_FP_CTXT_NEEDED, 1);
11164     }
11165 
11166     if (arm_feature(env, ARM_FEATURE_M)) {
11167         bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
11168 
11169         if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
11170             flags = FIELD_DP32(flags, TBFLAG_A32, LSPACT, 1);
11171         }
11172     }
11173 
11174     *pflags = flags;
11175     *cs_base = 0;
11176 }
11177 
11178 #ifdef TARGET_AARCH64
11179 /*
11180  * The manual says that when SVE is enabled and VQ is widened the
11181  * implementation is allowed to zero the previously inaccessible
11182  * portion of the registers.  The corollary to that is that when
11183  * SVE is enabled and VQ is narrowed we are also allowed to zero
11184  * the now inaccessible portion of the registers.
11185  *
11186  * The intent of this is that no predicate bit beyond VQ is ever set.
11187  * Which means that some operations on predicate registers themselves
11188  * may operate on full uint64_t or even unrolled across the maximum
11189  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
11190  * may well be cheaper than conditionals to restrict the operation
11191  * to the relevant portion of a uint16_t[16].
11192  */
11193 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
11194 {
11195     int i, j;
11196     uint64_t pmask;
11197 
11198     assert(vq >= 1 && vq <= ARM_MAX_VQ);
11199     assert(vq <= env_archcpu(env)->sve_max_vq);
11200 
11201     /* Zap the high bits of the zregs.  */
11202     for (i = 0; i < 32; i++) {
11203         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
11204     }
11205 
11206     /* Zap the high bits of the pregs and ffr.  */
11207     pmask = 0;
11208     if (vq & 3) {
11209         pmask = ~(-1ULL << (16 * (vq & 3)));
11210     }
11211     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
11212         for (i = 0; i < 17; ++i) {
11213             env->vfp.pregs[i].p[j] &= pmask;
11214         }
11215         pmask = 0;
11216     }
11217 }
11218 
11219 /*
11220  * Notice a change in SVE vector size when changing EL.
11221  */
11222 void aarch64_sve_change_el(CPUARMState *env, int old_el,
11223                            int new_el, bool el0_a64)
11224 {
11225     ARMCPU *cpu = env_archcpu(env);
11226     int old_len, new_len;
11227     bool old_a64, new_a64;
11228 
11229     /* Nothing to do if no SVE.  */
11230     if (!cpu_isar_feature(aa64_sve, cpu)) {
11231         return;
11232     }
11233 
11234     /* Nothing to do if FP is disabled in either EL.  */
11235     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
11236         return;
11237     }
11238 
11239     /*
11240      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
11241      * at ELx, or not available because the EL is in AArch32 state, then
11242      * for all purposes other than a direct read, the ZCR_ELx.LEN field
11243      * has an effective value of 0".
11244      *
11245      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
11246      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
11247      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
11248      * we already have the correct register contents when encountering the
11249      * vq0->vq0 transition between EL0->EL1.
11250      */
11251     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
11252     old_len = (old_a64 && !sve_exception_el(env, old_el)
11253                ? sve_zcr_len_for_el(env, old_el) : 0);
11254     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
11255     new_len = (new_a64 && !sve_exception_el(env, new_el)
11256                ? sve_zcr_len_for_el(env, new_el) : 0);
11257 
11258     /* When changing vector length, clear inaccessible state.  */
11259     if (new_len < old_len) {
11260         aarch64_sve_narrow_vq(env, new_len + 1);
11261     }
11262 }
11263 #endif
11264