xref: /openbmc/qemu/target/arm/helper.c (revision d6cd3ae0)
1 /*
2  * ARM generic helpers.
3  *
4  * This code is licensed under the GNU GPL v2 or later.
5  *
6  * SPDX-License-Identifier: GPL-2.0-or-later
7  */
8 
9 #include "qemu/osdep.h"
10 #include "qemu/units.h"
11 #include "qemu/log.h"
12 #include "target/arm/idau.h"
13 #include "trace.h"
14 #include "cpu.h"
15 #include "internals.h"
16 #include "exec/helper-proto.h"
17 #include "qemu/host-utils.h"
18 #include "qemu/main-loop.h"
19 #include "qemu/timer.h"
20 #include "qemu/bitops.h"
21 #include "qemu/crc32c.h"
22 #include "qemu/qemu-print.h"
23 #include "exec/exec-all.h"
24 #include <zlib.h> /* For crc32 */
25 #include "hw/irq.h"
26 #include "semihosting/semihost.h"
27 #include "sysemu/cpus.h"
28 #include "sysemu/cpu-timers.h"
29 #include "sysemu/kvm.h"
30 #include "qemu/range.h"
31 #include "qapi/qapi-commands-machine-target.h"
32 #include "qapi/error.h"
33 #include "qemu/guest-random.h"
34 #ifdef CONFIG_TCG
35 #include "arm_ldst.h"
36 #include "exec/cpu_ldst.h"
37 #include "semihosting/common-semi.h"
38 #endif
39 #include "cpregs.h"
40 
41 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
42 
43 #ifndef CONFIG_USER_ONLY
44 
45 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
46                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
47                                bool s1_is_el0,
48                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
49                                target_ulong *page_size_ptr,
50                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
51     __attribute__((nonnull));
52 #endif
53 
54 static void switch_mode(CPUARMState *env, int mode);
55 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx);
56 
57 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
58 {
59     assert(ri->fieldoffset);
60     if (cpreg_field_is_64bit(ri)) {
61         return CPREG_FIELD64(env, ri);
62     } else {
63         return CPREG_FIELD32(env, ri);
64     }
65 }
66 
67 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
68                       uint64_t value)
69 {
70     assert(ri->fieldoffset);
71     if (cpreg_field_is_64bit(ri)) {
72         CPREG_FIELD64(env, ri) = value;
73     } else {
74         CPREG_FIELD32(env, ri) = value;
75     }
76 }
77 
78 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
79 {
80     return (char *)env + ri->fieldoffset;
81 }
82 
83 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
84 {
85     /* Raw read of a coprocessor register (as needed for migration, etc). */
86     if (ri->type & ARM_CP_CONST) {
87         return ri->resetvalue;
88     } else if (ri->raw_readfn) {
89         return ri->raw_readfn(env, ri);
90     } else if (ri->readfn) {
91         return ri->readfn(env, ri);
92     } else {
93         return raw_read(env, ri);
94     }
95 }
96 
97 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
98                              uint64_t v)
99 {
100     /* Raw write of a coprocessor register (as needed for migration, etc).
101      * Note that constant registers are treated as write-ignored; the
102      * caller should check for success by whether a readback gives the
103      * value written.
104      */
105     if (ri->type & ARM_CP_CONST) {
106         return;
107     } else if (ri->raw_writefn) {
108         ri->raw_writefn(env, ri, v);
109     } else if (ri->writefn) {
110         ri->writefn(env, ri, v);
111     } else {
112         raw_write(env, ri, v);
113     }
114 }
115 
116 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
117 {
118    /* Return true if the regdef would cause an assertion if you called
119     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
120     * program bug for it not to have the NO_RAW flag).
121     * NB that returning false here doesn't necessarily mean that calling
122     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
123     * read/write access functions which are safe for raw use" from "has
124     * read/write access functions which have side effects but has forgotten
125     * to provide raw access functions".
126     * The tests here line up with the conditions in read/write_raw_cp_reg()
127     * and assertions in raw_read()/raw_write().
128     */
129     if ((ri->type & ARM_CP_CONST) ||
130         ri->fieldoffset ||
131         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
132         return false;
133     }
134     return true;
135 }
136 
137 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
138 {
139     /* Write the coprocessor state from cpu->env to the (index,value) list. */
140     int i;
141     bool ok = true;
142 
143     for (i = 0; i < cpu->cpreg_array_len; i++) {
144         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
145         const ARMCPRegInfo *ri;
146         uint64_t newval;
147 
148         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
149         if (!ri) {
150             ok = false;
151             continue;
152         }
153         if (ri->type & ARM_CP_NO_RAW) {
154             continue;
155         }
156 
157         newval = read_raw_cp_reg(&cpu->env, ri);
158         if (kvm_sync) {
159             /*
160              * Only sync if the previous list->cpustate sync succeeded.
161              * Rather than tracking the success/failure state for every
162              * item in the list, we just recheck "does the raw write we must
163              * have made in write_list_to_cpustate() read back OK" here.
164              */
165             uint64_t oldval = cpu->cpreg_values[i];
166 
167             if (oldval == newval) {
168                 continue;
169             }
170 
171             write_raw_cp_reg(&cpu->env, ri, oldval);
172             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
173                 continue;
174             }
175 
176             write_raw_cp_reg(&cpu->env, ri, newval);
177         }
178         cpu->cpreg_values[i] = newval;
179     }
180     return ok;
181 }
182 
183 bool write_list_to_cpustate(ARMCPU *cpu)
184 {
185     int i;
186     bool ok = true;
187 
188     for (i = 0; i < cpu->cpreg_array_len; i++) {
189         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
190         uint64_t v = cpu->cpreg_values[i];
191         const ARMCPRegInfo *ri;
192 
193         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
194         if (!ri) {
195             ok = false;
196             continue;
197         }
198         if (ri->type & ARM_CP_NO_RAW) {
199             continue;
200         }
201         /* Write value and confirm it reads back as written
202          * (to catch read-only registers and partially read-only
203          * registers where the incoming migration value doesn't match)
204          */
205         write_raw_cp_reg(&cpu->env, ri, v);
206         if (read_raw_cp_reg(&cpu->env, ri) != v) {
207             ok = false;
208         }
209     }
210     return ok;
211 }
212 
213 static void add_cpreg_to_list(gpointer key, gpointer opaque)
214 {
215     ARMCPU *cpu = opaque;
216     uint32_t regidx = (uintptr_t)key;
217     const ARMCPRegInfo *ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
218 
219     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
220         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
221         /* The value array need not be initialized at this point */
222         cpu->cpreg_array_len++;
223     }
224 }
225 
226 static void count_cpreg(gpointer key, gpointer opaque)
227 {
228     ARMCPU *cpu = opaque;
229     const ARMCPRegInfo *ri;
230 
231     ri = g_hash_table_lookup(cpu->cp_regs, key);
232 
233     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
234         cpu->cpreg_array_len++;
235     }
236 }
237 
238 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
239 {
240     uint64_t aidx = cpreg_to_kvm_id((uintptr_t)a);
241     uint64_t bidx = cpreg_to_kvm_id((uintptr_t)b);
242 
243     if (aidx > bidx) {
244         return 1;
245     }
246     if (aidx < bidx) {
247         return -1;
248     }
249     return 0;
250 }
251 
252 void init_cpreg_list(ARMCPU *cpu)
253 {
254     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
255      * Note that we require cpreg_tuples[] to be sorted by key ID.
256      */
257     GList *keys;
258     int arraylen;
259 
260     keys = g_hash_table_get_keys(cpu->cp_regs);
261     keys = g_list_sort(keys, cpreg_key_compare);
262 
263     cpu->cpreg_array_len = 0;
264 
265     g_list_foreach(keys, count_cpreg, cpu);
266 
267     arraylen = cpu->cpreg_array_len;
268     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
269     cpu->cpreg_values = g_new(uint64_t, arraylen);
270     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
271     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
272     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
273     cpu->cpreg_array_len = 0;
274 
275     g_list_foreach(keys, add_cpreg_to_list, cpu);
276 
277     assert(cpu->cpreg_array_len == arraylen);
278 
279     g_list_free(keys);
280 }
281 
282 /*
283  * Some registers are not accessible from AArch32 EL3 if SCR.NS == 0.
284  */
285 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
286                                         const ARMCPRegInfo *ri,
287                                         bool isread)
288 {
289     if (!is_a64(env) && arm_current_el(env) == 3 &&
290         arm_is_secure_below_el3(env)) {
291         return CP_ACCESS_TRAP_UNCATEGORIZED;
292     }
293     return CP_ACCESS_OK;
294 }
295 
296 /* Some secure-only AArch32 registers trap to EL3 if used from
297  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
298  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
299  * We assume that the .access field is set to PL1_RW.
300  */
301 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
302                                             const ARMCPRegInfo *ri,
303                                             bool isread)
304 {
305     if (arm_current_el(env) == 3) {
306         return CP_ACCESS_OK;
307     }
308     if (arm_is_secure_below_el3(env)) {
309         if (env->cp15.scr_el3 & SCR_EEL2) {
310             return CP_ACCESS_TRAP_EL2;
311         }
312         return CP_ACCESS_TRAP_EL3;
313     }
314     /* This will be EL1 NS and EL2 NS, which just UNDEF */
315     return CP_ACCESS_TRAP_UNCATEGORIZED;
316 }
317 
318 static uint64_t arm_mdcr_el2_eff(CPUARMState *env)
319 {
320     return arm_is_el2_enabled(env) ? env->cp15.mdcr_el2 : 0;
321 }
322 
323 /* Check for traps to "powerdown debug" registers, which are controlled
324  * by MDCR.TDOSA
325  */
326 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
327                                    bool isread)
328 {
329     int el = arm_current_el(env);
330     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
331     bool mdcr_el2_tdosa = (mdcr_el2 & MDCR_TDOSA) || (mdcr_el2 & MDCR_TDE) ||
332         (arm_hcr_el2_eff(env) & HCR_TGE);
333 
334     if (el < 2 && mdcr_el2_tdosa) {
335         return CP_ACCESS_TRAP_EL2;
336     }
337     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
338         return CP_ACCESS_TRAP_EL3;
339     }
340     return CP_ACCESS_OK;
341 }
342 
343 /* Check for traps to "debug ROM" registers, which are controlled
344  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
345  */
346 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
347                                   bool isread)
348 {
349     int el = arm_current_el(env);
350     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
351     bool mdcr_el2_tdra = (mdcr_el2 & MDCR_TDRA) || (mdcr_el2 & MDCR_TDE) ||
352         (arm_hcr_el2_eff(env) & HCR_TGE);
353 
354     if (el < 2 && mdcr_el2_tdra) {
355         return CP_ACCESS_TRAP_EL2;
356     }
357     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
358         return CP_ACCESS_TRAP_EL3;
359     }
360     return CP_ACCESS_OK;
361 }
362 
363 /* Check for traps to general debug registers, which are controlled
364  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
365  */
366 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
367                                   bool isread)
368 {
369     int el = arm_current_el(env);
370     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
371     bool mdcr_el2_tda = (mdcr_el2 & MDCR_TDA) || (mdcr_el2 & MDCR_TDE) ||
372         (arm_hcr_el2_eff(env) & HCR_TGE);
373 
374     if (el < 2 && mdcr_el2_tda) {
375         return CP_ACCESS_TRAP_EL2;
376     }
377     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
378         return CP_ACCESS_TRAP_EL3;
379     }
380     return CP_ACCESS_OK;
381 }
382 
383 /* Check for traps to performance monitor registers, which are controlled
384  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
385  */
386 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
387                                  bool isread)
388 {
389     int el = arm_current_el(env);
390     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
391 
392     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
393         return CP_ACCESS_TRAP_EL2;
394     }
395     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
396         return CP_ACCESS_TRAP_EL3;
397     }
398     return CP_ACCESS_OK;
399 }
400 
401 /* Check for traps from EL1 due to HCR_EL2.TVM and HCR_EL2.TRVM.  */
402 static CPAccessResult access_tvm_trvm(CPUARMState *env, const ARMCPRegInfo *ri,
403                                       bool isread)
404 {
405     if (arm_current_el(env) == 1) {
406         uint64_t trap = isread ? HCR_TRVM : HCR_TVM;
407         if (arm_hcr_el2_eff(env) & trap) {
408             return CP_ACCESS_TRAP_EL2;
409         }
410     }
411     return CP_ACCESS_OK;
412 }
413 
414 /* Check for traps from EL1 due to HCR_EL2.TSW.  */
415 static CPAccessResult access_tsw(CPUARMState *env, const ARMCPRegInfo *ri,
416                                  bool isread)
417 {
418     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TSW)) {
419         return CP_ACCESS_TRAP_EL2;
420     }
421     return CP_ACCESS_OK;
422 }
423 
424 /* Check for traps from EL1 due to HCR_EL2.TACR.  */
425 static CPAccessResult access_tacr(CPUARMState *env, const ARMCPRegInfo *ri,
426                                   bool isread)
427 {
428     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TACR)) {
429         return CP_ACCESS_TRAP_EL2;
430     }
431     return CP_ACCESS_OK;
432 }
433 
434 /* Check for traps from EL1 due to HCR_EL2.TTLB. */
435 static CPAccessResult access_ttlb(CPUARMState *env, const ARMCPRegInfo *ri,
436                                   bool isread)
437 {
438     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TTLB)) {
439         return CP_ACCESS_TRAP_EL2;
440     }
441     return CP_ACCESS_OK;
442 }
443 
444 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
445 {
446     ARMCPU *cpu = env_archcpu(env);
447 
448     raw_write(env, ri, value);
449     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
450 }
451 
452 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
453 {
454     ARMCPU *cpu = env_archcpu(env);
455 
456     if (raw_read(env, ri) != value) {
457         /* Unlike real hardware the qemu TLB uses virtual addresses,
458          * not modified virtual addresses, so this causes a TLB flush.
459          */
460         tlb_flush(CPU(cpu));
461         raw_write(env, ri, value);
462     }
463 }
464 
465 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
466                              uint64_t value)
467 {
468     ARMCPU *cpu = env_archcpu(env);
469 
470     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
471         && !extended_addresses_enabled(env)) {
472         /* For VMSA (when not using the LPAE long descriptor page table
473          * format) this register includes the ASID, so do a TLB flush.
474          * For PMSA it is purely a process ID and no action is needed.
475          */
476         tlb_flush(CPU(cpu));
477     }
478     raw_write(env, ri, value);
479 }
480 
481 /* IS variants of TLB operations must affect all cores */
482 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
483                              uint64_t value)
484 {
485     CPUState *cs = env_cpu(env);
486 
487     tlb_flush_all_cpus_synced(cs);
488 }
489 
490 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
491                              uint64_t value)
492 {
493     CPUState *cs = env_cpu(env);
494 
495     tlb_flush_all_cpus_synced(cs);
496 }
497 
498 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
499                              uint64_t value)
500 {
501     CPUState *cs = env_cpu(env);
502 
503     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
504 }
505 
506 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
507                              uint64_t value)
508 {
509     CPUState *cs = env_cpu(env);
510 
511     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
512 }
513 
514 /*
515  * Non-IS variants of TLB operations are upgraded to
516  * IS versions if we are at EL1 and HCR_EL2.FB is effectively set to
517  * force broadcast of these operations.
518  */
519 static bool tlb_force_broadcast(CPUARMState *env)
520 {
521     return arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_FB);
522 }
523 
524 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
525                           uint64_t value)
526 {
527     /* Invalidate all (TLBIALL) */
528     CPUState *cs = env_cpu(env);
529 
530     if (tlb_force_broadcast(env)) {
531         tlb_flush_all_cpus_synced(cs);
532     } else {
533         tlb_flush(cs);
534     }
535 }
536 
537 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
538                           uint64_t value)
539 {
540     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
541     CPUState *cs = env_cpu(env);
542 
543     value &= TARGET_PAGE_MASK;
544     if (tlb_force_broadcast(env)) {
545         tlb_flush_page_all_cpus_synced(cs, value);
546     } else {
547         tlb_flush_page(cs, value);
548     }
549 }
550 
551 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
552                            uint64_t value)
553 {
554     /* Invalidate by ASID (TLBIASID) */
555     CPUState *cs = env_cpu(env);
556 
557     if (tlb_force_broadcast(env)) {
558         tlb_flush_all_cpus_synced(cs);
559     } else {
560         tlb_flush(cs);
561     }
562 }
563 
564 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
565                            uint64_t value)
566 {
567     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
568     CPUState *cs = env_cpu(env);
569 
570     value &= TARGET_PAGE_MASK;
571     if (tlb_force_broadcast(env)) {
572         tlb_flush_page_all_cpus_synced(cs, value);
573     } else {
574         tlb_flush_page(cs, value);
575     }
576 }
577 
578 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
579                                uint64_t value)
580 {
581     CPUState *cs = env_cpu(env);
582 
583     tlb_flush_by_mmuidx(cs,
584                         ARMMMUIdxBit_E10_1 |
585                         ARMMMUIdxBit_E10_1_PAN |
586                         ARMMMUIdxBit_E10_0);
587 }
588 
589 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
590                                   uint64_t value)
591 {
592     CPUState *cs = env_cpu(env);
593 
594     tlb_flush_by_mmuidx_all_cpus_synced(cs,
595                                         ARMMMUIdxBit_E10_1 |
596                                         ARMMMUIdxBit_E10_1_PAN |
597                                         ARMMMUIdxBit_E10_0);
598 }
599 
600 
601 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
602                               uint64_t value)
603 {
604     CPUState *cs = env_cpu(env);
605 
606     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_E2);
607 }
608 
609 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
610                                  uint64_t value)
611 {
612     CPUState *cs = env_cpu(env);
613 
614     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_E2);
615 }
616 
617 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
618                               uint64_t value)
619 {
620     CPUState *cs = env_cpu(env);
621     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
622 
623     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_E2);
624 }
625 
626 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
627                                  uint64_t value)
628 {
629     CPUState *cs = env_cpu(env);
630     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
631 
632     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
633                                              ARMMMUIdxBit_E2);
634 }
635 
636 static const ARMCPRegInfo cp_reginfo[] = {
637     /* Define the secure and non-secure FCSE identifier CP registers
638      * separately because there is no secure bank in V8 (no _EL3).  This allows
639      * the secure register to be properly reset and migrated. There is also no
640      * v8 EL1 version of the register so the non-secure instance stands alone.
641      */
642     { .name = "FCSEIDR",
643       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
644       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
645       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
646       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
647     { .name = "FCSEIDR_S",
648       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
649       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
650       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
651       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
652     /* Define the secure and non-secure context identifier CP registers
653      * separately because there is no secure bank in V8 (no _EL3).  This allows
654      * the secure register to be properly reset and migrated.  In the
655      * non-secure case, the 32-bit register will have reset and migration
656      * disabled during registration as it is handled by the 64-bit instance.
657      */
658     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
659       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
660       .access = PL1_RW, .accessfn = access_tvm_trvm,
661       .secure = ARM_CP_SECSTATE_NS,
662       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
663       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
664     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
665       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
666       .access = PL1_RW, .accessfn = access_tvm_trvm,
667       .secure = ARM_CP_SECSTATE_S,
668       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
669       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
670 };
671 
672 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
673     /* NB: Some of these registers exist in v8 but with more precise
674      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
675      */
676     /* MMU Domain access control / MPU write buffer control */
677     { .name = "DACR",
678       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
679       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
680       .writefn = dacr_write, .raw_writefn = raw_write,
681       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
682                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
683     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
684      * For v6 and v5, these mappings are overly broad.
685      */
686     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
687       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
688     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
689       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
690     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
691       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
692     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
693       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
694     /* Cache maintenance ops; some of this space may be overridden later. */
695     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
696       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
697       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
698 };
699 
700 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
701     /* Not all pre-v6 cores implemented this WFI, so this is slightly
702      * over-broad.
703      */
704     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
705       .access = PL1_W, .type = ARM_CP_WFI },
706 };
707 
708 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
709     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
710      * is UNPREDICTABLE; we choose to NOP as most implementations do).
711      */
712     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
713       .access = PL1_W, .type = ARM_CP_WFI },
714     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
715      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
716      * OMAPCP will override this space.
717      */
718     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
719       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
720       .resetvalue = 0 },
721     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
722       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
723       .resetvalue = 0 },
724     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
725     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
726       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
727       .resetvalue = 0 },
728     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
729      * implementing it as RAZ means the "debug architecture version" bits
730      * will read as a reserved value, which should cause Linux to not try
731      * to use the debug hardware.
732      */
733     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
734       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
735     /* MMU TLB control. Note that the wildcarding means we cover not just
736      * the unified TLB ops but also the dside/iside/inner-shareable variants.
737      */
738     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
739       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
740       .type = ARM_CP_NO_RAW },
741     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
742       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
743       .type = ARM_CP_NO_RAW },
744     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
745       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
746       .type = ARM_CP_NO_RAW },
747     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
748       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
749       .type = ARM_CP_NO_RAW },
750     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
751       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
752     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
753       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
754 };
755 
756 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
757                         uint64_t value)
758 {
759     uint32_t mask = 0;
760 
761     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
762     if (!arm_feature(env, ARM_FEATURE_V8)) {
763         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
764          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
765          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
766          */
767         if (cpu_isar_feature(aa32_vfp_simd, env_archcpu(env))) {
768             /* VFP coprocessor: cp10 & cp11 [23:20] */
769             mask |= R_CPACR_ASEDIS_MASK |
770                     R_CPACR_D32DIS_MASK |
771                     R_CPACR_CP11_MASK |
772                     R_CPACR_CP10_MASK;
773 
774             if (!arm_feature(env, ARM_FEATURE_NEON)) {
775                 /* ASEDIS [31] bit is RAO/WI */
776                 value |= R_CPACR_ASEDIS_MASK;
777             }
778 
779             /* VFPv3 and upwards with NEON implement 32 double precision
780              * registers (D0-D31).
781              */
782             if (!cpu_isar_feature(aa32_simd_r32, env_archcpu(env))) {
783                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
784                 value |= R_CPACR_D32DIS_MASK;
785             }
786         }
787         value &= mask;
788     }
789 
790     /*
791      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
792      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
793      */
794     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
795         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
796         mask = R_CPACR_CP11_MASK | R_CPACR_CP10_MASK;
797         value = (value & ~mask) | (env->cp15.cpacr_el1 & mask);
798     }
799 
800     env->cp15.cpacr_el1 = value;
801 }
802 
803 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
804 {
805     /*
806      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
807      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
808      */
809     uint64_t value = env->cp15.cpacr_el1;
810 
811     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
812         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
813         value = ~(R_CPACR_CP11_MASK | R_CPACR_CP10_MASK);
814     }
815     return value;
816 }
817 
818 
819 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
820 {
821     /* Call cpacr_write() so that we reset with the correct RAO bits set
822      * for our CPU features.
823      */
824     cpacr_write(env, ri, 0);
825 }
826 
827 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
828                                    bool isread)
829 {
830     if (arm_feature(env, ARM_FEATURE_V8)) {
831         /* Check if CPACR accesses are to be trapped to EL2 */
832         if (arm_current_el(env) == 1 && arm_is_el2_enabled(env) &&
833             FIELD_EX64(env->cp15.cptr_el[2], CPTR_EL2, TCPAC)) {
834             return CP_ACCESS_TRAP_EL2;
835         /* Check if CPACR accesses are to be trapped to EL3 */
836         } else if (arm_current_el(env) < 3 &&
837                    FIELD_EX64(env->cp15.cptr_el[3], CPTR_EL3, TCPAC)) {
838             return CP_ACCESS_TRAP_EL3;
839         }
840     }
841 
842     return CP_ACCESS_OK;
843 }
844 
845 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
846                                   bool isread)
847 {
848     /* Check if CPTR accesses are set to trap to EL3 */
849     if (arm_current_el(env) == 2 &&
850         FIELD_EX64(env->cp15.cptr_el[3], CPTR_EL3, TCPAC)) {
851         return CP_ACCESS_TRAP_EL3;
852     }
853 
854     return CP_ACCESS_OK;
855 }
856 
857 static const ARMCPRegInfo v6_cp_reginfo[] = {
858     /* prefetch by MVA in v6, NOP in v7 */
859     { .name = "MVA_prefetch",
860       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
861       .access = PL1_W, .type = ARM_CP_NOP },
862     /* We need to break the TB after ISB to execute self-modifying code
863      * correctly and also to take any pending interrupts immediately.
864      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
865      */
866     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
867       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
868     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
869       .access = PL0_W, .type = ARM_CP_NOP },
870     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
871       .access = PL0_W, .type = ARM_CP_NOP },
872     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
873       .access = PL1_RW, .accessfn = access_tvm_trvm,
874       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
875                              offsetof(CPUARMState, cp15.ifar_ns) },
876       .resetvalue = 0, },
877     /* Watchpoint Fault Address Register : should actually only be present
878      * for 1136, 1176, 11MPCore.
879      */
880     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
881       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
882     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
883       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
884       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
885       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
886 };
887 
888 typedef struct pm_event {
889     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
890     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
891     bool (*supported)(CPUARMState *);
892     /*
893      * Retrieve the current count of the underlying event. The programmed
894      * counters hold a difference from the return value from this function
895      */
896     uint64_t (*get_count)(CPUARMState *);
897     /*
898      * Return how many nanoseconds it will take (at a minimum) for count events
899      * to occur. A negative value indicates the counter will never overflow, or
900      * that the counter has otherwise arranged for the overflow bit to be set
901      * and the PMU interrupt to be raised on overflow.
902      */
903     int64_t (*ns_per_count)(uint64_t);
904 } pm_event;
905 
906 static bool event_always_supported(CPUARMState *env)
907 {
908     return true;
909 }
910 
911 static uint64_t swinc_get_count(CPUARMState *env)
912 {
913     /*
914      * SW_INCR events are written directly to the pmevcntr's by writes to
915      * PMSWINC, so there is no underlying count maintained by the PMU itself
916      */
917     return 0;
918 }
919 
920 static int64_t swinc_ns_per(uint64_t ignored)
921 {
922     return -1;
923 }
924 
925 /*
926  * Return the underlying cycle count for the PMU cycle counters. If we're in
927  * usermode, simply return 0.
928  */
929 static uint64_t cycles_get_count(CPUARMState *env)
930 {
931 #ifndef CONFIG_USER_ONLY
932     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
933                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
934 #else
935     return cpu_get_host_ticks();
936 #endif
937 }
938 
939 #ifndef CONFIG_USER_ONLY
940 static int64_t cycles_ns_per(uint64_t cycles)
941 {
942     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
943 }
944 
945 static bool instructions_supported(CPUARMState *env)
946 {
947     return icount_enabled() == 1; /* Precise instruction counting */
948 }
949 
950 static uint64_t instructions_get_count(CPUARMState *env)
951 {
952     return (uint64_t)icount_get_raw();
953 }
954 
955 static int64_t instructions_ns_per(uint64_t icount)
956 {
957     return icount_to_ns((int64_t)icount);
958 }
959 #endif
960 
961 static bool pmu_8_1_events_supported(CPUARMState *env)
962 {
963     /* For events which are supported in any v8.1 PMU */
964     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
965 }
966 
967 static bool pmu_8_4_events_supported(CPUARMState *env)
968 {
969     /* For events which are supported in any v8.1 PMU */
970     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
971 }
972 
973 static uint64_t zero_event_get_count(CPUARMState *env)
974 {
975     /* For events which on QEMU never fire, so their count is always zero */
976     return 0;
977 }
978 
979 static int64_t zero_event_ns_per(uint64_t cycles)
980 {
981     /* An event which never fires can never overflow */
982     return -1;
983 }
984 
985 static const pm_event pm_events[] = {
986     { .number = 0x000, /* SW_INCR */
987       .supported = event_always_supported,
988       .get_count = swinc_get_count,
989       .ns_per_count = swinc_ns_per,
990     },
991 #ifndef CONFIG_USER_ONLY
992     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
993       .supported = instructions_supported,
994       .get_count = instructions_get_count,
995       .ns_per_count = instructions_ns_per,
996     },
997     { .number = 0x011, /* CPU_CYCLES, Cycle */
998       .supported = event_always_supported,
999       .get_count = cycles_get_count,
1000       .ns_per_count = cycles_ns_per,
1001     },
1002 #endif
1003     { .number = 0x023, /* STALL_FRONTEND */
1004       .supported = pmu_8_1_events_supported,
1005       .get_count = zero_event_get_count,
1006       .ns_per_count = zero_event_ns_per,
1007     },
1008     { .number = 0x024, /* STALL_BACKEND */
1009       .supported = pmu_8_1_events_supported,
1010       .get_count = zero_event_get_count,
1011       .ns_per_count = zero_event_ns_per,
1012     },
1013     { .number = 0x03c, /* STALL */
1014       .supported = pmu_8_4_events_supported,
1015       .get_count = zero_event_get_count,
1016       .ns_per_count = zero_event_ns_per,
1017     },
1018 };
1019 
1020 /*
1021  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1022  * events (i.e. the statistical profiling extension), this implementation
1023  * should first be updated to something sparse instead of the current
1024  * supported_event_map[] array.
1025  */
1026 #define MAX_EVENT_ID 0x3c
1027 #define UNSUPPORTED_EVENT UINT16_MAX
1028 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1029 
1030 /*
1031  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1032  * of ARM event numbers to indices in our pm_events array.
1033  *
1034  * Note: Events in the 0x40XX range are not currently supported.
1035  */
1036 void pmu_init(ARMCPU *cpu)
1037 {
1038     unsigned int i;
1039 
1040     /*
1041      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1042      * events to them
1043      */
1044     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1045         supported_event_map[i] = UNSUPPORTED_EVENT;
1046     }
1047     cpu->pmceid0 = 0;
1048     cpu->pmceid1 = 0;
1049 
1050     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1051         const pm_event *cnt = &pm_events[i];
1052         assert(cnt->number <= MAX_EVENT_ID);
1053         /* We do not currently support events in the 0x40xx range */
1054         assert(cnt->number <= 0x3f);
1055 
1056         if (cnt->supported(&cpu->env)) {
1057             supported_event_map[cnt->number] = i;
1058             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1059             if (cnt->number & 0x20) {
1060                 cpu->pmceid1 |= event_mask;
1061             } else {
1062                 cpu->pmceid0 |= event_mask;
1063             }
1064         }
1065     }
1066 }
1067 
1068 /*
1069  * Check at runtime whether a PMU event is supported for the current machine
1070  */
1071 static bool event_supported(uint16_t number)
1072 {
1073     if (number > MAX_EVENT_ID) {
1074         return false;
1075     }
1076     return supported_event_map[number] != UNSUPPORTED_EVENT;
1077 }
1078 
1079 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1080                                    bool isread)
1081 {
1082     /* Performance monitor registers user accessibility is controlled
1083      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1084      * trapping to EL2 or EL3 for other accesses.
1085      */
1086     int el = arm_current_el(env);
1087     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1088 
1089     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1090         return CP_ACCESS_TRAP;
1091     }
1092     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
1093         return CP_ACCESS_TRAP_EL2;
1094     }
1095     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1096         return CP_ACCESS_TRAP_EL3;
1097     }
1098 
1099     return CP_ACCESS_OK;
1100 }
1101 
1102 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1103                                            const ARMCPRegInfo *ri,
1104                                            bool isread)
1105 {
1106     /* ER: event counter read trap control */
1107     if (arm_feature(env, ARM_FEATURE_V8)
1108         && arm_current_el(env) == 0
1109         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1110         && isread) {
1111         return CP_ACCESS_OK;
1112     }
1113 
1114     return pmreg_access(env, ri, isread);
1115 }
1116 
1117 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1118                                          const ARMCPRegInfo *ri,
1119                                          bool isread)
1120 {
1121     /* SW: software increment write trap control */
1122     if (arm_feature(env, ARM_FEATURE_V8)
1123         && arm_current_el(env) == 0
1124         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1125         && !isread) {
1126         return CP_ACCESS_OK;
1127     }
1128 
1129     return pmreg_access(env, ri, isread);
1130 }
1131 
1132 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1133                                         const ARMCPRegInfo *ri,
1134                                         bool isread)
1135 {
1136     /* ER: event counter read trap control */
1137     if (arm_feature(env, ARM_FEATURE_V8)
1138         && arm_current_el(env) == 0
1139         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1140         return CP_ACCESS_OK;
1141     }
1142 
1143     return pmreg_access(env, ri, isread);
1144 }
1145 
1146 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1147                                          const ARMCPRegInfo *ri,
1148                                          bool isread)
1149 {
1150     /* CR: cycle counter read trap control */
1151     if (arm_feature(env, ARM_FEATURE_V8)
1152         && arm_current_el(env) == 0
1153         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1154         && isread) {
1155         return CP_ACCESS_OK;
1156     }
1157 
1158     return pmreg_access(env, ri, isread);
1159 }
1160 
1161 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1162  * the current EL, security state, and register configuration.
1163  */
1164 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1165 {
1166     uint64_t filter;
1167     bool e, p, u, nsk, nsu, nsh, m;
1168     bool enabled, prohibited, filtered;
1169     bool secure = arm_is_secure(env);
1170     int el = arm_current_el(env);
1171     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1172     uint8_t hpmn = mdcr_el2 & MDCR_HPMN;
1173 
1174     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1175         return false;
1176     }
1177 
1178     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1179             (counter < hpmn || counter == 31)) {
1180         e = env->cp15.c9_pmcr & PMCRE;
1181     } else {
1182         e = mdcr_el2 & MDCR_HPME;
1183     }
1184     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1185 
1186     if (!secure) {
1187         if (el == 2 && (counter < hpmn || counter == 31)) {
1188             prohibited = mdcr_el2 & MDCR_HPMD;
1189         } else {
1190             prohibited = false;
1191         }
1192     } else {
1193         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1194            !(env->cp15.mdcr_el3 & MDCR_SPME);
1195     }
1196 
1197     if (prohibited && counter == 31) {
1198         prohibited = env->cp15.c9_pmcr & PMCRDP;
1199     }
1200 
1201     if (counter == 31) {
1202         filter = env->cp15.pmccfiltr_el0;
1203     } else {
1204         filter = env->cp15.c14_pmevtyper[counter];
1205     }
1206 
1207     p   = filter & PMXEVTYPER_P;
1208     u   = filter & PMXEVTYPER_U;
1209     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1210     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1211     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1212     m   = arm_el_is_aa64(env, 1) &&
1213               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1214 
1215     if (el == 0) {
1216         filtered = secure ? u : u != nsu;
1217     } else if (el == 1) {
1218         filtered = secure ? p : p != nsk;
1219     } else if (el == 2) {
1220         filtered = !nsh;
1221     } else { /* EL3 */
1222         filtered = m != p;
1223     }
1224 
1225     if (counter != 31) {
1226         /*
1227          * If not checking PMCCNTR, ensure the counter is setup to an event we
1228          * support
1229          */
1230         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1231         if (!event_supported(event)) {
1232             return false;
1233         }
1234     }
1235 
1236     return enabled && !prohibited && !filtered;
1237 }
1238 
1239 static void pmu_update_irq(CPUARMState *env)
1240 {
1241     ARMCPU *cpu = env_archcpu(env);
1242     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1243             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1244 }
1245 
1246 /*
1247  * Ensure c15_ccnt is the guest-visible count so that operations such as
1248  * enabling/disabling the counter or filtering, modifying the count itself,
1249  * etc. can be done logically. This is essentially a no-op if the counter is
1250  * not enabled at the time of the call.
1251  */
1252 static void pmccntr_op_start(CPUARMState *env)
1253 {
1254     uint64_t cycles = cycles_get_count(env);
1255 
1256     if (pmu_counter_enabled(env, 31)) {
1257         uint64_t eff_cycles = cycles;
1258         if (env->cp15.c9_pmcr & PMCRD) {
1259             /* Increment once every 64 processor clock cycles */
1260             eff_cycles /= 64;
1261         }
1262 
1263         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1264 
1265         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1266                                  1ull << 63 : 1ull << 31;
1267         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1268             env->cp15.c9_pmovsr |= (1 << 31);
1269             pmu_update_irq(env);
1270         }
1271 
1272         env->cp15.c15_ccnt = new_pmccntr;
1273     }
1274     env->cp15.c15_ccnt_delta = cycles;
1275 }
1276 
1277 /*
1278  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1279  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1280  * pmccntr_op_start.
1281  */
1282 static void pmccntr_op_finish(CPUARMState *env)
1283 {
1284     if (pmu_counter_enabled(env, 31)) {
1285 #ifndef CONFIG_USER_ONLY
1286         /* Calculate when the counter will next overflow */
1287         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1288         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1289             remaining_cycles = (uint32_t)remaining_cycles;
1290         }
1291         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1292 
1293         if (overflow_in > 0) {
1294             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1295                 overflow_in;
1296             ARMCPU *cpu = env_archcpu(env);
1297             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1298         }
1299 #endif
1300 
1301         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1302         if (env->cp15.c9_pmcr & PMCRD) {
1303             /* Increment once every 64 processor clock cycles */
1304             prev_cycles /= 64;
1305         }
1306         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1307     }
1308 }
1309 
1310 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1311 {
1312 
1313     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1314     uint64_t count = 0;
1315     if (event_supported(event)) {
1316         uint16_t event_idx = supported_event_map[event];
1317         count = pm_events[event_idx].get_count(env);
1318     }
1319 
1320     if (pmu_counter_enabled(env, counter)) {
1321         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1322 
1323         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1324             env->cp15.c9_pmovsr |= (1 << counter);
1325             pmu_update_irq(env);
1326         }
1327         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1328     }
1329     env->cp15.c14_pmevcntr_delta[counter] = count;
1330 }
1331 
1332 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1333 {
1334     if (pmu_counter_enabled(env, counter)) {
1335 #ifndef CONFIG_USER_ONLY
1336         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1337         uint16_t event_idx = supported_event_map[event];
1338         uint64_t delta = UINT32_MAX -
1339             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1340         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1341 
1342         if (overflow_in > 0) {
1343             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1344                 overflow_in;
1345             ARMCPU *cpu = env_archcpu(env);
1346             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1347         }
1348 #endif
1349 
1350         env->cp15.c14_pmevcntr_delta[counter] -=
1351             env->cp15.c14_pmevcntr[counter];
1352     }
1353 }
1354 
1355 void pmu_op_start(CPUARMState *env)
1356 {
1357     unsigned int i;
1358     pmccntr_op_start(env);
1359     for (i = 0; i < pmu_num_counters(env); i++) {
1360         pmevcntr_op_start(env, i);
1361     }
1362 }
1363 
1364 void pmu_op_finish(CPUARMState *env)
1365 {
1366     unsigned int i;
1367     pmccntr_op_finish(env);
1368     for (i = 0; i < pmu_num_counters(env); i++) {
1369         pmevcntr_op_finish(env, i);
1370     }
1371 }
1372 
1373 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1374 {
1375     pmu_op_start(&cpu->env);
1376 }
1377 
1378 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1379 {
1380     pmu_op_finish(&cpu->env);
1381 }
1382 
1383 void arm_pmu_timer_cb(void *opaque)
1384 {
1385     ARMCPU *cpu = opaque;
1386 
1387     /*
1388      * Update all the counter values based on the current underlying counts,
1389      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1390      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1391      * counter may expire.
1392      */
1393     pmu_op_start(&cpu->env);
1394     pmu_op_finish(&cpu->env);
1395 }
1396 
1397 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1398                        uint64_t value)
1399 {
1400     pmu_op_start(env);
1401 
1402     if (value & PMCRC) {
1403         /* The counter has been reset */
1404         env->cp15.c15_ccnt = 0;
1405     }
1406 
1407     if (value & PMCRP) {
1408         unsigned int i;
1409         for (i = 0; i < pmu_num_counters(env); i++) {
1410             env->cp15.c14_pmevcntr[i] = 0;
1411         }
1412     }
1413 
1414     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1415     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1416 
1417     pmu_op_finish(env);
1418 }
1419 
1420 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1421                           uint64_t value)
1422 {
1423     unsigned int i;
1424     for (i = 0; i < pmu_num_counters(env); i++) {
1425         /* Increment a counter's count iff: */
1426         if ((value & (1 << i)) && /* counter's bit is set */
1427                 /* counter is enabled and not filtered */
1428                 pmu_counter_enabled(env, i) &&
1429                 /* counter is SW_INCR */
1430                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1431             pmevcntr_op_start(env, i);
1432 
1433             /*
1434              * Detect if this write causes an overflow since we can't predict
1435              * PMSWINC overflows like we can for other events
1436              */
1437             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1438 
1439             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1440                 env->cp15.c9_pmovsr |= (1 << i);
1441                 pmu_update_irq(env);
1442             }
1443 
1444             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1445 
1446             pmevcntr_op_finish(env, i);
1447         }
1448     }
1449 }
1450 
1451 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1452 {
1453     uint64_t ret;
1454     pmccntr_op_start(env);
1455     ret = env->cp15.c15_ccnt;
1456     pmccntr_op_finish(env);
1457     return ret;
1458 }
1459 
1460 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1461                          uint64_t value)
1462 {
1463     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1464      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1465      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1466      * accessed.
1467      */
1468     env->cp15.c9_pmselr = value & 0x1f;
1469 }
1470 
1471 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1472                         uint64_t value)
1473 {
1474     pmccntr_op_start(env);
1475     env->cp15.c15_ccnt = value;
1476     pmccntr_op_finish(env);
1477 }
1478 
1479 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1480                             uint64_t value)
1481 {
1482     uint64_t cur_val = pmccntr_read(env, NULL);
1483 
1484     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1485 }
1486 
1487 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1488                             uint64_t value)
1489 {
1490     pmccntr_op_start(env);
1491     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1492     pmccntr_op_finish(env);
1493 }
1494 
1495 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1496                             uint64_t value)
1497 {
1498     pmccntr_op_start(env);
1499     /* M is not accessible from AArch32 */
1500     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1501         (value & PMCCFILTR);
1502     pmccntr_op_finish(env);
1503 }
1504 
1505 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1506 {
1507     /* M is not visible in AArch32 */
1508     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1509 }
1510 
1511 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1512                             uint64_t value)
1513 {
1514     value &= pmu_counter_mask(env);
1515     env->cp15.c9_pmcnten |= value;
1516 }
1517 
1518 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1519                              uint64_t value)
1520 {
1521     value &= pmu_counter_mask(env);
1522     env->cp15.c9_pmcnten &= ~value;
1523 }
1524 
1525 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1526                          uint64_t value)
1527 {
1528     value &= pmu_counter_mask(env);
1529     env->cp15.c9_pmovsr &= ~value;
1530     pmu_update_irq(env);
1531 }
1532 
1533 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1534                          uint64_t value)
1535 {
1536     value &= pmu_counter_mask(env);
1537     env->cp15.c9_pmovsr |= value;
1538     pmu_update_irq(env);
1539 }
1540 
1541 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1542                              uint64_t value, const uint8_t counter)
1543 {
1544     if (counter == 31) {
1545         pmccfiltr_write(env, ri, value);
1546     } else if (counter < pmu_num_counters(env)) {
1547         pmevcntr_op_start(env, counter);
1548 
1549         /*
1550          * If this counter's event type is changing, store the current
1551          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1552          * pmevcntr_op_finish has the correct baseline when it converts back to
1553          * a delta.
1554          */
1555         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1556             PMXEVTYPER_EVTCOUNT;
1557         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1558         if (old_event != new_event) {
1559             uint64_t count = 0;
1560             if (event_supported(new_event)) {
1561                 uint16_t event_idx = supported_event_map[new_event];
1562                 count = pm_events[event_idx].get_count(env);
1563             }
1564             env->cp15.c14_pmevcntr_delta[counter] = count;
1565         }
1566 
1567         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1568         pmevcntr_op_finish(env, counter);
1569     }
1570     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1571      * PMSELR value is equal to or greater than the number of implemented
1572      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1573      */
1574 }
1575 
1576 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1577                                const uint8_t counter)
1578 {
1579     if (counter == 31) {
1580         return env->cp15.pmccfiltr_el0;
1581     } else if (counter < pmu_num_counters(env)) {
1582         return env->cp15.c14_pmevtyper[counter];
1583     } else {
1584       /*
1585        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1586        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1587        */
1588         return 0;
1589     }
1590 }
1591 
1592 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1593                               uint64_t value)
1594 {
1595     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1596     pmevtyper_write(env, ri, value, counter);
1597 }
1598 
1599 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1600                                uint64_t value)
1601 {
1602     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1603     env->cp15.c14_pmevtyper[counter] = value;
1604 
1605     /*
1606      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1607      * pmu_op_finish calls when loading saved state for a migration. Because
1608      * we're potentially updating the type of event here, the value written to
1609      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1610      * different counter type. Therefore, we need to set this value to the
1611      * current count for the counter type we're writing so that pmu_op_finish
1612      * has the correct count for its calculation.
1613      */
1614     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1615     if (event_supported(event)) {
1616         uint16_t event_idx = supported_event_map[event];
1617         env->cp15.c14_pmevcntr_delta[counter] =
1618             pm_events[event_idx].get_count(env);
1619     }
1620 }
1621 
1622 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1623 {
1624     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1625     return pmevtyper_read(env, ri, counter);
1626 }
1627 
1628 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1629                              uint64_t value)
1630 {
1631     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1632 }
1633 
1634 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1635 {
1636     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1637 }
1638 
1639 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1640                              uint64_t value, uint8_t counter)
1641 {
1642     if (counter < pmu_num_counters(env)) {
1643         pmevcntr_op_start(env, counter);
1644         env->cp15.c14_pmevcntr[counter] = value;
1645         pmevcntr_op_finish(env, counter);
1646     }
1647     /*
1648      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1649      * are CONSTRAINED UNPREDICTABLE.
1650      */
1651 }
1652 
1653 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1654                               uint8_t counter)
1655 {
1656     if (counter < pmu_num_counters(env)) {
1657         uint64_t ret;
1658         pmevcntr_op_start(env, counter);
1659         ret = env->cp15.c14_pmevcntr[counter];
1660         pmevcntr_op_finish(env, counter);
1661         return ret;
1662     } else {
1663       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1664        * are CONSTRAINED UNPREDICTABLE. */
1665         return 0;
1666     }
1667 }
1668 
1669 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1670                              uint64_t value)
1671 {
1672     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1673     pmevcntr_write(env, ri, value, counter);
1674 }
1675 
1676 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1677 {
1678     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1679     return pmevcntr_read(env, ri, counter);
1680 }
1681 
1682 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1683                              uint64_t value)
1684 {
1685     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1686     assert(counter < pmu_num_counters(env));
1687     env->cp15.c14_pmevcntr[counter] = value;
1688     pmevcntr_write(env, ri, value, counter);
1689 }
1690 
1691 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1692 {
1693     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1694     assert(counter < pmu_num_counters(env));
1695     return env->cp15.c14_pmevcntr[counter];
1696 }
1697 
1698 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1699                              uint64_t value)
1700 {
1701     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1702 }
1703 
1704 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1705 {
1706     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1707 }
1708 
1709 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1710                             uint64_t value)
1711 {
1712     if (arm_feature(env, ARM_FEATURE_V8)) {
1713         env->cp15.c9_pmuserenr = value & 0xf;
1714     } else {
1715         env->cp15.c9_pmuserenr = value & 1;
1716     }
1717 }
1718 
1719 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1720                              uint64_t value)
1721 {
1722     /* We have no event counters so only the C bit can be changed */
1723     value &= pmu_counter_mask(env);
1724     env->cp15.c9_pminten |= value;
1725     pmu_update_irq(env);
1726 }
1727 
1728 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1729                              uint64_t value)
1730 {
1731     value &= pmu_counter_mask(env);
1732     env->cp15.c9_pminten &= ~value;
1733     pmu_update_irq(env);
1734 }
1735 
1736 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1737                        uint64_t value)
1738 {
1739     /* Note that even though the AArch64 view of this register has bits
1740      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1741      * architectural requirements for bits which are RES0 only in some
1742      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1743      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1744      */
1745     raw_write(env, ri, value & ~0x1FULL);
1746 }
1747 
1748 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1749 {
1750     /* Begin with base v8.0 state.  */
1751     uint32_t valid_mask = 0x3fff;
1752     ARMCPU *cpu = env_archcpu(env);
1753 
1754     if (ri->state == ARM_CP_STATE_AA64) {
1755         if (arm_feature(env, ARM_FEATURE_AARCH64) &&
1756             !cpu_isar_feature(aa64_aa32_el1, cpu)) {
1757                 value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1758         }
1759         valid_mask &= ~SCR_NET;
1760 
1761         if (cpu_isar_feature(aa64_ras, cpu)) {
1762             valid_mask |= SCR_TERR;
1763         }
1764         if (cpu_isar_feature(aa64_lor, cpu)) {
1765             valid_mask |= SCR_TLOR;
1766         }
1767         if (cpu_isar_feature(aa64_pauth, cpu)) {
1768             valid_mask |= SCR_API | SCR_APK;
1769         }
1770         if (cpu_isar_feature(aa64_sel2, cpu)) {
1771             valid_mask |= SCR_EEL2;
1772         }
1773         if (cpu_isar_feature(aa64_mte, cpu)) {
1774             valid_mask |= SCR_ATA;
1775         }
1776         if (cpu_isar_feature(aa64_scxtnum, cpu)) {
1777             valid_mask |= SCR_ENSCXT;
1778         }
1779     } else {
1780         valid_mask &= ~(SCR_RW | SCR_ST);
1781         if (cpu_isar_feature(aa32_ras, cpu)) {
1782             valid_mask |= SCR_TERR;
1783         }
1784     }
1785 
1786     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1787         valid_mask &= ~SCR_HCE;
1788 
1789         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1790          * supported if EL2 exists. The bit is UNK/SBZP when
1791          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1792          * when EL2 is unavailable.
1793          * On ARMv8, this bit is always available.
1794          */
1795         if (arm_feature(env, ARM_FEATURE_V7) &&
1796             !arm_feature(env, ARM_FEATURE_V8)) {
1797             valid_mask &= ~SCR_SMD;
1798         }
1799     }
1800 
1801     /* Clear all-context RES0 bits.  */
1802     value &= valid_mask;
1803     raw_write(env, ri, value);
1804 }
1805 
1806 static void scr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1807 {
1808     /*
1809      * scr_write will set the RES1 bits on an AArch64-only CPU.
1810      * The reset value will be 0x30 on an AArch64-only CPU and 0 otherwise.
1811      */
1812     scr_write(env, ri, 0);
1813 }
1814 
1815 static CPAccessResult access_aa64_tid2(CPUARMState *env,
1816                                        const ARMCPRegInfo *ri,
1817                                        bool isread)
1818 {
1819     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
1820         return CP_ACCESS_TRAP_EL2;
1821     }
1822 
1823     return CP_ACCESS_OK;
1824 }
1825 
1826 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1827 {
1828     ARMCPU *cpu = env_archcpu(env);
1829 
1830     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1831      * bank
1832      */
1833     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1834                                         ri->secure & ARM_CP_SECSTATE_S);
1835 
1836     return cpu->ccsidr[index];
1837 }
1838 
1839 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1840                          uint64_t value)
1841 {
1842     raw_write(env, ri, value & 0xf);
1843 }
1844 
1845 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1846 {
1847     CPUState *cs = env_cpu(env);
1848     bool el1 = arm_current_el(env) == 1;
1849     uint64_t hcr_el2 = el1 ? arm_hcr_el2_eff(env) : 0;
1850     uint64_t ret = 0;
1851 
1852     if (hcr_el2 & HCR_IMO) {
1853         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1854             ret |= CPSR_I;
1855         }
1856     } else {
1857         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1858             ret |= CPSR_I;
1859         }
1860     }
1861 
1862     if (hcr_el2 & HCR_FMO) {
1863         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1864             ret |= CPSR_F;
1865         }
1866     } else {
1867         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1868             ret |= CPSR_F;
1869         }
1870     }
1871 
1872     if (hcr_el2 & HCR_AMO) {
1873         if (cs->interrupt_request & CPU_INTERRUPT_VSERR) {
1874             ret |= CPSR_A;
1875         }
1876     }
1877 
1878     return ret;
1879 }
1880 
1881 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1882                                        bool isread)
1883 {
1884     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
1885         return CP_ACCESS_TRAP_EL2;
1886     }
1887 
1888     return CP_ACCESS_OK;
1889 }
1890 
1891 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1892                                        bool isread)
1893 {
1894     if (arm_feature(env, ARM_FEATURE_V8)) {
1895         return access_aa64_tid1(env, ri, isread);
1896     }
1897 
1898     return CP_ACCESS_OK;
1899 }
1900 
1901 static const ARMCPRegInfo v7_cp_reginfo[] = {
1902     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1903     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1904       .access = PL1_W, .type = ARM_CP_NOP },
1905     /* Performance monitors are implementation defined in v7,
1906      * but with an ARM recommended set of registers, which we
1907      * follow.
1908      *
1909      * Performance registers fall into three categories:
1910      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1911      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1912      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1913      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1914      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1915      */
1916     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1917       .access = PL0_RW, .type = ARM_CP_ALIAS,
1918       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1919       .writefn = pmcntenset_write,
1920       .accessfn = pmreg_access,
1921       .raw_writefn = raw_write },
1922     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1923       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1924       .access = PL0_RW, .accessfn = pmreg_access,
1925       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1926       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1927     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1928       .access = PL0_RW,
1929       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1930       .accessfn = pmreg_access,
1931       .writefn = pmcntenclr_write,
1932       .type = ARM_CP_ALIAS },
1933     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1934       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1935       .access = PL0_RW, .accessfn = pmreg_access,
1936       .type = ARM_CP_ALIAS,
1937       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1938       .writefn = pmcntenclr_write },
1939     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1940       .access = PL0_RW, .type = ARM_CP_IO,
1941       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1942       .accessfn = pmreg_access,
1943       .writefn = pmovsr_write,
1944       .raw_writefn = raw_write },
1945     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1946       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1947       .access = PL0_RW, .accessfn = pmreg_access,
1948       .type = ARM_CP_ALIAS | ARM_CP_IO,
1949       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1950       .writefn = pmovsr_write,
1951       .raw_writefn = raw_write },
1952     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1953       .access = PL0_W, .accessfn = pmreg_access_swinc,
1954       .type = ARM_CP_NO_RAW | ARM_CP_IO,
1955       .writefn = pmswinc_write },
1956     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
1957       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
1958       .access = PL0_W, .accessfn = pmreg_access_swinc,
1959       .type = ARM_CP_NO_RAW | ARM_CP_IO,
1960       .writefn = pmswinc_write },
1961     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1962       .access = PL0_RW, .type = ARM_CP_ALIAS,
1963       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1964       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1965       .raw_writefn = raw_write},
1966     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1967       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1968       .access = PL0_RW, .accessfn = pmreg_access_selr,
1969       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1970       .writefn = pmselr_write, .raw_writefn = raw_write, },
1971     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1972       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
1973       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1974       .accessfn = pmreg_access_ccntr },
1975     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1976       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1977       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1978       .type = ARM_CP_IO,
1979       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
1980       .readfn = pmccntr_read, .writefn = pmccntr_write,
1981       .raw_readfn = raw_read, .raw_writefn = raw_write, },
1982     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
1983       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
1984       .access = PL0_RW, .accessfn = pmreg_access,
1985       .type = ARM_CP_ALIAS | ARM_CP_IO,
1986       .resetvalue = 0, },
1987     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1988       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1989       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
1990       .access = PL0_RW, .accessfn = pmreg_access,
1991       .type = ARM_CP_IO,
1992       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1993       .resetvalue = 0, },
1994     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1995       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1996       .accessfn = pmreg_access,
1997       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1998     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1999       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2000       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2001       .accessfn = pmreg_access,
2002       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2003     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2004       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2005       .accessfn = pmreg_access_xevcntr,
2006       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2007     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2008       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2009       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2010       .accessfn = pmreg_access_xevcntr,
2011       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2012     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2013       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2014       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2015       .resetvalue = 0,
2016       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2017     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2018       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2019       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2020       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2021       .resetvalue = 0,
2022       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2023     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2024       .access = PL1_RW, .accessfn = access_tpm,
2025       .type = ARM_CP_ALIAS | ARM_CP_IO,
2026       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2027       .resetvalue = 0,
2028       .writefn = pmintenset_write, .raw_writefn = raw_write },
2029     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2030       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2031       .access = PL1_RW, .accessfn = access_tpm,
2032       .type = ARM_CP_IO,
2033       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2034       .writefn = pmintenset_write, .raw_writefn = raw_write,
2035       .resetvalue = 0x0 },
2036     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2037       .access = PL1_RW, .accessfn = access_tpm,
2038       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2039       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2040       .writefn = pmintenclr_write, },
2041     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2042       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2043       .access = PL1_RW, .accessfn = access_tpm,
2044       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2045       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2046       .writefn = pmintenclr_write },
2047     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2048       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2049       .access = PL1_R,
2050       .accessfn = access_aa64_tid2,
2051       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2052     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2053       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2054       .access = PL1_RW,
2055       .accessfn = access_aa64_tid2,
2056       .writefn = csselr_write, .resetvalue = 0,
2057       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2058                              offsetof(CPUARMState, cp15.csselr_ns) } },
2059     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2060      * just RAZ for all cores:
2061      */
2062     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2063       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2064       .access = PL1_R, .type = ARM_CP_CONST,
2065       .accessfn = access_aa64_tid1,
2066       .resetvalue = 0 },
2067     /* Auxiliary fault status registers: these also are IMPDEF, and we
2068      * choose to RAZ/WI for all cores.
2069      */
2070     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2071       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2072       .access = PL1_RW, .accessfn = access_tvm_trvm,
2073       .type = ARM_CP_CONST, .resetvalue = 0 },
2074     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2075       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2076       .access = PL1_RW, .accessfn = access_tvm_trvm,
2077       .type = ARM_CP_CONST, .resetvalue = 0 },
2078     /* MAIR can just read-as-written because we don't implement caches
2079      * and so don't need to care about memory attributes.
2080      */
2081     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2082       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2083       .access = PL1_RW, .accessfn = access_tvm_trvm,
2084       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2085       .resetvalue = 0 },
2086     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2087       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2088       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2089       .resetvalue = 0 },
2090     /* For non-long-descriptor page tables these are PRRR and NMRR;
2091      * regardless they still act as reads-as-written for QEMU.
2092      */
2093      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2094       * allows them to assign the correct fieldoffset based on the endianness
2095       * handled in the field definitions.
2096       */
2097     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2098       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2099       .access = PL1_RW, .accessfn = access_tvm_trvm,
2100       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2101                              offsetof(CPUARMState, cp15.mair0_ns) },
2102       .resetfn = arm_cp_reset_ignore },
2103     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2104       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2105       .access = PL1_RW, .accessfn = access_tvm_trvm,
2106       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2107                              offsetof(CPUARMState, cp15.mair1_ns) },
2108       .resetfn = arm_cp_reset_ignore },
2109     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2110       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2111       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2112     /* 32 bit ITLB invalidates */
2113     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2114       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2115       .writefn = tlbiall_write },
2116     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2117       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2118       .writefn = tlbimva_write },
2119     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2120       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2121       .writefn = tlbiasid_write },
2122     /* 32 bit DTLB invalidates */
2123     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2124       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2125       .writefn = tlbiall_write },
2126     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2127       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2128       .writefn = tlbimva_write },
2129     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2130       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2131       .writefn = tlbiasid_write },
2132     /* 32 bit TLB invalidates */
2133     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2134       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2135       .writefn = tlbiall_write },
2136     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2137       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2138       .writefn = tlbimva_write },
2139     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2140       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2141       .writefn = tlbiasid_write },
2142     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2143       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2144       .writefn = tlbimvaa_write },
2145 };
2146 
2147 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2148     /* 32 bit TLB invalidates, Inner Shareable */
2149     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2150       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2151       .writefn = tlbiall_is_write },
2152     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2153       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2154       .writefn = tlbimva_is_write },
2155     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2156       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2157       .writefn = tlbiasid_is_write },
2158     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2159       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2160       .writefn = tlbimvaa_is_write },
2161 };
2162 
2163 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2164     /* PMOVSSET is not implemented in v7 before v7ve */
2165     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2166       .access = PL0_RW, .accessfn = pmreg_access,
2167       .type = ARM_CP_ALIAS | ARM_CP_IO,
2168       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2169       .writefn = pmovsset_write,
2170       .raw_writefn = raw_write },
2171     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2172       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2173       .access = PL0_RW, .accessfn = pmreg_access,
2174       .type = ARM_CP_ALIAS | ARM_CP_IO,
2175       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2176       .writefn = pmovsset_write,
2177       .raw_writefn = raw_write },
2178 };
2179 
2180 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2181                         uint64_t value)
2182 {
2183     value &= 1;
2184     env->teecr = value;
2185 }
2186 
2187 static CPAccessResult teecr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2188                                    bool isread)
2189 {
2190     /*
2191      * HSTR.TTEE only exists in v7A, not v8A, but v8A doesn't have T2EE
2192      * at all, so we don't need to check whether we're v8A.
2193      */
2194     if (arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
2195         (env->cp15.hstr_el2 & HSTR_TTEE)) {
2196         return CP_ACCESS_TRAP_EL2;
2197     }
2198     return CP_ACCESS_OK;
2199 }
2200 
2201 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2202                                     bool isread)
2203 {
2204     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2205         return CP_ACCESS_TRAP;
2206     }
2207     return teecr_access(env, ri, isread);
2208 }
2209 
2210 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2211     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2212       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2213       .resetvalue = 0,
2214       .writefn = teecr_write, .accessfn = teecr_access },
2215     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2216       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2217       .accessfn = teehbr_access, .resetvalue = 0 },
2218 };
2219 
2220 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2221     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2222       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2223       .access = PL0_RW,
2224       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2225     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2226       .access = PL0_RW,
2227       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2228                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2229       .resetfn = arm_cp_reset_ignore },
2230     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2231       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2232       .access = PL0_R|PL1_W,
2233       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2234       .resetvalue = 0},
2235     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2236       .access = PL0_R|PL1_W,
2237       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2238                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2239       .resetfn = arm_cp_reset_ignore },
2240     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2241       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2242       .access = PL1_RW,
2243       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2244     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2245       .access = PL1_RW,
2246       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2247                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2248       .resetvalue = 0 },
2249 };
2250 
2251 #ifndef CONFIG_USER_ONLY
2252 
2253 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2254                                        bool isread)
2255 {
2256     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2257      * Writable only at the highest implemented exception level.
2258      */
2259     int el = arm_current_el(env);
2260     uint64_t hcr;
2261     uint32_t cntkctl;
2262 
2263     switch (el) {
2264     case 0:
2265         hcr = arm_hcr_el2_eff(env);
2266         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2267             cntkctl = env->cp15.cnthctl_el2;
2268         } else {
2269             cntkctl = env->cp15.c14_cntkctl;
2270         }
2271         if (!extract32(cntkctl, 0, 2)) {
2272             return CP_ACCESS_TRAP;
2273         }
2274         break;
2275     case 1:
2276         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2277             arm_is_secure_below_el3(env)) {
2278             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2279             return CP_ACCESS_TRAP_UNCATEGORIZED;
2280         }
2281         break;
2282     case 2:
2283     case 3:
2284         break;
2285     }
2286 
2287     if (!isread && el < arm_highest_el(env)) {
2288         return CP_ACCESS_TRAP_UNCATEGORIZED;
2289     }
2290 
2291     return CP_ACCESS_OK;
2292 }
2293 
2294 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2295                                         bool isread)
2296 {
2297     unsigned int cur_el = arm_current_el(env);
2298     bool has_el2 = arm_is_el2_enabled(env);
2299     uint64_t hcr = arm_hcr_el2_eff(env);
2300 
2301     switch (cur_el) {
2302     case 0:
2303         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2304         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2305             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2306                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2307         }
2308 
2309         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2310         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2311             return CP_ACCESS_TRAP;
2312         }
2313 
2314         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2315         if (hcr & HCR_E2H) {
2316             if (timeridx == GTIMER_PHYS &&
2317                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2318                 return CP_ACCESS_TRAP_EL2;
2319             }
2320         } else {
2321             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2322             if (has_el2 && timeridx == GTIMER_PHYS &&
2323                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2324                 return CP_ACCESS_TRAP_EL2;
2325             }
2326         }
2327         break;
2328 
2329     case 1:
2330         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2331         if (has_el2 && timeridx == GTIMER_PHYS &&
2332             (hcr & HCR_E2H
2333              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2334              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2335             return CP_ACCESS_TRAP_EL2;
2336         }
2337         break;
2338     }
2339     return CP_ACCESS_OK;
2340 }
2341 
2342 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2343                                       bool isread)
2344 {
2345     unsigned int cur_el = arm_current_el(env);
2346     bool has_el2 = arm_is_el2_enabled(env);
2347     uint64_t hcr = arm_hcr_el2_eff(env);
2348 
2349     switch (cur_el) {
2350     case 0:
2351         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2352             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2353             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2354                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2355         }
2356 
2357         /*
2358          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2359          * EL0 if EL0[PV]TEN is zero.
2360          */
2361         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2362             return CP_ACCESS_TRAP;
2363         }
2364         /* fall through */
2365 
2366     case 1:
2367         if (has_el2 && timeridx == GTIMER_PHYS) {
2368             if (hcr & HCR_E2H) {
2369                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2370                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2371                     return CP_ACCESS_TRAP_EL2;
2372                 }
2373             } else {
2374                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2375                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2376                     return CP_ACCESS_TRAP_EL2;
2377                 }
2378             }
2379         }
2380         break;
2381     }
2382     return CP_ACCESS_OK;
2383 }
2384 
2385 static CPAccessResult gt_pct_access(CPUARMState *env,
2386                                     const ARMCPRegInfo *ri,
2387                                     bool isread)
2388 {
2389     return gt_counter_access(env, GTIMER_PHYS, isread);
2390 }
2391 
2392 static CPAccessResult gt_vct_access(CPUARMState *env,
2393                                     const ARMCPRegInfo *ri,
2394                                     bool isread)
2395 {
2396     return gt_counter_access(env, GTIMER_VIRT, isread);
2397 }
2398 
2399 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2400                                        bool isread)
2401 {
2402     return gt_timer_access(env, GTIMER_PHYS, isread);
2403 }
2404 
2405 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2406                                        bool isread)
2407 {
2408     return gt_timer_access(env, GTIMER_VIRT, isread);
2409 }
2410 
2411 static CPAccessResult gt_stimer_access(CPUARMState *env,
2412                                        const ARMCPRegInfo *ri,
2413                                        bool isread)
2414 {
2415     /* The AArch64 register view of the secure physical timer is
2416      * always accessible from EL3, and configurably accessible from
2417      * Secure EL1.
2418      */
2419     switch (arm_current_el(env)) {
2420     case 1:
2421         if (!arm_is_secure(env)) {
2422             return CP_ACCESS_TRAP;
2423         }
2424         if (!(env->cp15.scr_el3 & SCR_ST)) {
2425             return CP_ACCESS_TRAP_EL3;
2426         }
2427         return CP_ACCESS_OK;
2428     case 0:
2429     case 2:
2430         return CP_ACCESS_TRAP;
2431     case 3:
2432         return CP_ACCESS_OK;
2433     default:
2434         g_assert_not_reached();
2435     }
2436 }
2437 
2438 static uint64_t gt_get_countervalue(CPUARMState *env)
2439 {
2440     ARMCPU *cpu = env_archcpu(env);
2441 
2442     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2443 }
2444 
2445 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2446 {
2447     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2448 
2449     if (gt->ctl & 1) {
2450         /* Timer enabled: calculate and set current ISTATUS, irq, and
2451          * reset timer to when ISTATUS next has to change
2452          */
2453         uint64_t offset = timeridx == GTIMER_VIRT ?
2454                                       cpu->env.cp15.cntvoff_el2 : 0;
2455         uint64_t count = gt_get_countervalue(&cpu->env);
2456         /* Note that this must be unsigned 64 bit arithmetic: */
2457         int istatus = count - offset >= gt->cval;
2458         uint64_t nexttick;
2459         int irqstate;
2460 
2461         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2462 
2463         irqstate = (istatus && !(gt->ctl & 2));
2464         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2465 
2466         if (istatus) {
2467             /* Next transition is when count rolls back over to zero */
2468             nexttick = UINT64_MAX;
2469         } else {
2470             /* Next transition is when we hit cval */
2471             nexttick = gt->cval + offset;
2472         }
2473         /* Note that the desired next expiry time might be beyond the
2474          * signed-64-bit range of a QEMUTimer -- in this case we just
2475          * set the timer for as far in the future as possible. When the
2476          * timer expires we will reset the timer for any remaining period.
2477          */
2478         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2479             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2480         } else {
2481             timer_mod(cpu->gt_timer[timeridx], nexttick);
2482         }
2483         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2484     } else {
2485         /* Timer disabled: ISTATUS and timer output always clear */
2486         gt->ctl &= ~4;
2487         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2488         timer_del(cpu->gt_timer[timeridx]);
2489         trace_arm_gt_recalc_disabled(timeridx);
2490     }
2491 }
2492 
2493 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2494                            int timeridx)
2495 {
2496     ARMCPU *cpu = env_archcpu(env);
2497 
2498     timer_del(cpu->gt_timer[timeridx]);
2499 }
2500 
2501 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2502 {
2503     return gt_get_countervalue(env);
2504 }
2505 
2506 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2507 {
2508     uint64_t hcr;
2509 
2510     switch (arm_current_el(env)) {
2511     case 2:
2512         hcr = arm_hcr_el2_eff(env);
2513         if (hcr & HCR_E2H) {
2514             return 0;
2515         }
2516         break;
2517     case 0:
2518         hcr = arm_hcr_el2_eff(env);
2519         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2520             return 0;
2521         }
2522         break;
2523     }
2524 
2525     return env->cp15.cntvoff_el2;
2526 }
2527 
2528 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2529 {
2530     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2531 }
2532 
2533 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2534                           int timeridx,
2535                           uint64_t value)
2536 {
2537     trace_arm_gt_cval_write(timeridx, value);
2538     env->cp15.c14_timer[timeridx].cval = value;
2539     gt_recalc_timer(env_archcpu(env), timeridx);
2540 }
2541 
2542 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2543                              int timeridx)
2544 {
2545     uint64_t offset = 0;
2546 
2547     switch (timeridx) {
2548     case GTIMER_VIRT:
2549     case GTIMER_HYPVIRT:
2550         offset = gt_virt_cnt_offset(env);
2551         break;
2552     }
2553 
2554     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2555                       (gt_get_countervalue(env) - offset));
2556 }
2557 
2558 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2559                           int timeridx,
2560                           uint64_t value)
2561 {
2562     uint64_t offset = 0;
2563 
2564     switch (timeridx) {
2565     case GTIMER_VIRT:
2566     case GTIMER_HYPVIRT:
2567         offset = gt_virt_cnt_offset(env);
2568         break;
2569     }
2570 
2571     trace_arm_gt_tval_write(timeridx, value);
2572     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2573                                          sextract64(value, 0, 32);
2574     gt_recalc_timer(env_archcpu(env), timeridx);
2575 }
2576 
2577 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2578                          int timeridx,
2579                          uint64_t value)
2580 {
2581     ARMCPU *cpu = env_archcpu(env);
2582     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2583 
2584     trace_arm_gt_ctl_write(timeridx, value);
2585     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2586     if ((oldval ^ value) & 1) {
2587         /* Enable toggled */
2588         gt_recalc_timer(cpu, timeridx);
2589     } else if ((oldval ^ value) & 2) {
2590         /* IMASK toggled: don't need to recalculate,
2591          * just set the interrupt line based on ISTATUS
2592          */
2593         int irqstate = (oldval & 4) && !(value & 2);
2594 
2595         trace_arm_gt_imask_toggle(timeridx, irqstate);
2596         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2597     }
2598 }
2599 
2600 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2601 {
2602     gt_timer_reset(env, ri, GTIMER_PHYS);
2603 }
2604 
2605 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2606                                uint64_t value)
2607 {
2608     gt_cval_write(env, ri, GTIMER_PHYS, value);
2609 }
2610 
2611 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2612 {
2613     return gt_tval_read(env, ri, GTIMER_PHYS);
2614 }
2615 
2616 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2617                                uint64_t value)
2618 {
2619     gt_tval_write(env, ri, GTIMER_PHYS, value);
2620 }
2621 
2622 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2623                               uint64_t value)
2624 {
2625     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2626 }
2627 
2628 static int gt_phys_redir_timeridx(CPUARMState *env)
2629 {
2630     switch (arm_mmu_idx(env)) {
2631     case ARMMMUIdx_E20_0:
2632     case ARMMMUIdx_E20_2:
2633     case ARMMMUIdx_E20_2_PAN:
2634     case ARMMMUIdx_SE20_0:
2635     case ARMMMUIdx_SE20_2:
2636     case ARMMMUIdx_SE20_2_PAN:
2637         return GTIMER_HYP;
2638     default:
2639         return GTIMER_PHYS;
2640     }
2641 }
2642 
2643 static int gt_virt_redir_timeridx(CPUARMState *env)
2644 {
2645     switch (arm_mmu_idx(env)) {
2646     case ARMMMUIdx_E20_0:
2647     case ARMMMUIdx_E20_2:
2648     case ARMMMUIdx_E20_2_PAN:
2649     case ARMMMUIdx_SE20_0:
2650     case ARMMMUIdx_SE20_2:
2651     case ARMMMUIdx_SE20_2_PAN:
2652         return GTIMER_HYPVIRT;
2653     default:
2654         return GTIMER_VIRT;
2655     }
2656 }
2657 
2658 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2659                                         const ARMCPRegInfo *ri)
2660 {
2661     int timeridx = gt_phys_redir_timeridx(env);
2662     return env->cp15.c14_timer[timeridx].cval;
2663 }
2664 
2665 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2666                                      uint64_t value)
2667 {
2668     int timeridx = gt_phys_redir_timeridx(env);
2669     gt_cval_write(env, ri, timeridx, value);
2670 }
2671 
2672 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2673                                         const ARMCPRegInfo *ri)
2674 {
2675     int timeridx = gt_phys_redir_timeridx(env);
2676     return gt_tval_read(env, ri, timeridx);
2677 }
2678 
2679 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2680                                      uint64_t value)
2681 {
2682     int timeridx = gt_phys_redir_timeridx(env);
2683     gt_tval_write(env, ri, timeridx, value);
2684 }
2685 
2686 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2687                                        const ARMCPRegInfo *ri)
2688 {
2689     int timeridx = gt_phys_redir_timeridx(env);
2690     return env->cp15.c14_timer[timeridx].ctl;
2691 }
2692 
2693 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2694                                     uint64_t value)
2695 {
2696     int timeridx = gt_phys_redir_timeridx(env);
2697     gt_ctl_write(env, ri, timeridx, value);
2698 }
2699 
2700 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2701 {
2702     gt_timer_reset(env, ri, GTIMER_VIRT);
2703 }
2704 
2705 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2706                                uint64_t value)
2707 {
2708     gt_cval_write(env, ri, GTIMER_VIRT, value);
2709 }
2710 
2711 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2712 {
2713     return gt_tval_read(env, ri, GTIMER_VIRT);
2714 }
2715 
2716 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2717                                uint64_t value)
2718 {
2719     gt_tval_write(env, ri, GTIMER_VIRT, value);
2720 }
2721 
2722 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2723                               uint64_t value)
2724 {
2725     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2726 }
2727 
2728 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2729                               uint64_t value)
2730 {
2731     ARMCPU *cpu = env_archcpu(env);
2732 
2733     trace_arm_gt_cntvoff_write(value);
2734     raw_write(env, ri, value);
2735     gt_recalc_timer(cpu, GTIMER_VIRT);
2736 }
2737 
2738 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2739                                         const ARMCPRegInfo *ri)
2740 {
2741     int timeridx = gt_virt_redir_timeridx(env);
2742     return env->cp15.c14_timer[timeridx].cval;
2743 }
2744 
2745 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2746                                      uint64_t value)
2747 {
2748     int timeridx = gt_virt_redir_timeridx(env);
2749     gt_cval_write(env, ri, timeridx, value);
2750 }
2751 
2752 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
2753                                         const ARMCPRegInfo *ri)
2754 {
2755     int timeridx = gt_virt_redir_timeridx(env);
2756     return gt_tval_read(env, ri, timeridx);
2757 }
2758 
2759 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2760                                      uint64_t value)
2761 {
2762     int timeridx = gt_virt_redir_timeridx(env);
2763     gt_tval_write(env, ri, timeridx, value);
2764 }
2765 
2766 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
2767                                        const ARMCPRegInfo *ri)
2768 {
2769     int timeridx = gt_virt_redir_timeridx(env);
2770     return env->cp15.c14_timer[timeridx].ctl;
2771 }
2772 
2773 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2774                                     uint64_t value)
2775 {
2776     int timeridx = gt_virt_redir_timeridx(env);
2777     gt_ctl_write(env, ri, timeridx, value);
2778 }
2779 
2780 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2781 {
2782     gt_timer_reset(env, ri, GTIMER_HYP);
2783 }
2784 
2785 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2786                               uint64_t value)
2787 {
2788     gt_cval_write(env, ri, GTIMER_HYP, value);
2789 }
2790 
2791 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2792 {
2793     return gt_tval_read(env, ri, GTIMER_HYP);
2794 }
2795 
2796 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2797                               uint64_t value)
2798 {
2799     gt_tval_write(env, ri, GTIMER_HYP, value);
2800 }
2801 
2802 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2803                               uint64_t value)
2804 {
2805     gt_ctl_write(env, ri, GTIMER_HYP, value);
2806 }
2807 
2808 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2809 {
2810     gt_timer_reset(env, ri, GTIMER_SEC);
2811 }
2812 
2813 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2814                               uint64_t value)
2815 {
2816     gt_cval_write(env, ri, GTIMER_SEC, value);
2817 }
2818 
2819 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2820 {
2821     return gt_tval_read(env, ri, GTIMER_SEC);
2822 }
2823 
2824 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2825                               uint64_t value)
2826 {
2827     gt_tval_write(env, ri, GTIMER_SEC, value);
2828 }
2829 
2830 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2831                               uint64_t value)
2832 {
2833     gt_ctl_write(env, ri, GTIMER_SEC, value);
2834 }
2835 
2836 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2837 {
2838     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
2839 }
2840 
2841 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2842                              uint64_t value)
2843 {
2844     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
2845 }
2846 
2847 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2848 {
2849     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
2850 }
2851 
2852 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2853                              uint64_t value)
2854 {
2855     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
2856 }
2857 
2858 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2859                             uint64_t value)
2860 {
2861     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
2862 }
2863 
2864 void arm_gt_ptimer_cb(void *opaque)
2865 {
2866     ARMCPU *cpu = opaque;
2867 
2868     gt_recalc_timer(cpu, GTIMER_PHYS);
2869 }
2870 
2871 void arm_gt_vtimer_cb(void *opaque)
2872 {
2873     ARMCPU *cpu = opaque;
2874 
2875     gt_recalc_timer(cpu, GTIMER_VIRT);
2876 }
2877 
2878 void arm_gt_htimer_cb(void *opaque)
2879 {
2880     ARMCPU *cpu = opaque;
2881 
2882     gt_recalc_timer(cpu, GTIMER_HYP);
2883 }
2884 
2885 void arm_gt_stimer_cb(void *opaque)
2886 {
2887     ARMCPU *cpu = opaque;
2888 
2889     gt_recalc_timer(cpu, GTIMER_SEC);
2890 }
2891 
2892 void arm_gt_hvtimer_cb(void *opaque)
2893 {
2894     ARMCPU *cpu = opaque;
2895 
2896     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
2897 }
2898 
2899 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
2900 {
2901     ARMCPU *cpu = env_archcpu(env);
2902 
2903     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
2904 }
2905 
2906 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2907     /* Note that CNTFRQ is purely reads-as-written for the benefit
2908      * of software; writing it doesn't actually change the timer frequency.
2909      * Our reset value matches the fixed frequency we implement the timer at.
2910      */
2911     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2912       .type = ARM_CP_ALIAS,
2913       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2914       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2915     },
2916     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2917       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2918       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2919       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2920       .resetfn = arm_gt_cntfrq_reset,
2921     },
2922     /* overall control: mostly access permissions */
2923     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2924       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2925       .access = PL1_RW,
2926       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2927       .resetvalue = 0,
2928     },
2929     /* per-timer control */
2930     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2931       .secure = ARM_CP_SECSTATE_NS,
2932       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2933       .accessfn = gt_ptimer_access,
2934       .fieldoffset = offsetoflow32(CPUARMState,
2935                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2936       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
2937       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
2938     },
2939     { .name = "CNTP_CTL_S",
2940       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2941       .secure = ARM_CP_SECSTATE_S,
2942       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2943       .accessfn = gt_ptimer_access,
2944       .fieldoffset = offsetoflow32(CPUARMState,
2945                                    cp15.c14_timer[GTIMER_SEC].ctl),
2946       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2947     },
2948     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2949       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2950       .type = ARM_CP_IO, .access = PL0_RW,
2951       .accessfn = gt_ptimer_access,
2952       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2953       .resetvalue = 0,
2954       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
2955       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
2956     },
2957     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2958       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2959       .accessfn = gt_vtimer_access,
2960       .fieldoffset = offsetoflow32(CPUARMState,
2961                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2962       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
2963       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
2964     },
2965     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2966       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2967       .type = ARM_CP_IO, .access = PL0_RW,
2968       .accessfn = gt_vtimer_access,
2969       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2970       .resetvalue = 0,
2971       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
2972       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
2973     },
2974     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2975     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2976       .secure = ARM_CP_SECSTATE_NS,
2977       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2978       .accessfn = gt_ptimer_access,
2979       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
2980     },
2981     { .name = "CNTP_TVAL_S",
2982       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2983       .secure = ARM_CP_SECSTATE_S,
2984       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2985       .accessfn = gt_ptimer_access,
2986       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2987     },
2988     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2989       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2990       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2991       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2992       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
2993     },
2994     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2995       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2996       .accessfn = gt_vtimer_access,
2997       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
2998     },
2999     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3000       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
3001       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3002       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
3003       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3004     },
3005     /* The counter itself */
3006     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
3007       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3008       .accessfn = gt_pct_access,
3009       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
3010     },
3011     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3012       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3013       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3014       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3015     },
3016     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3017       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3018       .accessfn = gt_vct_access,
3019       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3020     },
3021     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3022       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3023       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3024       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3025     },
3026     /* Comparison value, indicating when the timer goes off */
3027     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3028       .secure = ARM_CP_SECSTATE_NS,
3029       .access = PL0_RW,
3030       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3031       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3032       .accessfn = gt_ptimer_access,
3033       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3034       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3035     },
3036     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3037       .secure = ARM_CP_SECSTATE_S,
3038       .access = PL0_RW,
3039       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3040       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3041       .accessfn = gt_ptimer_access,
3042       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3043     },
3044     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3045       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3046       .access = PL0_RW,
3047       .type = ARM_CP_IO,
3048       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3049       .resetvalue = 0, .accessfn = gt_ptimer_access,
3050       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3051       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3052     },
3053     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3054       .access = PL0_RW,
3055       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3056       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3057       .accessfn = gt_vtimer_access,
3058       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3059       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3060     },
3061     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3062       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3063       .access = PL0_RW,
3064       .type = ARM_CP_IO,
3065       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3066       .resetvalue = 0, .accessfn = gt_vtimer_access,
3067       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3068       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3069     },
3070     /* Secure timer -- this is actually restricted to only EL3
3071      * and configurably Secure-EL1 via the accessfn.
3072      */
3073     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3074       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3075       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3076       .accessfn = gt_stimer_access,
3077       .readfn = gt_sec_tval_read,
3078       .writefn = gt_sec_tval_write,
3079       .resetfn = gt_sec_timer_reset,
3080     },
3081     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3082       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3083       .type = ARM_CP_IO, .access = PL1_RW,
3084       .accessfn = gt_stimer_access,
3085       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3086       .resetvalue = 0,
3087       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3088     },
3089     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3090       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3091       .type = ARM_CP_IO, .access = PL1_RW,
3092       .accessfn = gt_stimer_access,
3093       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3094       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3095     },
3096 };
3097 
3098 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3099                                  bool isread)
3100 {
3101     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3102         return CP_ACCESS_TRAP;
3103     }
3104     return CP_ACCESS_OK;
3105 }
3106 
3107 #else
3108 
3109 /* In user-mode most of the generic timer registers are inaccessible
3110  * however modern kernels (4.12+) allow access to cntvct_el0
3111  */
3112 
3113 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3114 {
3115     ARMCPU *cpu = env_archcpu(env);
3116 
3117     /* Currently we have no support for QEMUTimer in linux-user so we
3118      * can't call gt_get_countervalue(env), instead we directly
3119      * call the lower level functions.
3120      */
3121     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3122 }
3123 
3124 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3125     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3126       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3127       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3128       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3129       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3130     },
3131     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3132       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3133       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3134       .readfn = gt_virt_cnt_read,
3135     },
3136 };
3137 
3138 #endif
3139 
3140 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3141 {
3142     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3143         raw_write(env, ri, value);
3144     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3145         raw_write(env, ri, value & 0xfffff6ff);
3146     } else {
3147         raw_write(env, ri, value & 0xfffff1ff);
3148     }
3149 }
3150 
3151 #ifndef CONFIG_USER_ONLY
3152 /* get_phys_addr() isn't present for user-mode-only targets */
3153 
3154 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3155                                  bool isread)
3156 {
3157     if (ri->opc2 & 4) {
3158         /* The ATS12NSO* operations must trap to EL3 or EL2 if executed in
3159          * Secure EL1 (which can only happen if EL3 is AArch64).
3160          * They are simply UNDEF if executed from NS EL1.
3161          * They function normally from EL2 or EL3.
3162          */
3163         if (arm_current_el(env) == 1) {
3164             if (arm_is_secure_below_el3(env)) {
3165                 if (env->cp15.scr_el3 & SCR_EEL2) {
3166                     return CP_ACCESS_TRAP_UNCATEGORIZED_EL2;
3167                 }
3168                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3169             }
3170             return CP_ACCESS_TRAP_UNCATEGORIZED;
3171         }
3172     }
3173     return CP_ACCESS_OK;
3174 }
3175 
3176 #ifdef CONFIG_TCG
3177 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3178                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3179 {
3180     hwaddr phys_addr;
3181     target_ulong page_size;
3182     int prot;
3183     bool ret;
3184     uint64_t par64;
3185     bool format64 = false;
3186     MemTxAttrs attrs = {};
3187     ARMMMUFaultInfo fi = {};
3188     ARMCacheAttrs cacheattrs = {};
3189 
3190     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3191                         &prot, &page_size, &fi, &cacheattrs);
3192 
3193     /*
3194      * ATS operations only do S1 or S1+S2 translations, so we never
3195      * have to deal with the ARMCacheAttrs format for S2 only.
3196      */
3197     assert(!cacheattrs.is_s2_format);
3198 
3199     if (ret) {
3200         /*
3201          * Some kinds of translation fault must cause exceptions rather
3202          * than being reported in the PAR.
3203          */
3204         int current_el = arm_current_el(env);
3205         int target_el;
3206         uint32_t syn, fsr, fsc;
3207         bool take_exc = false;
3208 
3209         if (fi.s1ptw && current_el == 1
3210             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3211             /*
3212              * Synchronous stage 2 fault on an access made as part of the
3213              * translation table walk for AT S1E0* or AT S1E1* insn
3214              * executed from NS EL1. If this is a synchronous external abort
3215              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3216              * to EL3. Otherwise the fault is taken as an exception to EL2,
3217              * and HPFAR_EL2 holds the faulting IPA.
3218              */
3219             if (fi.type == ARMFault_SyncExternalOnWalk &&
3220                 (env->cp15.scr_el3 & SCR_EA)) {
3221                 target_el = 3;
3222             } else {
3223                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3224                 if (arm_is_secure_below_el3(env) && fi.s1ns) {
3225                     env->cp15.hpfar_el2 |= HPFAR_NS;
3226                 }
3227                 target_el = 2;
3228             }
3229             take_exc = true;
3230         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3231             /*
3232              * Synchronous external aborts during a translation table walk
3233              * are taken as Data Abort exceptions.
3234              */
3235             if (fi.stage2) {
3236                 if (current_el == 3) {
3237                     target_el = 3;
3238                 } else {
3239                     target_el = 2;
3240                 }
3241             } else {
3242                 target_el = exception_target_el(env);
3243             }
3244             take_exc = true;
3245         }
3246 
3247         if (take_exc) {
3248             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3249             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3250                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3251                 fsr = arm_fi_to_lfsc(&fi);
3252                 fsc = extract32(fsr, 0, 6);
3253             } else {
3254                 fsr = arm_fi_to_sfsc(&fi);
3255                 fsc = 0x3f;
3256             }
3257             /*
3258              * Report exception with ESR indicating a fault due to a
3259              * translation table walk for a cache maintenance instruction.
3260              */
3261             syn = syn_data_abort_no_iss(current_el == target_el, 0,
3262                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3263             env->exception.vaddress = value;
3264             env->exception.fsr = fsr;
3265             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3266         }
3267     }
3268 
3269     if (is_a64(env)) {
3270         format64 = true;
3271     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3272         /*
3273          * ATS1Cxx:
3274          * * TTBCR.EAE determines whether the result is returned using the
3275          *   32-bit or the 64-bit PAR format
3276          * * Instructions executed in Hyp mode always use the 64bit format
3277          *
3278          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3279          * * The Non-secure TTBCR.EAE bit is set to 1
3280          * * The implementation includes EL2, and the value of HCR.VM is 1
3281          *
3282          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3283          *
3284          * ATS1Hx always uses the 64bit format.
3285          */
3286         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3287 
3288         if (arm_feature(env, ARM_FEATURE_EL2)) {
3289             if (mmu_idx == ARMMMUIdx_E10_0 ||
3290                 mmu_idx == ARMMMUIdx_E10_1 ||
3291                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3292                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3293             } else {
3294                 format64 |= arm_current_el(env) == 2;
3295             }
3296         }
3297     }
3298 
3299     if (format64) {
3300         /* Create a 64-bit PAR */
3301         par64 = (1 << 11); /* LPAE bit always set */
3302         if (!ret) {
3303             par64 |= phys_addr & ~0xfffULL;
3304             if (!attrs.secure) {
3305                 par64 |= (1 << 9); /* NS */
3306             }
3307             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3308             par64 |= cacheattrs.shareability << 7; /* SH */
3309         } else {
3310             uint32_t fsr = arm_fi_to_lfsc(&fi);
3311 
3312             par64 |= 1; /* F */
3313             par64 |= (fsr & 0x3f) << 1; /* FS */
3314             if (fi.stage2) {
3315                 par64 |= (1 << 9); /* S */
3316             }
3317             if (fi.s1ptw) {
3318                 par64 |= (1 << 8); /* PTW */
3319             }
3320         }
3321     } else {
3322         /* fsr is a DFSR/IFSR value for the short descriptor
3323          * translation table format (with WnR always clear).
3324          * Convert it to a 32-bit PAR.
3325          */
3326         if (!ret) {
3327             /* We do not set any attribute bits in the PAR */
3328             if (page_size == (1 << 24)
3329                 && arm_feature(env, ARM_FEATURE_V7)) {
3330                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3331             } else {
3332                 par64 = phys_addr & 0xfffff000;
3333             }
3334             if (!attrs.secure) {
3335                 par64 |= (1 << 9); /* NS */
3336             }
3337         } else {
3338             uint32_t fsr = arm_fi_to_sfsc(&fi);
3339 
3340             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3341                     ((fsr & 0xf) << 1) | 1;
3342         }
3343     }
3344     return par64;
3345 }
3346 #endif /* CONFIG_TCG */
3347 
3348 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3349 {
3350 #ifdef CONFIG_TCG
3351     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3352     uint64_t par64;
3353     ARMMMUIdx mmu_idx;
3354     int el = arm_current_el(env);
3355     bool secure = arm_is_secure_below_el3(env);
3356 
3357     switch (ri->opc2 & 6) {
3358     case 0:
3359         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3360         switch (el) {
3361         case 3:
3362             mmu_idx = ARMMMUIdx_SE3;
3363             break;
3364         case 2:
3365             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3366             /* fall through */
3367         case 1:
3368             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3369                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3370                            : ARMMMUIdx_Stage1_E1_PAN);
3371             } else {
3372                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3373             }
3374             break;
3375         default:
3376             g_assert_not_reached();
3377         }
3378         break;
3379     case 2:
3380         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3381         switch (el) {
3382         case 3:
3383             mmu_idx = ARMMMUIdx_SE10_0;
3384             break;
3385         case 2:
3386             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3387             mmu_idx = ARMMMUIdx_Stage1_E0;
3388             break;
3389         case 1:
3390             mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3391             break;
3392         default:
3393             g_assert_not_reached();
3394         }
3395         break;
3396     case 4:
3397         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3398         mmu_idx = ARMMMUIdx_E10_1;
3399         break;
3400     case 6:
3401         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3402         mmu_idx = ARMMMUIdx_E10_0;
3403         break;
3404     default:
3405         g_assert_not_reached();
3406     }
3407 
3408     par64 = do_ats_write(env, value, access_type, mmu_idx);
3409 
3410     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3411 #else
3412     /* Handled by hardware accelerator. */
3413     g_assert_not_reached();
3414 #endif /* CONFIG_TCG */
3415 }
3416 
3417 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3418                         uint64_t value)
3419 {
3420 #ifdef CONFIG_TCG
3421     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3422     uint64_t par64;
3423 
3424     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3425 
3426     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3427 #else
3428     /* Handled by hardware accelerator. */
3429     g_assert_not_reached();
3430 #endif /* CONFIG_TCG */
3431 }
3432 
3433 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3434                                      bool isread)
3435 {
3436     if (arm_current_el(env) == 3 &&
3437         !(env->cp15.scr_el3 & (SCR_NS | SCR_EEL2))) {
3438         return CP_ACCESS_TRAP;
3439     }
3440     return CP_ACCESS_OK;
3441 }
3442 
3443 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3444                         uint64_t value)
3445 {
3446 #ifdef CONFIG_TCG
3447     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3448     ARMMMUIdx mmu_idx;
3449     int secure = arm_is_secure_below_el3(env);
3450 
3451     switch (ri->opc2 & 6) {
3452     case 0:
3453         switch (ri->opc1) {
3454         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3455             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3456                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3457                            : ARMMMUIdx_Stage1_E1_PAN);
3458             } else {
3459                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3460             }
3461             break;
3462         case 4: /* AT S1E2R, AT S1E2W */
3463             mmu_idx = secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2;
3464             break;
3465         case 6: /* AT S1E3R, AT S1E3W */
3466             mmu_idx = ARMMMUIdx_SE3;
3467             break;
3468         default:
3469             g_assert_not_reached();
3470         }
3471         break;
3472     case 2: /* AT S1E0R, AT S1E0W */
3473         mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3474         break;
3475     case 4: /* AT S12E1R, AT S12E1W */
3476         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3477         break;
3478     case 6: /* AT S12E0R, AT S12E0W */
3479         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3480         break;
3481     default:
3482         g_assert_not_reached();
3483     }
3484 
3485     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3486 #else
3487     /* Handled by hardware accelerator. */
3488     g_assert_not_reached();
3489 #endif /* CONFIG_TCG */
3490 }
3491 #endif
3492 
3493 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3494     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3495       .access = PL1_RW, .resetvalue = 0,
3496       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3497                              offsetoflow32(CPUARMState, cp15.par_ns) },
3498       .writefn = par_write },
3499 #ifndef CONFIG_USER_ONLY
3500     /* This underdecoding is safe because the reginfo is NO_RAW. */
3501     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3502       .access = PL1_W, .accessfn = ats_access,
3503       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3504 #endif
3505 };
3506 
3507 /* Return basic MPU access permission bits.  */
3508 static uint32_t simple_mpu_ap_bits(uint32_t val)
3509 {
3510     uint32_t ret;
3511     uint32_t mask;
3512     int i;
3513     ret = 0;
3514     mask = 3;
3515     for (i = 0; i < 16; i += 2) {
3516         ret |= (val >> i) & mask;
3517         mask <<= 2;
3518     }
3519     return ret;
3520 }
3521 
3522 /* Pad basic MPU access permission bits to extended format.  */
3523 static uint32_t extended_mpu_ap_bits(uint32_t val)
3524 {
3525     uint32_t ret;
3526     uint32_t mask;
3527     int i;
3528     ret = 0;
3529     mask = 3;
3530     for (i = 0; i < 16; i += 2) {
3531         ret |= (val & mask) << i;
3532         mask <<= 2;
3533     }
3534     return ret;
3535 }
3536 
3537 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3538                                  uint64_t value)
3539 {
3540     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3541 }
3542 
3543 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3544 {
3545     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3546 }
3547 
3548 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3549                                  uint64_t value)
3550 {
3551     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3552 }
3553 
3554 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3555 {
3556     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3557 }
3558 
3559 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3560 {
3561     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3562 
3563     if (!u32p) {
3564         return 0;
3565     }
3566 
3567     u32p += env->pmsav7.rnr[M_REG_NS];
3568     return *u32p;
3569 }
3570 
3571 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3572                          uint64_t value)
3573 {
3574     ARMCPU *cpu = env_archcpu(env);
3575     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3576 
3577     if (!u32p) {
3578         return;
3579     }
3580 
3581     u32p += env->pmsav7.rnr[M_REG_NS];
3582     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3583     *u32p = value;
3584 }
3585 
3586 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3587                               uint64_t value)
3588 {
3589     ARMCPU *cpu = env_archcpu(env);
3590     uint32_t nrgs = cpu->pmsav7_dregion;
3591 
3592     if (value >= nrgs) {
3593         qemu_log_mask(LOG_GUEST_ERROR,
3594                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3595                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3596         return;
3597     }
3598 
3599     raw_write(env, ri, value);
3600 }
3601 
3602 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3603     /* Reset for all these registers is handled in arm_cpu_reset(),
3604      * because the PMSAv7 is also used by M-profile CPUs, which do
3605      * not register cpregs but still need the state to be reset.
3606      */
3607     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3608       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3609       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3610       .readfn = pmsav7_read, .writefn = pmsav7_write,
3611       .resetfn = arm_cp_reset_ignore },
3612     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3613       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3614       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3615       .readfn = pmsav7_read, .writefn = pmsav7_write,
3616       .resetfn = arm_cp_reset_ignore },
3617     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3618       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3619       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3620       .readfn = pmsav7_read, .writefn = pmsav7_write,
3621       .resetfn = arm_cp_reset_ignore },
3622     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3623       .access = PL1_RW,
3624       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3625       .writefn = pmsav7_rgnr_write,
3626       .resetfn = arm_cp_reset_ignore },
3627 };
3628 
3629 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3630     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3631       .access = PL1_RW, .type = ARM_CP_ALIAS,
3632       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3633       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3634     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3635       .access = PL1_RW, .type = ARM_CP_ALIAS,
3636       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3637       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3638     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3639       .access = PL1_RW,
3640       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3641       .resetvalue = 0, },
3642     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3643       .access = PL1_RW,
3644       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3645       .resetvalue = 0, },
3646     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3647       .access = PL1_RW,
3648       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3649     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3650       .access = PL1_RW,
3651       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3652     /* Protection region base and size registers */
3653     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3654       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3655       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3656     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3657       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3658       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3659     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3660       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3661       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3662     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3663       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3664       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3665     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3666       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3667       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3668     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3669       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3670       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3671     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3672       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3673       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3674     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3675       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3676       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3677 };
3678 
3679 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3680                                  uint64_t value)
3681 {
3682     TCR *tcr = raw_ptr(env, ri);
3683     int maskshift = extract32(value, 0, 3);
3684 
3685     if (!arm_feature(env, ARM_FEATURE_V8)) {
3686         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3687             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3688              * using Long-desciptor translation table format */
3689             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3690         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3691             /* In an implementation that includes the Security Extensions
3692              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3693              * Short-descriptor translation table format.
3694              */
3695             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3696         } else {
3697             value &= TTBCR_N;
3698         }
3699     }
3700 
3701     /* Update the masks corresponding to the TCR bank being written
3702      * Note that we always calculate mask and base_mask, but
3703      * they are only used for short-descriptor tables (ie if EAE is 0);
3704      * for long-descriptor tables the TCR fields are used differently
3705      * and the mask and base_mask values are meaningless.
3706      */
3707     tcr->raw_tcr = value;
3708     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3709     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3710 }
3711 
3712 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3713                              uint64_t value)
3714 {
3715     ARMCPU *cpu = env_archcpu(env);
3716     TCR *tcr = raw_ptr(env, ri);
3717 
3718     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3719         /* With LPAE the TTBCR could result in a change of ASID
3720          * via the TTBCR.A1 bit, so do a TLB flush.
3721          */
3722         tlb_flush(CPU(cpu));
3723     }
3724     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3725     value = deposit64(tcr->raw_tcr, 0, 32, value);
3726     vmsa_ttbcr_raw_write(env, ri, value);
3727 }
3728 
3729 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3730 {
3731     TCR *tcr = raw_ptr(env, ri);
3732 
3733     /* Reset both the TCR as well as the masks corresponding to the bank of
3734      * the TCR being reset.
3735      */
3736     tcr->raw_tcr = 0;
3737     tcr->mask = 0;
3738     tcr->base_mask = 0xffffc000u;
3739 }
3740 
3741 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3742                                uint64_t value)
3743 {
3744     ARMCPU *cpu = env_archcpu(env);
3745     TCR *tcr = raw_ptr(env, ri);
3746 
3747     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3748     tlb_flush(CPU(cpu));
3749     tcr->raw_tcr = value;
3750 }
3751 
3752 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3753                             uint64_t value)
3754 {
3755     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3756     if (cpreg_field_is_64bit(ri) &&
3757         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3758         ARMCPU *cpu = env_archcpu(env);
3759         tlb_flush(CPU(cpu));
3760     }
3761     raw_write(env, ri, value);
3762 }
3763 
3764 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3765                                     uint64_t value)
3766 {
3767     /*
3768      * If we are running with E2&0 regime, then an ASID is active.
3769      * Flush if that might be changing.  Note we're not checking
3770      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
3771      * holds the active ASID, only checking the field that might.
3772      */
3773     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
3774         (arm_hcr_el2_eff(env) & HCR_E2H)) {
3775         uint16_t mask = ARMMMUIdxBit_E20_2 |
3776                         ARMMMUIdxBit_E20_2_PAN |
3777                         ARMMMUIdxBit_E20_0;
3778 
3779         if (arm_is_secure_below_el3(env)) {
3780             mask >>= ARM_MMU_IDX_A_NS;
3781         }
3782 
3783         tlb_flush_by_mmuidx(env_cpu(env), mask);
3784     }
3785     raw_write(env, ri, value);
3786 }
3787 
3788 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3789                         uint64_t value)
3790 {
3791     ARMCPU *cpu = env_archcpu(env);
3792     CPUState *cs = CPU(cpu);
3793 
3794     /*
3795      * A change in VMID to the stage2 page table (Stage2) invalidates
3796      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
3797      */
3798     if (raw_read(env, ri) != value) {
3799         uint16_t mask = ARMMMUIdxBit_E10_1 |
3800                         ARMMMUIdxBit_E10_1_PAN |
3801                         ARMMMUIdxBit_E10_0;
3802 
3803         if (arm_is_secure_below_el3(env)) {
3804             mask >>= ARM_MMU_IDX_A_NS;
3805         }
3806 
3807         tlb_flush_by_mmuidx(cs, mask);
3808         raw_write(env, ri, value);
3809     }
3810 }
3811 
3812 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3813     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3814       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
3815       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3816                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3817     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3818       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3819       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3820                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3821     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3822       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3823       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3824                              offsetof(CPUARMState, cp15.dfar_ns) } },
3825     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3826       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3827       .access = PL1_RW, .accessfn = access_tvm_trvm,
3828       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3829       .resetvalue = 0, },
3830 };
3831 
3832 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3833     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3834       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3835       .access = PL1_RW, .accessfn = access_tvm_trvm,
3836       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3837     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3838       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3839       .access = PL1_RW, .accessfn = access_tvm_trvm,
3840       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3841       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3842                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3843     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3844       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3845       .access = PL1_RW, .accessfn = access_tvm_trvm,
3846       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3847       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3848                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3849     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3850       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3851       .access = PL1_RW, .accessfn = access_tvm_trvm,
3852       .writefn = vmsa_tcr_el12_write,
3853       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3854       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3855     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3856       .access = PL1_RW, .accessfn = access_tvm_trvm,
3857       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3858       .raw_writefn = vmsa_ttbcr_raw_write,
3859       /* No offsetoflow32 -- pass the entire TCR to writefn/raw_writefn. */
3860       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.tcr_el[3]),
3861                              offsetof(CPUARMState, cp15.tcr_el[1])} },
3862 };
3863 
3864 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3865  * qemu tlbs nor adjusting cached masks.
3866  */
3867 static const ARMCPRegInfo ttbcr2_reginfo = {
3868     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3869     .access = PL1_RW, .accessfn = access_tvm_trvm,
3870     .type = ARM_CP_ALIAS,
3871     .bank_fieldoffsets = {
3872         offsetofhigh32(CPUARMState, cp15.tcr_el[3].raw_tcr),
3873         offsetofhigh32(CPUARMState, cp15.tcr_el[1].raw_tcr),
3874     },
3875 };
3876 
3877 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3878                                 uint64_t value)
3879 {
3880     env->cp15.c15_ticonfig = value & 0xe7;
3881     /* The OS_TYPE bit in this register changes the reported CPUID! */
3882     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3883         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3884 }
3885 
3886 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3887                                 uint64_t value)
3888 {
3889     env->cp15.c15_threadid = value & 0xffff;
3890 }
3891 
3892 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3893                            uint64_t value)
3894 {
3895     /* Wait-for-interrupt (deprecated) */
3896     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
3897 }
3898 
3899 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3900                                   uint64_t value)
3901 {
3902     /* On OMAP there are registers indicating the max/min index of dcache lines
3903      * containing a dirty line; cache flush operations have to reset these.
3904      */
3905     env->cp15.c15_i_max = 0x000;
3906     env->cp15.c15_i_min = 0xff0;
3907 }
3908 
3909 static const ARMCPRegInfo omap_cp_reginfo[] = {
3910     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3911       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3912       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3913       .resetvalue = 0, },
3914     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3915       .access = PL1_RW, .type = ARM_CP_NOP },
3916     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3917       .access = PL1_RW,
3918       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3919       .writefn = omap_ticonfig_write },
3920     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3921       .access = PL1_RW,
3922       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3923     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3924       .access = PL1_RW, .resetvalue = 0xff0,
3925       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3926     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3927       .access = PL1_RW,
3928       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3929       .writefn = omap_threadid_write },
3930     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3931       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3932       .type = ARM_CP_NO_RAW,
3933       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3934     /* TODO: Peripheral port remap register:
3935      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3936      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3937      * when MMU is off.
3938      */
3939     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3940       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3941       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3942       .writefn = omap_cachemaint_write },
3943     { .name = "C9", .cp = 15, .crn = 9,
3944       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3945       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3946 };
3947 
3948 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3949                               uint64_t value)
3950 {
3951     env->cp15.c15_cpar = value & 0x3fff;
3952 }
3953 
3954 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3955     { .name = "XSCALE_CPAR",
3956       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3957       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3958       .writefn = xscale_cpar_write, },
3959     { .name = "XSCALE_AUXCR",
3960       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3961       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3962       .resetvalue = 0, },
3963     /* XScale specific cache-lockdown: since we have no cache we NOP these
3964      * and hope the guest does not really rely on cache behaviour.
3965      */
3966     { .name = "XSCALE_LOCK_ICACHE_LINE",
3967       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3968       .access = PL1_W, .type = ARM_CP_NOP },
3969     { .name = "XSCALE_UNLOCK_ICACHE",
3970       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3971       .access = PL1_W, .type = ARM_CP_NOP },
3972     { .name = "XSCALE_DCACHE_LOCK",
3973       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3974       .access = PL1_RW, .type = ARM_CP_NOP },
3975     { .name = "XSCALE_UNLOCK_DCACHE",
3976       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3977       .access = PL1_W, .type = ARM_CP_NOP },
3978 };
3979 
3980 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3981     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3982      * implementation of this implementation-defined space.
3983      * Ideally this should eventually disappear in favour of actually
3984      * implementing the correct behaviour for all cores.
3985      */
3986     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3987       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3988       .access = PL1_RW,
3989       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3990       .resetvalue = 0 },
3991 };
3992 
3993 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3994     /* Cache status: RAZ because we have no cache so it's always clean */
3995     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3996       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3997       .resetvalue = 0 },
3998 };
3999 
4000 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
4001     /* We never have a a block transfer operation in progress */
4002     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4003       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4004       .resetvalue = 0 },
4005     /* The cache ops themselves: these all NOP for QEMU */
4006     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4007       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4008     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4009       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4010     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4011       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4012     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4013       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4014     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4015       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4016     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4017       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4018 };
4019 
4020 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4021     /* The cache test-and-clean instructions always return (1 << 30)
4022      * to indicate that there are no dirty cache lines.
4023      */
4024     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4025       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4026       .resetvalue = (1 << 30) },
4027     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4028       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4029       .resetvalue = (1 << 30) },
4030 };
4031 
4032 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4033     /* Ignore ReadBuffer accesses */
4034     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4035       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4036       .access = PL1_RW, .resetvalue = 0,
4037       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4038 };
4039 
4040 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4041 {
4042     unsigned int cur_el = arm_current_el(env);
4043 
4044     if (arm_is_el2_enabled(env) && cur_el == 1) {
4045         return env->cp15.vpidr_el2;
4046     }
4047     return raw_read(env, ri);
4048 }
4049 
4050 static uint64_t mpidr_read_val(CPUARMState *env)
4051 {
4052     ARMCPU *cpu = env_archcpu(env);
4053     uint64_t mpidr = cpu->mp_affinity;
4054 
4055     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4056         mpidr |= (1U << 31);
4057         /* Cores which are uniprocessor (non-coherent)
4058          * but still implement the MP extensions set
4059          * bit 30. (For instance, Cortex-R5).
4060          */
4061         if (cpu->mp_is_up) {
4062             mpidr |= (1u << 30);
4063         }
4064     }
4065     return mpidr;
4066 }
4067 
4068 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4069 {
4070     unsigned int cur_el = arm_current_el(env);
4071 
4072     if (arm_is_el2_enabled(env) && cur_el == 1) {
4073         return env->cp15.vmpidr_el2;
4074     }
4075     return mpidr_read_val(env);
4076 }
4077 
4078 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4079     /* NOP AMAIR0/1 */
4080     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4081       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4082       .access = PL1_RW, .accessfn = access_tvm_trvm,
4083       .type = ARM_CP_CONST, .resetvalue = 0 },
4084     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4085     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4086       .access = PL1_RW, .accessfn = access_tvm_trvm,
4087       .type = ARM_CP_CONST, .resetvalue = 0 },
4088     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4089       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4090       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4091                              offsetof(CPUARMState, cp15.par_ns)} },
4092     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4093       .access = PL1_RW, .accessfn = access_tvm_trvm,
4094       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4095       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4096                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4097       .writefn = vmsa_ttbr_write, },
4098     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4099       .access = PL1_RW, .accessfn = access_tvm_trvm,
4100       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4101       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4102                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4103       .writefn = vmsa_ttbr_write, },
4104 };
4105 
4106 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4107 {
4108     return vfp_get_fpcr(env);
4109 }
4110 
4111 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4112                             uint64_t value)
4113 {
4114     vfp_set_fpcr(env, value);
4115 }
4116 
4117 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4118 {
4119     return vfp_get_fpsr(env);
4120 }
4121 
4122 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4123                             uint64_t value)
4124 {
4125     vfp_set_fpsr(env, value);
4126 }
4127 
4128 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4129                                        bool isread)
4130 {
4131     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4132         return CP_ACCESS_TRAP;
4133     }
4134     return CP_ACCESS_OK;
4135 }
4136 
4137 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4138                             uint64_t value)
4139 {
4140     env->daif = value & PSTATE_DAIF;
4141 }
4142 
4143 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4144 {
4145     return env->pstate & PSTATE_PAN;
4146 }
4147 
4148 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4149                            uint64_t value)
4150 {
4151     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4152 }
4153 
4154 static const ARMCPRegInfo pan_reginfo = {
4155     .name = "PAN", .state = ARM_CP_STATE_AA64,
4156     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4157     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4158     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4159 };
4160 
4161 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4162 {
4163     return env->pstate & PSTATE_UAO;
4164 }
4165 
4166 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4167                            uint64_t value)
4168 {
4169     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4170 }
4171 
4172 static const ARMCPRegInfo uao_reginfo = {
4173     .name = "UAO", .state = ARM_CP_STATE_AA64,
4174     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4175     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4176     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4177 };
4178 
4179 static uint64_t aa64_dit_read(CPUARMState *env, const ARMCPRegInfo *ri)
4180 {
4181     return env->pstate & PSTATE_DIT;
4182 }
4183 
4184 static void aa64_dit_write(CPUARMState *env, const ARMCPRegInfo *ri,
4185                            uint64_t value)
4186 {
4187     env->pstate = (env->pstate & ~PSTATE_DIT) | (value & PSTATE_DIT);
4188 }
4189 
4190 static const ARMCPRegInfo dit_reginfo = {
4191     .name = "DIT", .state = ARM_CP_STATE_AA64,
4192     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 5,
4193     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4194     .readfn = aa64_dit_read, .writefn = aa64_dit_write
4195 };
4196 
4197 static uint64_t aa64_ssbs_read(CPUARMState *env, const ARMCPRegInfo *ri)
4198 {
4199     return env->pstate & PSTATE_SSBS;
4200 }
4201 
4202 static void aa64_ssbs_write(CPUARMState *env, const ARMCPRegInfo *ri,
4203                            uint64_t value)
4204 {
4205     env->pstate = (env->pstate & ~PSTATE_SSBS) | (value & PSTATE_SSBS);
4206 }
4207 
4208 static const ARMCPRegInfo ssbs_reginfo = {
4209     .name = "SSBS", .state = ARM_CP_STATE_AA64,
4210     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 6,
4211     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4212     .readfn = aa64_ssbs_read, .writefn = aa64_ssbs_write
4213 };
4214 
4215 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4216                                               const ARMCPRegInfo *ri,
4217                                               bool isread)
4218 {
4219     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4220     switch (arm_current_el(env)) {
4221     case 0:
4222         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4223         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4224             return CP_ACCESS_TRAP;
4225         }
4226         /* fall through */
4227     case 1:
4228         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4229         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4230             return CP_ACCESS_TRAP_EL2;
4231         }
4232         break;
4233     }
4234     return CP_ACCESS_OK;
4235 }
4236 
4237 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4238                                               const ARMCPRegInfo *ri,
4239                                               bool isread)
4240 {
4241     /* Cache invalidate/clean to Point of Unification... */
4242     switch (arm_current_el(env)) {
4243     case 0:
4244         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4245         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4246             return CP_ACCESS_TRAP;
4247         }
4248         /* fall through */
4249     case 1:
4250         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4251         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4252             return CP_ACCESS_TRAP_EL2;
4253         }
4254         break;
4255     }
4256     return CP_ACCESS_OK;
4257 }
4258 
4259 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4260  * Page D4-1736 (DDI0487A.b)
4261  */
4262 
4263 static int vae1_tlbmask(CPUARMState *env)
4264 {
4265     uint64_t hcr = arm_hcr_el2_eff(env);
4266     uint16_t mask;
4267 
4268     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4269         mask = ARMMMUIdxBit_E20_2 |
4270                ARMMMUIdxBit_E20_2_PAN |
4271                ARMMMUIdxBit_E20_0;
4272     } else {
4273         mask = ARMMMUIdxBit_E10_1 |
4274                ARMMMUIdxBit_E10_1_PAN |
4275                ARMMMUIdxBit_E10_0;
4276     }
4277 
4278     if (arm_is_secure_below_el3(env)) {
4279         mask >>= ARM_MMU_IDX_A_NS;
4280     }
4281 
4282     return mask;
4283 }
4284 
4285 /* Return 56 if TBI is enabled, 64 otherwise. */
4286 static int tlbbits_for_regime(CPUARMState *env, ARMMMUIdx mmu_idx,
4287                               uint64_t addr)
4288 {
4289     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
4290     int tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
4291     int select = extract64(addr, 55, 1);
4292 
4293     return (tbi >> select) & 1 ? 56 : 64;
4294 }
4295 
4296 static int vae1_tlbbits(CPUARMState *env, uint64_t addr)
4297 {
4298     uint64_t hcr = arm_hcr_el2_eff(env);
4299     ARMMMUIdx mmu_idx;
4300 
4301     /* Only the regime of the mmu_idx below is significant. */
4302     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4303         mmu_idx = ARMMMUIdx_E20_0;
4304     } else {
4305         mmu_idx = ARMMMUIdx_E10_0;
4306     }
4307 
4308     if (arm_is_secure_below_el3(env)) {
4309         mmu_idx &= ~ARM_MMU_IDX_A_NS;
4310     }
4311 
4312     return tlbbits_for_regime(env, mmu_idx, addr);
4313 }
4314 
4315 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4316                                       uint64_t value)
4317 {
4318     CPUState *cs = env_cpu(env);
4319     int mask = vae1_tlbmask(env);
4320 
4321     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4322 }
4323 
4324 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4325                                     uint64_t value)
4326 {
4327     CPUState *cs = env_cpu(env);
4328     int mask = vae1_tlbmask(env);
4329 
4330     if (tlb_force_broadcast(env)) {
4331         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4332     } else {
4333         tlb_flush_by_mmuidx(cs, mask);
4334     }
4335 }
4336 
4337 static int alle1_tlbmask(CPUARMState *env)
4338 {
4339     /*
4340      * Note that the 'ALL' scope must invalidate both stage 1 and
4341      * stage 2 translations, whereas most other scopes only invalidate
4342      * stage 1 translations.
4343      */
4344     if (arm_is_secure_below_el3(env)) {
4345         return ARMMMUIdxBit_SE10_1 |
4346                ARMMMUIdxBit_SE10_1_PAN |
4347                ARMMMUIdxBit_SE10_0;
4348     } else {
4349         return ARMMMUIdxBit_E10_1 |
4350                ARMMMUIdxBit_E10_1_PAN |
4351                ARMMMUIdxBit_E10_0;
4352     }
4353 }
4354 
4355 static int e2_tlbmask(CPUARMState *env)
4356 {
4357     if (arm_is_secure_below_el3(env)) {
4358         return ARMMMUIdxBit_SE20_0 |
4359                ARMMMUIdxBit_SE20_2 |
4360                ARMMMUIdxBit_SE20_2_PAN |
4361                ARMMMUIdxBit_SE2;
4362     } else {
4363         return ARMMMUIdxBit_E20_0 |
4364                ARMMMUIdxBit_E20_2 |
4365                ARMMMUIdxBit_E20_2_PAN |
4366                ARMMMUIdxBit_E2;
4367     }
4368 }
4369 
4370 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4371                                   uint64_t value)
4372 {
4373     CPUState *cs = env_cpu(env);
4374     int mask = alle1_tlbmask(env);
4375 
4376     tlb_flush_by_mmuidx(cs, mask);
4377 }
4378 
4379 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4380                                   uint64_t value)
4381 {
4382     CPUState *cs = env_cpu(env);
4383     int mask = e2_tlbmask(env);
4384 
4385     tlb_flush_by_mmuidx(cs, mask);
4386 }
4387 
4388 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4389                                   uint64_t value)
4390 {
4391     ARMCPU *cpu = env_archcpu(env);
4392     CPUState *cs = CPU(cpu);
4393 
4394     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4395 }
4396 
4397 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4398                                     uint64_t value)
4399 {
4400     CPUState *cs = env_cpu(env);
4401     int mask = alle1_tlbmask(env);
4402 
4403     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4404 }
4405 
4406 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4407                                     uint64_t value)
4408 {
4409     CPUState *cs = env_cpu(env);
4410     int mask = e2_tlbmask(env);
4411 
4412     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4413 }
4414 
4415 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4416                                     uint64_t value)
4417 {
4418     CPUState *cs = env_cpu(env);
4419 
4420     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4421 }
4422 
4423 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4424                                  uint64_t value)
4425 {
4426     /* Invalidate by VA, EL2
4427      * Currently handles both VAE2 and VALE2, since we don't support
4428      * flush-last-level-only.
4429      */
4430     CPUState *cs = env_cpu(env);
4431     int mask = e2_tlbmask(env);
4432     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4433 
4434     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4435 }
4436 
4437 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4438                                  uint64_t value)
4439 {
4440     /* Invalidate by VA, EL3
4441      * Currently handles both VAE3 and VALE3, since we don't support
4442      * flush-last-level-only.
4443      */
4444     ARMCPU *cpu = env_archcpu(env);
4445     CPUState *cs = CPU(cpu);
4446     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4447 
4448     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4449 }
4450 
4451 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4452                                    uint64_t value)
4453 {
4454     CPUState *cs = env_cpu(env);
4455     int mask = vae1_tlbmask(env);
4456     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4457     int bits = vae1_tlbbits(env, pageaddr);
4458 
4459     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4460 }
4461 
4462 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4463                                  uint64_t value)
4464 {
4465     /* Invalidate by VA, EL1&0 (AArch64 version).
4466      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4467      * since we don't support flush-for-specific-ASID-only or
4468      * flush-last-level-only.
4469      */
4470     CPUState *cs = env_cpu(env);
4471     int mask = vae1_tlbmask(env);
4472     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4473     int bits = vae1_tlbbits(env, pageaddr);
4474 
4475     if (tlb_force_broadcast(env)) {
4476         tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4477     } else {
4478         tlb_flush_page_bits_by_mmuidx(cs, pageaddr, mask, bits);
4479     }
4480 }
4481 
4482 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4483                                    uint64_t value)
4484 {
4485     CPUState *cs = env_cpu(env);
4486     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4487     bool secure = arm_is_secure_below_el3(env);
4488     int mask = secure ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2;
4489     int bits = tlbbits_for_regime(env, secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2,
4490                                   pageaddr);
4491 
4492     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4493 }
4494 
4495 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4496                                    uint64_t value)
4497 {
4498     CPUState *cs = env_cpu(env);
4499     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4500     int bits = tlbbits_for_regime(env, ARMMMUIdx_SE3, pageaddr);
4501 
4502     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr,
4503                                                   ARMMMUIdxBit_SE3, bits);
4504 }
4505 
4506 #ifdef TARGET_AARCH64
4507 typedef struct {
4508     uint64_t base;
4509     uint64_t length;
4510 } TLBIRange;
4511 
4512 static TLBIRange tlbi_aa64_get_range(CPUARMState *env, ARMMMUIdx mmuidx,
4513                                      uint64_t value)
4514 {
4515     unsigned int page_size_granule, page_shift, num, scale, exponent;
4516     /* Extract one bit to represent the va selector in use. */
4517     uint64_t select = sextract64(value, 36, 1);
4518     ARMVAParameters param = aa64_va_parameters(env, select, mmuidx, true);
4519     TLBIRange ret = { };
4520 
4521     page_size_granule = extract64(value, 46, 2);
4522 
4523     /* The granule encoded in value must match the granule in use. */
4524     if (page_size_granule != (param.using64k ? 3 : param.using16k ? 2 : 1)) {
4525         qemu_log_mask(LOG_GUEST_ERROR, "Invalid tlbi page size granule %d\n",
4526                       page_size_granule);
4527         return ret;
4528     }
4529 
4530     page_shift = (page_size_granule - 1) * 2 + 12;
4531     num = extract64(value, 39, 5);
4532     scale = extract64(value, 44, 2);
4533     exponent = (5 * scale) + 1;
4534 
4535     ret.length = (num + 1) << (exponent + page_shift);
4536 
4537     if (param.select) {
4538         ret.base = sextract64(value, 0, 37);
4539     } else {
4540         ret.base = extract64(value, 0, 37);
4541     }
4542     if (param.ds) {
4543         /*
4544          * With DS=1, BaseADDR is always shifted 16 so that it is able
4545          * to address all 52 va bits.  The input address is perforce
4546          * aligned on a 64k boundary regardless of translation granule.
4547          */
4548         page_shift = 16;
4549     }
4550     ret.base <<= page_shift;
4551 
4552     return ret;
4553 }
4554 
4555 static void do_rvae_write(CPUARMState *env, uint64_t value,
4556                           int idxmap, bool synced)
4557 {
4558     ARMMMUIdx one_idx = ARM_MMU_IDX_A | ctz32(idxmap);
4559     TLBIRange range;
4560     int bits;
4561 
4562     range = tlbi_aa64_get_range(env, one_idx, value);
4563     bits = tlbbits_for_regime(env, one_idx, range.base);
4564 
4565     if (synced) {
4566         tlb_flush_range_by_mmuidx_all_cpus_synced(env_cpu(env),
4567                                                   range.base,
4568                                                   range.length,
4569                                                   idxmap,
4570                                                   bits);
4571     } else {
4572         tlb_flush_range_by_mmuidx(env_cpu(env), range.base,
4573                                   range.length, idxmap, bits);
4574     }
4575 }
4576 
4577 static void tlbi_aa64_rvae1_write(CPUARMState *env,
4578                                   const ARMCPRegInfo *ri,
4579                                   uint64_t value)
4580 {
4581     /*
4582      * Invalidate by VA range, EL1&0.
4583      * Currently handles all of RVAE1, RVAAE1, RVAALE1 and RVALE1,
4584      * since we don't support flush-for-specific-ASID-only or
4585      * flush-last-level-only.
4586      */
4587 
4588     do_rvae_write(env, value, vae1_tlbmask(env),
4589                   tlb_force_broadcast(env));
4590 }
4591 
4592 static void tlbi_aa64_rvae1is_write(CPUARMState *env,
4593                                     const ARMCPRegInfo *ri,
4594                                     uint64_t value)
4595 {
4596     /*
4597      * Invalidate by VA range, Inner/Outer Shareable EL1&0.
4598      * Currently handles all of RVAE1IS, RVAE1OS, RVAAE1IS, RVAAE1OS,
4599      * RVAALE1IS, RVAALE1OS, RVALE1IS and RVALE1OS, since we don't support
4600      * flush-for-specific-ASID-only, flush-last-level-only or inner/outer
4601      * shareable specific flushes.
4602      */
4603 
4604     do_rvae_write(env, value, vae1_tlbmask(env), true);
4605 }
4606 
4607 static int vae2_tlbmask(CPUARMState *env)
4608 {
4609     return (arm_is_secure_below_el3(env)
4610             ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2);
4611 }
4612 
4613 static void tlbi_aa64_rvae2_write(CPUARMState *env,
4614                                   const ARMCPRegInfo *ri,
4615                                   uint64_t value)
4616 {
4617     /*
4618      * Invalidate by VA range, EL2.
4619      * Currently handles all of RVAE2 and RVALE2,
4620      * since we don't support flush-for-specific-ASID-only or
4621      * flush-last-level-only.
4622      */
4623 
4624     do_rvae_write(env, value, vae2_tlbmask(env),
4625                   tlb_force_broadcast(env));
4626 
4627 
4628 }
4629 
4630 static void tlbi_aa64_rvae2is_write(CPUARMState *env,
4631                                     const ARMCPRegInfo *ri,
4632                                     uint64_t value)
4633 {
4634     /*
4635      * Invalidate by VA range, Inner/Outer Shareable, EL2.
4636      * Currently handles all of RVAE2IS, RVAE2OS, RVALE2IS and RVALE2OS,
4637      * since we don't support flush-for-specific-ASID-only,
4638      * flush-last-level-only or inner/outer shareable specific flushes.
4639      */
4640 
4641     do_rvae_write(env, value, vae2_tlbmask(env), true);
4642 
4643 }
4644 
4645 static void tlbi_aa64_rvae3_write(CPUARMState *env,
4646                                   const ARMCPRegInfo *ri,
4647                                   uint64_t value)
4648 {
4649     /*
4650      * Invalidate by VA range, EL3.
4651      * Currently handles all of RVAE3 and RVALE3,
4652      * since we don't support flush-for-specific-ASID-only or
4653      * flush-last-level-only.
4654      */
4655 
4656     do_rvae_write(env, value, ARMMMUIdxBit_SE3,
4657                   tlb_force_broadcast(env));
4658 }
4659 
4660 static void tlbi_aa64_rvae3is_write(CPUARMState *env,
4661                                     const ARMCPRegInfo *ri,
4662                                     uint64_t value)
4663 {
4664     /*
4665      * Invalidate by VA range, EL3, Inner/Outer Shareable.
4666      * Currently handles all of RVAE3IS, RVAE3OS, RVALE3IS and RVALE3OS,
4667      * since we don't support flush-for-specific-ASID-only,
4668      * flush-last-level-only or inner/outer specific flushes.
4669      */
4670 
4671     do_rvae_write(env, value, ARMMMUIdxBit_SE3, true);
4672 }
4673 #endif
4674 
4675 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4676                                       bool isread)
4677 {
4678     int cur_el = arm_current_el(env);
4679 
4680     if (cur_el < 2) {
4681         uint64_t hcr = arm_hcr_el2_eff(env);
4682 
4683         if (cur_el == 0) {
4684             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4685                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4686                     return CP_ACCESS_TRAP_EL2;
4687                 }
4688             } else {
4689                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4690                     return CP_ACCESS_TRAP;
4691                 }
4692                 if (hcr & HCR_TDZ) {
4693                     return CP_ACCESS_TRAP_EL2;
4694                 }
4695             }
4696         } else if (hcr & HCR_TDZ) {
4697             return CP_ACCESS_TRAP_EL2;
4698         }
4699     }
4700     return CP_ACCESS_OK;
4701 }
4702 
4703 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4704 {
4705     ARMCPU *cpu = env_archcpu(env);
4706     int dzp_bit = 1 << 4;
4707 
4708     /* DZP indicates whether DC ZVA access is allowed */
4709     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4710         dzp_bit = 0;
4711     }
4712     return cpu->dcz_blocksize | dzp_bit;
4713 }
4714 
4715 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4716                                     bool isread)
4717 {
4718     if (!(env->pstate & PSTATE_SP)) {
4719         /* Access to SP_EL0 is undefined if it's being used as
4720          * the stack pointer.
4721          */
4722         return CP_ACCESS_TRAP_UNCATEGORIZED;
4723     }
4724     return CP_ACCESS_OK;
4725 }
4726 
4727 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4728 {
4729     return env->pstate & PSTATE_SP;
4730 }
4731 
4732 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4733 {
4734     update_spsel(env, val);
4735 }
4736 
4737 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4738                         uint64_t value)
4739 {
4740     ARMCPU *cpu = env_archcpu(env);
4741 
4742     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4743         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4744         value &= ~SCTLR_M;
4745     }
4746 
4747     /* ??? Lots of these bits are not implemented.  */
4748 
4749     if (ri->state == ARM_CP_STATE_AA64 && !cpu_isar_feature(aa64_mte, cpu)) {
4750         if (ri->opc1 == 6) { /* SCTLR_EL3 */
4751             value &= ~(SCTLR_ITFSB | SCTLR_TCF | SCTLR_ATA);
4752         } else {
4753             value &= ~(SCTLR_ITFSB | SCTLR_TCF0 | SCTLR_TCF |
4754                        SCTLR_ATA0 | SCTLR_ATA);
4755         }
4756     }
4757 
4758     if (raw_read(env, ri) == value) {
4759         /* Skip the TLB flush if nothing actually changed; Linux likes
4760          * to do a lot of pointless SCTLR writes.
4761          */
4762         return;
4763     }
4764 
4765     raw_write(env, ri, value);
4766 
4767     /* This may enable/disable the MMU, so do a TLB flush.  */
4768     tlb_flush(CPU(cpu));
4769 
4770     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4771         /*
4772          * Normally we would always end the TB on an SCTLR write; see the
4773          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4774          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4775          * of hflags from the translator, so do it here.
4776          */
4777         arm_rebuild_hflags(env);
4778     }
4779 }
4780 
4781 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4782                        uint64_t value)
4783 {
4784     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4785 }
4786 
4787 static const ARMCPRegInfo v8_cp_reginfo[] = {
4788     /* Minimal set of EL0-visible registers. This will need to be expanded
4789      * significantly for system emulation of AArch64 CPUs.
4790      */
4791     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4792       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4793       .access = PL0_RW, .type = ARM_CP_NZCV },
4794     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4795       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4796       .type = ARM_CP_NO_RAW,
4797       .access = PL0_RW, .accessfn = aa64_daif_access,
4798       .fieldoffset = offsetof(CPUARMState, daif),
4799       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4800     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4801       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4802       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4803       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4804     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4805       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4806       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4807       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4808     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4809       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4810       .access = PL0_R, .type = ARM_CP_NO_RAW,
4811       .readfn = aa64_dczid_read },
4812     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4813       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4814       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4815 #ifndef CONFIG_USER_ONLY
4816       /* Avoid overhead of an access check that always passes in user-mode */
4817       .accessfn = aa64_zva_access,
4818 #endif
4819     },
4820     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4821       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4822       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4823     /* Cache ops: all NOPs since we don't emulate caches */
4824     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4825       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4826       .access = PL1_W, .type = ARM_CP_NOP,
4827       .accessfn = aa64_cacheop_pou_access },
4828     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4829       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4830       .access = PL1_W, .type = ARM_CP_NOP,
4831       .accessfn = aa64_cacheop_pou_access },
4832     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4833       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4834       .access = PL0_W, .type = ARM_CP_NOP,
4835       .accessfn = aa64_cacheop_pou_access },
4836     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4837       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4838       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4839       .type = ARM_CP_NOP },
4840     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4841       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4842       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4843     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4844       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4845       .access = PL0_W, .type = ARM_CP_NOP,
4846       .accessfn = aa64_cacheop_poc_access },
4847     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4848       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4849       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4850     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4851       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4852       .access = PL0_W, .type = ARM_CP_NOP,
4853       .accessfn = aa64_cacheop_pou_access },
4854     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4855       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4856       .access = PL0_W, .type = ARM_CP_NOP,
4857       .accessfn = aa64_cacheop_poc_access },
4858     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4859       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4860       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4861     /* TLBI operations */
4862     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4863       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4864       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4865       .writefn = tlbi_aa64_vmalle1is_write },
4866     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4867       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4868       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4869       .writefn = tlbi_aa64_vae1is_write },
4870     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4871       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4872       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4873       .writefn = tlbi_aa64_vmalle1is_write },
4874     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4875       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4876       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4877       .writefn = tlbi_aa64_vae1is_write },
4878     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4879       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4880       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4881       .writefn = tlbi_aa64_vae1is_write },
4882     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4883       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4884       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4885       .writefn = tlbi_aa64_vae1is_write },
4886     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4887       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4888       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4889       .writefn = tlbi_aa64_vmalle1_write },
4890     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4891       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4892       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4893       .writefn = tlbi_aa64_vae1_write },
4894     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4895       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4896       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4897       .writefn = tlbi_aa64_vmalle1_write },
4898     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4899       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4900       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4901       .writefn = tlbi_aa64_vae1_write },
4902     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4903       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4904       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4905       .writefn = tlbi_aa64_vae1_write },
4906     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4907       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4908       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4909       .writefn = tlbi_aa64_vae1_write },
4910     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4911       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4912       .access = PL2_W, .type = ARM_CP_NOP },
4913     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4914       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4915       .access = PL2_W, .type = ARM_CP_NOP },
4916     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4917       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4918       .access = PL2_W, .type = ARM_CP_NO_RAW,
4919       .writefn = tlbi_aa64_alle1is_write },
4920     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4921       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4922       .access = PL2_W, .type = ARM_CP_NO_RAW,
4923       .writefn = tlbi_aa64_alle1is_write },
4924     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4925       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4926       .access = PL2_W, .type = ARM_CP_NOP },
4927     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4928       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4929       .access = PL2_W, .type = ARM_CP_NOP },
4930     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4931       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4932       .access = PL2_W, .type = ARM_CP_NO_RAW,
4933       .writefn = tlbi_aa64_alle1_write },
4934     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4935       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4936       .access = PL2_W, .type = ARM_CP_NO_RAW,
4937       .writefn = tlbi_aa64_alle1is_write },
4938 #ifndef CONFIG_USER_ONLY
4939     /* 64 bit address translation operations */
4940     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4941       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4942       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4943       .writefn = ats_write64 },
4944     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4945       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4946       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4947       .writefn = ats_write64 },
4948     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4949       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4950       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4951       .writefn = ats_write64 },
4952     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4953       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4954       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4955       .writefn = ats_write64 },
4956     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4957       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4958       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4959       .writefn = ats_write64 },
4960     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4961       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4962       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4963       .writefn = ats_write64 },
4964     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4965       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4966       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4967       .writefn = ats_write64 },
4968     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4969       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4970       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4971       .writefn = ats_write64 },
4972     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4973     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4974       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4975       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4976       .writefn = ats_write64 },
4977     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4978       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4979       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4980       .writefn = ats_write64 },
4981     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4982       .type = ARM_CP_ALIAS,
4983       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4984       .access = PL1_RW, .resetvalue = 0,
4985       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4986       .writefn = par_write },
4987 #endif
4988     /* TLB invalidate last level of translation table walk */
4989     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4990       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4991       .writefn = tlbimva_is_write },
4992     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4993       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4994       .writefn = tlbimvaa_is_write },
4995     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4996       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4997       .writefn = tlbimva_write },
4998     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4999       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5000       .writefn = tlbimvaa_write },
5001     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5002       .type = ARM_CP_NO_RAW, .access = PL2_W,
5003       .writefn = tlbimva_hyp_write },
5004     { .name = "TLBIMVALHIS",
5005       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5006       .type = ARM_CP_NO_RAW, .access = PL2_W,
5007       .writefn = tlbimva_hyp_is_write },
5008     { .name = "TLBIIPAS2",
5009       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5010       .type = ARM_CP_NOP, .access = PL2_W },
5011     { .name = "TLBIIPAS2IS",
5012       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5013       .type = ARM_CP_NOP, .access = PL2_W },
5014     { .name = "TLBIIPAS2L",
5015       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5016       .type = ARM_CP_NOP, .access = PL2_W },
5017     { .name = "TLBIIPAS2LIS",
5018       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5019       .type = ARM_CP_NOP, .access = PL2_W },
5020     /* 32 bit cache operations */
5021     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5022       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5023     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5024       .type = ARM_CP_NOP, .access = PL1_W },
5025     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5026       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5027     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5028       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5029     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5030       .type = ARM_CP_NOP, .access = PL1_W },
5031     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5032       .type = ARM_CP_NOP, .access = PL1_W },
5033     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5034       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5035     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5036       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5037     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5038       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5039     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5040       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5041     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5042       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5043     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5044       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5045     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5046       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5047     /* MMU Domain access control / MPU write buffer control */
5048     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5049       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5050       .writefn = dacr_write, .raw_writefn = raw_write,
5051       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5052                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5053     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5054       .type = ARM_CP_ALIAS,
5055       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5056       .access = PL1_RW,
5057       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5058     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5059       .type = ARM_CP_ALIAS,
5060       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5061       .access = PL1_RW,
5062       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5063     /* We rely on the access checks not allowing the guest to write to the
5064      * state field when SPSel indicates that it's being used as the stack
5065      * pointer.
5066      */
5067     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5068       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5069       .access = PL1_RW, .accessfn = sp_el0_access,
5070       .type = ARM_CP_ALIAS,
5071       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5072     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5073       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5074       .access = PL2_RW, .type = ARM_CP_ALIAS,
5075       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5076     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5077       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5078       .type = ARM_CP_NO_RAW,
5079       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5080     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5081       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5082       .access = PL2_RW,
5083       .type = ARM_CP_ALIAS | ARM_CP_FPU | ARM_CP_EL3_NO_EL2_KEEP,
5084       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]) },
5085     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5086       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5087       .access = PL2_RW, .resetvalue = 0, .type = ARM_CP_EL3_NO_EL2_KEEP,
5088       .writefn = dacr_write, .raw_writefn = raw_write,
5089       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5090     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5091       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5092       .access = PL2_RW, .resetvalue = 0, .type = ARM_CP_EL3_NO_EL2_KEEP,
5093       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5094     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5095       .type = ARM_CP_ALIAS,
5096       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5097       .access = PL2_RW,
5098       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5099     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5100       .type = ARM_CP_ALIAS,
5101       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5102       .access = PL2_RW,
5103       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5104     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5105       .type = ARM_CP_ALIAS,
5106       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5107       .access = PL2_RW,
5108       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5109     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5110       .type = ARM_CP_ALIAS,
5111       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5112       .access = PL2_RW,
5113       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5114     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5115       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5116       .resetvalue = 0,
5117       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5118     { .name = "SDCR", .type = ARM_CP_ALIAS,
5119       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5120       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5121       .writefn = sdcr_write,
5122       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5123 };
5124 
5125 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5126 {
5127     ARMCPU *cpu = env_archcpu(env);
5128 
5129     if (arm_feature(env, ARM_FEATURE_V8)) {
5130         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5131     } else {
5132         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5133     }
5134 
5135     if (arm_feature(env, ARM_FEATURE_EL3)) {
5136         valid_mask &= ~HCR_HCD;
5137     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5138         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5139          * However, if we're using the SMC PSCI conduit then QEMU is
5140          * effectively acting like EL3 firmware and so the guest at
5141          * EL2 should retain the ability to prevent EL1 from being
5142          * able to make SMC calls into the ersatz firmware, so in
5143          * that case HCR.TSC should be read/write.
5144          */
5145         valid_mask &= ~HCR_TSC;
5146     }
5147 
5148     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5149         if (cpu_isar_feature(aa64_vh, cpu)) {
5150             valid_mask |= HCR_E2H;
5151         }
5152         if (cpu_isar_feature(aa64_ras, cpu)) {
5153             valid_mask |= HCR_TERR | HCR_TEA;
5154         }
5155         if (cpu_isar_feature(aa64_lor, cpu)) {
5156             valid_mask |= HCR_TLOR;
5157         }
5158         if (cpu_isar_feature(aa64_pauth, cpu)) {
5159             valid_mask |= HCR_API | HCR_APK;
5160         }
5161         if (cpu_isar_feature(aa64_mte, cpu)) {
5162             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5163         }
5164         if (cpu_isar_feature(aa64_scxtnum, cpu)) {
5165             valid_mask |= HCR_ENSCXT;
5166         }
5167         if (cpu_isar_feature(aa64_fwb, cpu)) {
5168             valid_mask |= HCR_FWB;
5169         }
5170     }
5171 
5172     /* Clear RES0 bits.  */
5173     value &= valid_mask;
5174 
5175     /*
5176      * These bits change the MMU setup:
5177      * HCR_VM enables stage 2 translation
5178      * HCR_PTW forbids certain page-table setups
5179      * HCR_DC disables stage1 and enables stage2 translation
5180      * HCR_DCT enables tagging on (disabled) stage1 translation
5181      * HCR_FWB changes the interpretation of stage2 descriptor bits
5182      */
5183     if ((env->cp15.hcr_el2 ^ value) &
5184         (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT | HCR_FWB)) {
5185         tlb_flush(CPU(cpu));
5186     }
5187     env->cp15.hcr_el2 = value;
5188 
5189     /*
5190      * Updates to VI and VF require us to update the status of
5191      * virtual interrupts, which are the logical OR of these bits
5192      * and the state of the input lines from the GIC. (This requires
5193      * that we have the iothread lock, which is done by marking the
5194      * reginfo structs as ARM_CP_IO.)
5195      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5196      * possible for it to be taken immediately, because VIRQ and
5197      * VFIQ are masked unless running at EL0 or EL1, and HCR
5198      * can only be written at EL2.
5199      */
5200     g_assert(qemu_mutex_iothread_locked());
5201     arm_cpu_update_virq(cpu);
5202     arm_cpu_update_vfiq(cpu);
5203     arm_cpu_update_vserr(cpu);
5204 }
5205 
5206 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5207 {
5208     do_hcr_write(env, value, 0);
5209 }
5210 
5211 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5212                           uint64_t value)
5213 {
5214     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5215     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5216     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5217 }
5218 
5219 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5220                          uint64_t value)
5221 {
5222     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5223     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5224     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5225 }
5226 
5227 /*
5228  * Return the effective value of HCR_EL2.
5229  * Bits that are not included here:
5230  * RW       (read from SCR_EL3.RW as needed)
5231  */
5232 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5233 {
5234     uint64_t ret = env->cp15.hcr_el2;
5235 
5236     if (!arm_is_el2_enabled(env)) {
5237         /*
5238          * "This register has no effect if EL2 is not enabled in the
5239          * current Security state".  This is ARMv8.4-SecEL2 speak for
5240          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5241          *
5242          * Prior to that, the language was "In an implementation that
5243          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5244          * as if this field is 0 for all purposes other than a direct
5245          * read or write access of HCR_EL2".  With lots of enumeration
5246          * on a per-field basis.  In current QEMU, this is condition
5247          * is arm_is_secure_below_el3.
5248          *
5249          * Since the v8.4 language applies to the entire register, and
5250          * appears to be backward compatible, use that.
5251          */
5252         return 0;
5253     }
5254 
5255     /*
5256      * For a cpu that supports both aarch64 and aarch32, we can set bits
5257      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5258      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5259      */
5260     if (!arm_el_is_aa64(env, 2)) {
5261         uint64_t aa32_valid;
5262 
5263         /*
5264          * These bits are up-to-date as of ARMv8.6.
5265          * For HCR, it's easiest to list just the 2 bits that are invalid.
5266          * For HCR2, list those that are valid.
5267          */
5268         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5269         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5270                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5271         ret &= aa32_valid;
5272     }
5273 
5274     if (ret & HCR_TGE) {
5275         /* These bits are up-to-date as of ARMv8.6.  */
5276         if (ret & HCR_E2H) {
5277             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5278                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5279                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5280                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5281                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5282                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5283         } else {
5284             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5285         }
5286         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5287                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5288                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5289                  HCR_TLOR);
5290     }
5291 
5292     return ret;
5293 }
5294 
5295 static void hcrx_write(CPUARMState *env, const ARMCPRegInfo *ri,
5296                        uint64_t value)
5297 {
5298     uint64_t valid_mask = 0;
5299 
5300     /* No features adding bits to HCRX are implemented. */
5301 
5302     /* Clear RES0 bits.  */
5303     env->cp15.hcrx_el2 = value & valid_mask;
5304 }
5305 
5306 static CPAccessResult access_hxen(CPUARMState *env, const ARMCPRegInfo *ri,
5307                                   bool isread)
5308 {
5309     if (arm_current_el(env) < 3
5310         && arm_feature(env, ARM_FEATURE_EL3)
5311         && !(env->cp15.scr_el3 & SCR_HXEN)) {
5312         return CP_ACCESS_TRAP_EL3;
5313     }
5314     return CP_ACCESS_OK;
5315 }
5316 
5317 static const ARMCPRegInfo hcrx_el2_reginfo = {
5318     .name = "HCRX_EL2", .state = ARM_CP_STATE_AA64,
5319     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 2,
5320     .access = PL2_RW, .writefn = hcrx_write, .accessfn = access_hxen,
5321     .fieldoffset = offsetof(CPUARMState, cp15.hcrx_el2),
5322 };
5323 
5324 /* Return the effective value of HCRX_EL2.  */
5325 uint64_t arm_hcrx_el2_eff(CPUARMState *env)
5326 {
5327     /*
5328      * The bits in this register behave as 0 for all purposes other than
5329      * direct reads of the register if:
5330      *   - EL2 is not enabled in the current security state,
5331      *   - SCR_EL3.HXEn is 0.
5332      */
5333     if (!arm_is_el2_enabled(env)
5334         || (arm_feature(env, ARM_FEATURE_EL3)
5335             && !(env->cp15.scr_el3 & SCR_HXEN))) {
5336         return 0;
5337     }
5338     return env->cp15.hcrx_el2;
5339 }
5340 
5341 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5342                            uint64_t value)
5343 {
5344     /*
5345      * For A-profile AArch32 EL3, if NSACR.CP10
5346      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5347      */
5348     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5349         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5350         uint64_t mask = R_HCPTR_TCP11_MASK | R_HCPTR_TCP10_MASK;
5351         value = (value & ~mask) | (env->cp15.cptr_el[2] & mask);
5352     }
5353     env->cp15.cptr_el[2] = value;
5354 }
5355 
5356 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5357 {
5358     /*
5359      * For A-profile AArch32 EL3, if NSACR.CP10
5360      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5361      */
5362     uint64_t value = env->cp15.cptr_el[2];
5363 
5364     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5365         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5366         value |= R_HCPTR_TCP11_MASK | R_HCPTR_TCP10_MASK;
5367     }
5368     return value;
5369 }
5370 
5371 static const ARMCPRegInfo el2_cp_reginfo[] = {
5372     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5373       .type = ARM_CP_IO,
5374       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5375       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5376       .writefn = hcr_write },
5377     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5378       .type = ARM_CP_ALIAS | ARM_CP_IO,
5379       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5380       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5381       .writefn = hcr_writelow },
5382     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5383       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5384       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5385     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5386       .type = ARM_CP_ALIAS,
5387       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5388       .access = PL2_RW,
5389       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5390     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5391       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5392       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5393     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5394       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5395       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5396     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5397       .type = ARM_CP_ALIAS,
5398       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5399       .access = PL2_RW,
5400       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5401     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5402       .type = ARM_CP_ALIAS,
5403       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5404       .access = PL2_RW,
5405       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5406     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5407       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5408       .access = PL2_RW, .writefn = vbar_write,
5409       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5410       .resetvalue = 0 },
5411     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5412       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5413       .access = PL3_RW, .type = ARM_CP_ALIAS,
5414       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5415     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5416       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5417       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5418       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5419       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5420     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5421       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5422       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5423       .resetvalue = 0 },
5424     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5425       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5426       .access = PL2_RW, .type = ARM_CP_ALIAS,
5427       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5428     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5429       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5430       .access = PL2_RW, .type = ARM_CP_CONST,
5431       .resetvalue = 0 },
5432     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5433     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5434       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5435       .access = PL2_RW, .type = ARM_CP_CONST,
5436       .resetvalue = 0 },
5437     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5438       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5439       .access = PL2_RW, .type = ARM_CP_CONST,
5440       .resetvalue = 0 },
5441     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5442       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5443       .access = PL2_RW, .type = ARM_CP_CONST,
5444       .resetvalue = 0 },
5445     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5446       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5447       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5448       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5449       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5450     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5451       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5452       .type = ARM_CP_ALIAS,
5453       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5454       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5455     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5456       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5457       .access = PL2_RW,
5458       /* no .writefn needed as this can't cause an ASID change;
5459        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5460        */
5461       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5462     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5463       .cp = 15, .opc1 = 6, .crm = 2,
5464       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5465       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5466       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5467       .writefn = vttbr_write },
5468     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5469       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5470       .access = PL2_RW, .writefn = vttbr_write,
5471       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5472     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5473       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5474       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5475       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5476     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5477       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5478       .access = PL2_RW, .resetvalue = 0,
5479       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5480     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5481       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5482       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5483       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5484     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5485       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5486       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5487     { .name = "TLBIALLNSNH",
5488       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5489       .type = ARM_CP_NO_RAW, .access = PL2_W,
5490       .writefn = tlbiall_nsnh_write },
5491     { .name = "TLBIALLNSNHIS",
5492       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5493       .type = ARM_CP_NO_RAW, .access = PL2_W,
5494       .writefn = tlbiall_nsnh_is_write },
5495     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5496       .type = ARM_CP_NO_RAW, .access = PL2_W,
5497       .writefn = tlbiall_hyp_write },
5498     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5499       .type = ARM_CP_NO_RAW, .access = PL2_W,
5500       .writefn = tlbiall_hyp_is_write },
5501     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5502       .type = ARM_CP_NO_RAW, .access = PL2_W,
5503       .writefn = tlbimva_hyp_write },
5504     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5505       .type = ARM_CP_NO_RAW, .access = PL2_W,
5506       .writefn = tlbimva_hyp_is_write },
5507     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5508       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5509       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5510       .writefn = tlbi_aa64_alle2_write },
5511     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5512       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5513       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5514       .writefn = tlbi_aa64_vae2_write },
5515     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5516       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5517       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5518       .writefn = tlbi_aa64_vae2_write },
5519     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5520       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5521       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5522       .writefn = tlbi_aa64_alle2is_write },
5523     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5524       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5525       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5526       .writefn = tlbi_aa64_vae2is_write },
5527     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5528       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5529       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5530       .writefn = tlbi_aa64_vae2is_write },
5531 #ifndef CONFIG_USER_ONLY
5532     /* Unlike the other EL2-related AT operations, these must
5533      * UNDEF from EL3 if EL2 is not implemented, which is why we
5534      * define them here rather than with the rest of the AT ops.
5535      */
5536     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5537       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5538       .access = PL2_W, .accessfn = at_s1e2_access,
5539       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC | ARM_CP_EL3_NO_EL2_UNDEF,
5540       .writefn = ats_write64 },
5541     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5542       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5543       .access = PL2_W, .accessfn = at_s1e2_access,
5544       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC | ARM_CP_EL3_NO_EL2_UNDEF,
5545       .writefn = ats_write64 },
5546     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5547      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5548      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5549      * to behave as if SCR.NS was 1.
5550      */
5551     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5552       .access = PL2_W,
5553       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5554     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5555       .access = PL2_W,
5556       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5557     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5558       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5559       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5560        * reset values as IMPDEF. We choose to reset to 3 to comply with
5561        * both ARMv7 and ARMv8.
5562        */
5563       .access = PL2_RW, .resetvalue = 3,
5564       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5565     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5566       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5567       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5568       .writefn = gt_cntvoff_write,
5569       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5570     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5571       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5572       .writefn = gt_cntvoff_write,
5573       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5574     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5575       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5576       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5577       .type = ARM_CP_IO, .access = PL2_RW,
5578       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5579     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5580       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5581       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5582       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5583     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5584       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5585       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5586       .resetfn = gt_hyp_timer_reset,
5587       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5588     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5589       .type = ARM_CP_IO,
5590       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5591       .access = PL2_RW,
5592       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5593       .resetvalue = 0,
5594       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5595 #endif
5596     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5597       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5598       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5599       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5600     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5601       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5602       .access = PL2_RW,
5603       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5604     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5605       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5606       .access = PL2_RW,
5607       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5608 };
5609 
5610 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5611     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5612       .type = ARM_CP_ALIAS | ARM_CP_IO,
5613       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5614       .access = PL2_RW,
5615       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5616       .writefn = hcr_writehigh },
5617 };
5618 
5619 static CPAccessResult sel2_access(CPUARMState *env, const ARMCPRegInfo *ri,
5620                                   bool isread)
5621 {
5622     if (arm_current_el(env) == 3 || arm_is_secure_below_el3(env)) {
5623         return CP_ACCESS_OK;
5624     }
5625     return CP_ACCESS_TRAP_UNCATEGORIZED;
5626 }
5627 
5628 static const ARMCPRegInfo el2_sec_cp_reginfo[] = {
5629     { .name = "VSTTBR_EL2", .state = ARM_CP_STATE_AA64,
5630       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 0,
5631       .access = PL2_RW, .accessfn = sel2_access,
5632       .fieldoffset = offsetof(CPUARMState, cp15.vsttbr_el2) },
5633     { .name = "VSTCR_EL2", .state = ARM_CP_STATE_AA64,
5634       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 2,
5635       .access = PL2_RW, .accessfn = sel2_access,
5636       .fieldoffset = offsetof(CPUARMState, cp15.vstcr_el2) },
5637 };
5638 
5639 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5640                                    bool isread)
5641 {
5642     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5643      * At Secure EL1 it traps to EL3 or EL2.
5644      */
5645     if (arm_current_el(env) == 3) {
5646         return CP_ACCESS_OK;
5647     }
5648     if (arm_is_secure_below_el3(env)) {
5649         if (env->cp15.scr_el3 & SCR_EEL2) {
5650             return CP_ACCESS_TRAP_EL2;
5651         }
5652         return CP_ACCESS_TRAP_EL3;
5653     }
5654     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5655     if (isread) {
5656         return CP_ACCESS_OK;
5657     }
5658     return CP_ACCESS_TRAP_UNCATEGORIZED;
5659 }
5660 
5661 static const ARMCPRegInfo el3_cp_reginfo[] = {
5662     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5663       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5664       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5665       .resetfn = scr_reset, .writefn = scr_write },
5666     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5667       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5668       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5669       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5670       .writefn = scr_write },
5671     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5672       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5673       .access = PL3_RW, .resetvalue = 0,
5674       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5675     { .name = "SDER",
5676       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5677       .access = PL3_RW, .resetvalue = 0,
5678       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5679     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5680       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5681       .writefn = vbar_write, .resetvalue = 0,
5682       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5683     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5684       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5685       .access = PL3_RW, .resetvalue = 0,
5686       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5687     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5688       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5689       .access = PL3_RW,
5690       /* no .writefn needed as this can't cause an ASID change;
5691        * we must provide a .raw_writefn and .resetfn because we handle
5692        * reset and migration for the AArch32 TTBCR(S), which might be
5693        * using mask and base_mask.
5694        */
5695       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5696       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5697     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5698       .type = ARM_CP_ALIAS,
5699       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5700       .access = PL3_RW,
5701       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5702     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5703       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5704       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5705     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5706       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5707       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5708     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5709       .type = ARM_CP_ALIAS,
5710       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5711       .access = PL3_RW,
5712       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5713     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5714       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5715       .access = PL3_RW, .writefn = vbar_write,
5716       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5717       .resetvalue = 0 },
5718     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5719       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5720       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5721       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5722     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5723       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5724       .access = PL3_RW, .resetvalue = 0,
5725       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5726     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5727       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5728       .access = PL3_RW, .type = ARM_CP_CONST,
5729       .resetvalue = 0 },
5730     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5731       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5732       .access = PL3_RW, .type = ARM_CP_CONST,
5733       .resetvalue = 0 },
5734     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5735       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5736       .access = PL3_RW, .type = ARM_CP_CONST,
5737       .resetvalue = 0 },
5738     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5739       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5740       .access = PL3_W, .type = ARM_CP_NO_RAW,
5741       .writefn = tlbi_aa64_alle3is_write },
5742     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5743       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5744       .access = PL3_W, .type = ARM_CP_NO_RAW,
5745       .writefn = tlbi_aa64_vae3is_write },
5746     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5747       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5748       .access = PL3_W, .type = ARM_CP_NO_RAW,
5749       .writefn = tlbi_aa64_vae3is_write },
5750     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5751       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5752       .access = PL3_W, .type = ARM_CP_NO_RAW,
5753       .writefn = tlbi_aa64_alle3_write },
5754     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5755       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5756       .access = PL3_W, .type = ARM_CP_NO_RAW,
5757       .writefn = tlbi_aa64_vae3_write },
5758     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5759       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5760       .access = PL3_W, .type = ARM_CP_NO_RAW,
5761       .writefn = tlbi_aa64_vae3_write },
5762 };
5763 
5764 #ifndef CONFIG_USER_ONLY
5765 /* Test if system register redirection is to occur in the current state.  */
5766 static bool redirect_for_e2h(CPUARMState *env)
5767 {
5768     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5769 }
5770 
5771 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5772 {
5773     CPReadFn *readfn;
5774 
5775     if (redirect_for_e2h(env)) {
5776         /* Switch to the saved EL2 version of the register.  */
5777         ri = ri->opaque;
5778         readfn = ri->readfn;
5779     } else {
5780         readfn = ri->orig_readfn;
5781     }
5782     if (readfn == NULL) {
5783         readfn = raw_read;
5784     }
5785     return readfn(env, ri);
5786 }
5787 
5788 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5789                           uint64_t value)
5790 {
5791     CPWriteFn *writefn;
5792 
5793     if (redirect_for_e2h(env)) {
5794         /* Switch to the saved EL2 version of the register.  */
5795         ri = ri->opaque;
5796         writefn = ri->writefn;
5797     } else {
5798         writefn = ri->orig_writefn;
5799     }
5800     if (writefn == NULL) {
5801         writefn = raw_write;
5802     }
5803     writefn(env, ri, value);
5804 }
5805 
5806 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5807 {
5808     struct E2HAlias {
5809         uint32_t src_key, dst_key, new_key;
5810         const char *src_name, *dst_name, *new_name;
5811         bool (*feature)(const ARMISARegisters *id);
5812     };
5813 
5814 #define K(op0, op1, crn, crm, op2) \
5815     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5816 
5817     static const struct E2HAlias aliases[] = {
5818         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5819           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5820         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5821           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5822         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5823           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5824         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5825           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5826         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5827           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5828         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5829           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5830         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5831           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5832         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5833           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5834         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5835           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5836         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5837           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5838         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5839           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5840         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5841           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5842         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5843           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5844         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5845           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5846         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5847           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5848         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5849           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5850 
5851         /*
5852          * Note that redirection of ZCR is mentioned in the description
5853          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5854          * not in the summary table.
5855          */
5856         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5857           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5858 
5859         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
5860           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
5861 
5862         { K(3, 0, 13, 0, 7), K(3, 4, 13, 0, 7), K(3, 5, 13, 0, 7),
5863           "SCXTNUM_EL1", "SCXTNUM_EL2", "SCXTNUM_EL12",
5864           isar_feature_aa64_scxtnum },
5865 
5866         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5867         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5868     };
5869 #undef K
5870 
5871     size_t i;
5872 
5873     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5874         const struct E2HAlias *a = &aliases[i];
5875         ARMCPRegInfo *src_reg, *dst_reg, *new_reg;
5876         bool ok;
5877 
5878         if (a->feature && !a->feature(&cpu->isar)) {
5879             continue;
5880         }
5881 
5882         src_reg = g_hash_table_lookup(cpu->cp_regs,
5883                                       (gpointer)(uintptr_t)a->src_key);
5884         dst_reg = g_hash_table_lookup(cpu->cp_regs,
5885                                       (gpointer)(uintptr_t)a->dst_key);
5886         g_assert(src_reg != NULL);
5887         g_assert(dst_reg != NULL);
5888 
5889         /* Cross-compare names to detect typos in the keys.  */
5890         g_assert(strcmp(src_reg->name, a->src_name) == 0);
5891         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
5892 
5893         /* None of the core system registers use opaque; we will.  */
5894         g_assert(src_reg->opaque == NULL);
5895 
5896         /* Create alias before redirection so we dup the right data. */
5897         new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
5898 
5899         new_reg->name = a->new_name;
5900         new_reg->type |= ARM_CP_ALIAS;
5901         /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
5902         new_reg->access &= PL2_RW | PL3_RW;
5903 
5904         ok = g_hash_table_insert(cpu->cp_regs,
5905                                  (gpointer)(uintptr_t)a->new_key, new_reg);
5906         g_assert(ok);
5907 
5908         src_reg->opaque = dst_reg;
5909         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
5910         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
5911         if (!src_reg->raw_readfn) {
5912             src_reg->raw_readfn = raw_read;
5913         }
5914         if (!src_reg->raw_writefn) {
5915             src_reg->raw_writefn = raw_write;
5916         }
5917         src_reg->readfn = el2_e2h_read;
5918         src_reg->writefn = el2_e2h_write;
5919     }
5920 }
5921 #endif
5922 
5923 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5924                                      bool isread)
5925 {
5926     int cur_el = arm_current_el(env);
5927 
5928     if (cur_el < 2) {
5929         uint64_t hcr = arm_hcr_el2_eff(env);
5930 
5931         if (cur_el == 0) {
5932             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
5933                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
5934                     return CP_ACCESS_TRAP_EL2;
5935                 }
5936             } else {
5937                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5938                     return CP_ACCESS_TRAP;
5939                 }
5940                 if (hcr & HCR_TID2) {
5941                     return CP_ACCESS_TRAP_EL2;
5942                 }
5943             }
5944         } else if (hcr & HCR_TID2) {
5945             return CP_ACCESS_TRAP_EL2;
5946         }
5947     }
5948 
5949     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
5950         return CP_ACCESS_TRAP_EL2;
5951     }
5952 
5953     return CP_ACCESS_OK;
5954 }
5955 
5956 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5957                         uint64_t value)
5958 {
5959     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5960      * read via a bit in OSLSR_EL1.
5961      */
5962     int oslock;
5963 
5964     if (ri->state == ARM_CP_STATE_AA32) {
5965         oslock = (value == 0xC5ACCE55);
5966     } else {
5967         oslock = value & 1;
5968     }
5969 
5970     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5971 }
5972 
5973 static const ARMCPRegInfo debug_cp_reginfo[] = {
5974     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5975      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5976      * unlike DBGDRAR it is never accessible from EL0.
5977      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5978      * accessor.
5979      */
5980     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5981       .access = PL0_R, .accessfn = access_tdra,
5982       .type = ARM_CP_CONST, .resetvalue = 0 },
5983     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5984       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5985       .access = PL1_R, .accessfn = access_tdra,
5986       .type = ARM_CP_CONST, .resetvalue = 0 },
5987     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5988       .access = PL0_R, .accessfn = access_tdra,
5989       .type = ARM_CP_CONST, .resetvalue = 0 },
5990     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5991     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5992       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5993       .access = PL1_RW, .accessfn = access_tda,
5994       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5995       .resetvalue = 0 },
5996     /*
5997      * MDCCSR_EL0[30:29] map to EDSCR[30:29].  Simply RAZ as the external
5998      * Debug Communication Channel is not implemented.
5999      */
6000     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_AA64,
6001       .opc0 = 2, .opc1 = 3, .crn = 0, .crm = 1, .opc2 = 0,
6002       .access = PL0_R, .accessfn = access_tda,
6003       .type = ARM_CP_CONST, .resetvalue = 0 },
6004     /*
6005      * DBGDSCRint[15,12,5:2] map to MDSCR_EL1[15,12,5:2].  Map all bits as
6006      * it is unlikely a guest will care.
6007      * We don't implement the configurable EL0 access.
6008      */
6009     { .name = "DBGDSCRint", .state = ARM_CP_STATE_AA32,
6010       .cp = 14, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6011       .type = ARM_CP_ALIAS,
6012       .access = PL1_R, .accessfn = access_tda,
6013       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
6014     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
6015       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
6016       .access = PL1_W, .type = ARM_CP_NO_RAW,
6017       .accessfn = access_tdosa,
6018       .writefn = oslar_write },
6019     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
6020       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
6021       .access = PL1_R, .resetvalue = 10,
6022       .accessfn = access_tdosa,
6023       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6024     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6025     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6026       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6027       .access = PL1_RW, .accessfn = access_tdosa,
6028       .type = ARM_CP_NOP },
6029     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6030      * implement vector catch debug events yet.
6031      */
6032     { .name = "DBGVCR",
6033       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6034       .access = PL1_RW, .accessfn = access_tda,
6035       .type = ARM_CP_NOP },
6036     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6037      * to save and restore a 32-bit guest's DBGVCR)
6038      */
6039     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6040       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6041       .access = PL2_RW, .accessfn = access_tda,
6042       .type = ARM_CP_NOP | ARM_CP_EL3_NO_EL2_KEEP },
6043     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6044      * Channel but Linux may try to access this register. The 32-bit
6045      * alias is DBGDCCINT.
6046      */
6047     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6048       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6049       .access = PL1_RW, .accessfn = access_tda,
6050       .type = ARM_CP_NOP },
6051 };
6052 
6053 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6054     /* 64 bit access versions of the (dummy) debug registers */
6055     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6056       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6057     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6058       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6059 };
6060 
6061 /*
6062  * Check for traps to RAS registers, which are controlled
6063  * by HCR_EL2.TERR and SCR_EL3.TERR.
6064  */
6065 static CPAccessResult access_terr(CPUARMState *env, const ARMCPRegInfo *ri,
6066                                   bool isread)
6067 {
6068     int el = arm_current_el(env);
6069 
6070     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TERR)) {
6071         return CP_ACCESS_TRAP_EL2;
6072     }
6073     if (el < 3 && (env->cp15.scr_el3 & SCR_TERR)) {
6074         return CP_ACCESS_TRAP_EL3;
6075     }
6076     return CP_ACCESS_OK;
6077 }
6078 
6079 static uint64_t disr_read(CPUARMState *env, const ARMCPRegInfo *ri)
6080 {
6081     int el = arm_current_el(env);
6082 
6083     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_AMO)) {
6084         return env->cp15.vdisr_el2;
6085     }
6086     if (el < 3 && (env->cp15.scr_el3 & SCR_EA)) {
6087         return 0; /* RAZ/WI */
6088     }
6089     return env->cp15.disr_el1;
6090 }
6091 
6092 static void disr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
6093 {
6094     int el = arm_current_el(env);
6095 
6096     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_AMO)) {
6097         env->cp15.vdisr_el2 = val;
6098         return;
6099     }
6100     if (el < 3 && (env->cp15.scr_el3 & SCR_EA)) {
6101         return; /* RAZ/WI */
6102     }
6103     env->cp15.disr_el1 = val;
6104 }
6105 
6106 /*
6107  * Minimal RAS implementation with no Error Records.
6108  * Which means that all of the Error Record registers:
6109  *   ERXADDR_EL1
6110  *   ERXCTLR_EL1
6111  *   ERXFR_EL1
6112  *   ERXMISC0_EL1
6113  *   ERXMISC1_EL1
6114  *   ERXMISC2_EL1
6115  *   ERXMISC3_EL1
6116  *   ERXPFGCDN_EL1  (RASv1p1)
6117  *   ERXPFGCTL_EL1  (RASv1p1)
6118  *   ERXPFGF_EL1    (RASv1p1)
6119  *   ERXSTATUS_EL1
6120  * and
6121  *   ERRSELR_EL1
6122  * may generate UNDEFINED, which is the effect we get by not
6123  * listing them at all.
6124  */
6125 static const ARMCPRegInfo minimal_ras_reginfo[] = {
6126     { .name = "DISR_EL1", .state = ARM_CP_STATE_BOTH,
6127       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 1,
6128       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.disr_el1),
6129       .readfn = disr_read, .writefn = disr_write, .raw_writefn = raw_write },
6130     { .name = "ERRIDR_EL1", .state = ARM_CP_STATE_BOTH,
6131       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 3, .opc2 = 0,
6132       .access = PL1_R, .accessfn = access_terr,
6133       .type = ARM_CP_CONST, .resetvalue = 0 },
6134     { .name = "VDISR_EL2", .state = ARM_CP_STATE_BOTH,
6135       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 1, .opc2 = 1,
6136       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.vdisr_el2) },
6137     { .name = "VSESR_EL2", .state = ARM_CP_STATE_BOTH,
6138       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 3,
6139       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.vsesr_el2) },
6140 };
6141 
6142 /* Return the exception level to which exceptions should be taken
6143  * via SVEAccessTrap.  If an exception should be routed through
6144  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6145  * take care of raising that exception.
6146  * C.f. the ARM pseudocode function CheckSVEEnabled.
6147  */
6148 int sve_exception_el(CPUARMState *env, int el)
6149 {
6150 #ifndef CONFIG_USER_ONLY
6151     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6152 
6153     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6154         switch (FIELD_EX64(env->cp15.cpacr_el1, CPACR_EL1, ZEN)) {
6155         case 1:
6156             if (el != 0) {
6157                 break;
6158             }
6159             /* fall through */
6160         case 0:
6161         case 2:
6162             /* route_to_el2 */
6163             return hcr_el2 & HCR_TGE ? 2 : 1;
6164         }
6165 
6166         /* Check CPACR.FPEN.  */
6167         switch (FIELD_EX64(env->cp15.cpacr_el1, CPACR_EL1, FPEN)) {
6168         case 1:
6169             if (el != 0) {
6170                 break;
6171             }
6172             /* fall through */
6173         case 0:
6174         case 2:
6175             return 0;
6176         }
6177     }
6178 
6179     /*
6180      * CPTR_EL2 changes format with HCR_EL2.E2H (regardless of TGE).
6181      */
6182     if (el <= 2) {
6183         if (hcr_el2 & HCR_E2H) {
6184             switch (FIELD_EX64(env->cp15.cptr_el[2], CPTR_EL2, ZEN)) {
6185             case 1:
6186                 if (el != 0 || !(hcr_el2 & HCR_TGE)) {
6187                     break;
6188                 }
6189                 /* fall through */
6190             case 0:
6191             case 2:
6192                 return 2;
6193             }
6194 
6195             switch (FIELD_EX32(env->cp15.cptr_el[2], CPTR_EL2, FPEN)) {
6196             case 1:
6197                 if (el == 2 || !(hcr_el2 & HCR_TGE)) {
6198                     break;
6199                 }
6200                 /* fall through */
6201             case 0:
6202             case 2:
6203                 return 0;
6204             }
6205         } else if (arm_is_el2_enabled(env)) {
6206             if (FIELD_EX64(env->cp15.cptr_el[2], CPTR_EL2, TZ)) {
6207                 return 2;
6208             }
6209             if (FIELD_EX64(env->cp15.cptr_el[2], CPTR_EL2, TFP)) {
6210                 return 0;
6211             }
6212         }
6213     }
6214 
6215     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6216     if (arm_feature(env, ARM_FEATURE_EL3)
6217         && !FIELD_EX64(env->cp15.cptr_el[3], CPTR_EL3, EZ)) {
6218         return 3;
6219     }
6220 #endif
6221     return 0;
6222 }
6223 
6224 uint32_t aarch64_sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6225 {
6226     uint32_t end_len;
6227 
6228     start_len = MIN(start_len, ARM_MAX_VQ - 1);
6229     end_len = start_len;
6230 
6231     if (!test_bit(start_len, cpu->sve_vq_map)) {
6232         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6233         assert(end_len < start_len);
6234     }
6235     return end_len;
6236 }
6237 
6238 /*
6239  * Given that SVE is enabled, return the vector length for EL.
6240  */
6241 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6242 {
6243     ARMCPU *cpu = env_archcpu(env);
6244     uint32_t zcr_len = cpu->sve_max_vq - 1;
6245 
6246     if (el <= 1 &&
6247         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6248         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6249     }
6250     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6251         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6252     }
6253     if (arm_feature(env, ARM_FEATURE_EL3)) {
6254         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6255     }
6256 
6257     return aarch64_sve_zcr_get_valid_len(cpu, zcr_len);
6258 }
6259 
6260 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6261                       uint64_t value)
6262 {
6263     int cur_el = arm_current_el(env);
6264     int old_len = sve_zcr_len_for_el(env, cur_el);
6265     int new_len;
6266 
6267     /* Bits other than [3:0] are RAZ/WI.  */
6268     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6269     raw_write(env, ri, value & 0xf);
6270 
6271     /*
6272      * Because we arrived here, we know both FP and SVE are enabled;
6273      * otherwise we would have trapped access to the ZCR_ELn register.
6274      */
6275     new_len = sve_zcr_len_for_el(env, cur_el);
6276     if (new_len < old_len) {
6277         aarch64_sve_narrow_vq(env, new_len + 1);
6278     }
6279 }
6280 
6281 static const ARMCPRegInfo zcr_reginfo[] = {
6282     { .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6283       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6284       .access = PL1_RW, .type = ARM_CP_SVE,
6285       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6286       .writefn = zcr_write, .raw_writefn = raw_write },
6287     { .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6288       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6289       .access = PL2_RW, .type = ARM_CP_SVE,
6290       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6291       .writefn = zcr_write, .raw_writefn = raw_write },
6292     { .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6293       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6294       .access = PL3_RW, .type = ARM_CP_SVE,
6295       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6296       .writefn = zcr_write, .raw_writefn = raw_write },
6297 };
6298 
6299 void hw_watchpoint_update(ARMCPU *cpu, int n)
6300 {
6301     CPUARMState *env = &cpu->env;
6302     vaddr len = 0;
6303     vaddr wvr = env->cp15.dbgwvr[n];
6304     uint64_t wcr = env->cp15.dbgwcr[n];
6305     int mask;
6306     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6307 
6308     if (env->cpu_watchpoint[n]) {
6309         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6310         env->cpu_watchpoint[n] = NULL;
6311     }
6312 
6313     if (!FIELD_EX64(wcr, DBGWCR, E)) {
6314         /* E bit clear : watchpoint disabled */
6315         return;
6316     }
6317 
6318     switch (FIELD_EX64(wcr, DBGWCR, LSC)) {
6319     case 0:
6320         /* LSC 00 is reserved and must behave as if the wp is disabled */
6321         return;
6322     case 1:
6323         flags |= BP_MEM_READ;
6324         break;
6325     case 2:
6326         flags |= BP_MEM_WRITE;
6327         break;
6328     case 3:
6329         flags |= BP_MEM_ACCESS;
6330         break;
6331     }
6332 
6333     /* Attempts to use both MASK and BAS fields simultaneously are
6334      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6335      * thus generating a watchpoint for every byte in the masked region.
6336      */
6337     mask = FIELD_EX64(wcr, DBGWCR, MASK);
6338     if (mask == 1 || mask == 2) {
6339         /* Reserved values of MASK; we must act as if the mask value was
6340          * some non-reserved value, or as if the watchpoint were disabled.
6341          * We choose the latter.
6342          */
6343         return;
6344     } else if (mask) {
6345         /* Watchpoint covers an aligned area up to 2GB in size */
6346         len = 1ULL << mask;
6347         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6348          * whether the watchpoint fires when the unmasked bits match; we opt
6349          * to generate the exceptions.
6350          */
6351         wvr &= ~(len - 1);
6352     } else {
6353         /* Watchpoint covers bytes defined by the byte address select bits */
6354         int bas = FIELD_EX64(wcr, DBGWCR, BAS);
6355         int basstart;
6356 
6357         if (extract64(wvr, 2, 1)) {
6358             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6359              * ignored, and BAS[3:0] define which bytes to watch.
6360              */
6361             bas &= 0xf;
6362         }
6363 
6364         if (bas == 0) {
6365             /* This must act as if the watchpoint is disabled */
6366             return;
6367         }
6368 
6369         /* The BAS bits are supposed to be programmed to indicate a contiguous
6370          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6371          * we fire for each byte in the word/doubleword addressed by the WVR.
6372          * We choose to ignore any non-zero bits after the first range of 1s.
6373          */
6374         basstart = ctz32(bas);
6375         len = cto32(bas >> basstart);
6376         wvr += basstart;
6377     }
6378 
6379     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6380                           &env->cpu_watchpoint[n]);
6381 }
6382 
6383 void hw_watchpoint_update_all(ARMCPU *cpu)
6384 {
6385     int i;
6386     CPUARMState *env = &cpu->env;
6387 
6388     /* Completely clear out existing QEMU watchpoints and our array, to
6389      * avoid possible stale entries following migration load.
6390      */
6391     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6392     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6393 
6394     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6395         hw_watchpoint_update(cpu, i);
6396     }
6397 }
6398 
6399 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6400                          uint64_t value)
6401 {
6402     ARMCPU *cpu = env_archcpu(env);
6403     int i = ri->crm;
6404 
6405     /*
6406      * Bits [1:0] are RES0.
6407      *
6408      * It is IMPLEMENTATION DEFINED whether [63:49] ([63:53] with FEAT_LVA)
6409      * are hardwired to the value of bit [48] ([52] with FEAT_LVA), or if
6410      * they contain the value written.  It is CONSTRAINED UNPREDICTABLE
6411      * whether the RESS bits are ignored when comparing an address.
6412      *
6413      * Therefore we are allowed to compare the entire register, which lets
6414      * us avoid considering whether or not FEAT_LVA is actually enabled.
6415      */
6416     value &= ~3ULL;
6417 
6418     raw_write(env, ri, value);
6419     hw_watchpoint_update(cpu, i);
6420 }
6421 
6422 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6423                          uint64_t value)
6424 {
6425     ARMCPU *cpu = env_archcpu(env);
6426     int i = ri->crm;
6427 
6428     raw_write(env, ri, value);
6429     hw_watchpoint_update(cpu, i);
6430 }
6431 
6432 void hw_breakpoint_update(ARMCPU *cpu, int n)
6433 {
6434     CPUARMState *env = &cpu->env;
6435     uint64_t bvr = env->cp15.dbgbvr[n];
6436     uint64_t bcr = env->cp15.dbgbcr[n];
6437     vaddr addr;
6438     int bt;
6439     int flags = BP_CPU;
6440 
6441     if (env->cpu_breakpoint[n]) {
6442         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6443         env->cpu_breakpoint[n] = NULL;
6444     }
6445 
6446     if (!extract64(bcr, 0, 1)) {
6447         /* E bit clear : watchpoint disabled */
6448         return;
6449     }
6450 
6451     bt = extract64(bcr, 20, 4);
6452 
6453     switch (bt) {
6454     case 4: /* unlinked address mismatch (reserved if AArch64) */
6455     case 5: /* linked address mismatch (reserved if AArch64) */
6456         qemu_log_mask(LOG_UNIMP,
6457                       "arm: address mismatch breakpoint types not implemented\n");
6458         return;
6459     case 0: /* unlinked address match */
6460     case 1: /* linked address match */
6461     {
6462         /*
6463          * Bits [1:0] are RES0.
6464          *
6465          * It is IMPLEMENTATION DEFINED whether bits [63:49]
6466          * ([63:53] for FEAT_LVA) are hardwired to a copy of the sign bit
6467          * of the VA field ([48] or [52] for FEAT_LVA), or whether the
6468          * value is read as written.  It is CONSTRAINED UNPREDICTABLE
6469          * whether the RESS bits are ignored when comparing an address.
6470          * Therefore we are allowed to compare the entire register, which
6471          * lets us avoid considering whether FEAT_LVA is actually enabled.
6472          *
6473          * The BAS field is used to allow setting breakpoints on 16-bit
6474          * wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6475          * a bp will fire if the addresses covered by the bp and the addresses
6476          * covered by the insn overlap but the insn doesn't start at the
6477          * start of the bp address range. We choose to require the insn and
6478          * the bp to have the same address. The constraints on writing to
6479          * BAS enforced in dbgbcr_write mean we have only four cases:
6480          *  0b0000  => no breakpoint
6481          *  0b0011  => breakpoint on addr
6482          *  0b1100  => breakpoint on addr + 2
6483          *  0b1111  => breakpoint on addr
6484          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6485          */
6486         int bas = extract64(bcr, 5, 4);
6487         addr = bvr & ~3ULL;
6488         if (bas == 0) {
6489             return;
6490         }
6491         if (bas == 0xc) {
6492             addr += 2;
6493         }
6494         break;
6495     }
6496     case 2: /* unlinked context ID match */
6497     case 8: /* unlinked VMID match (reserved if no EL2) */
6498     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6499         qemu_log_mask(LOG_UNIMP,
6500                       "arm: unlinked context breakpoint types not implemented\n");
6501         return;
6502     case 9: /* linked VMID match (reserved if no EL2) */
6503     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6504     case 3: /* linked context ID match */
6505     default:
6506         /* We must generate no events for Linked context matches (unless
6507          * they are linked to by some other bp/wp, which is handled in
6508          * updates for the linking bp/wp). We choose to also generate no events
6509          * for reserved values.
6510          */
6511         return;
6512     }
6513 
6514     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6515 }
6516 
6517 void hw_breakpoint_update_all(ARMCPU *cpu)
6518 {
6519     int i;
6520     CPUARMState *env = &cpu->env;
6521 
6522     /* Completely clear out existing QEMU breakpoints and our array, to
6523      * avoid possible stale entries following migration load.
6524      */
6525     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6526     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6527 
6528     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6529         hw_breakpoint_update(cpu, i);
6530     }
6531 }
6532 
6533 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6534                          uint64_t value)
6535 {
6536     ARMCPU *cpu = env_archcpu(env);
6537     int i = ri->crm;
6538 
6539     raw_write(env, ri, value);
6540     hw_breakpoint_update(cpu, i);
6541 }
6542 
6543 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6544                          uint64_t value)
6545 {
6546     ARMCPU *cpu = env_archcpu(env);
6547     int i = ri->crm;
6548 
6549     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6550      * copy of BAS[0].
6551      */
6552     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6553     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6554 
6555     raw_write(env, ri, value);
6556     hw_breakpoint_update(cpu, i);
6557 }
6558 
6559 static void define_debug_regs(ARMCPU *cpu)
6560 {
6561     /* Define v7 and v8 architectural debug registers.
6562      * These are just dummy implementations for now.
6563      */
6564     int i;
6565     int wrps, brps, ctx_cmps;
6566 
6567     /*
6568      * The Arm ARM says DBGDIDR is optional and deprecated if EL1 cannot
6569      * use AArch32.  Given that bit 15 is RES1, if the value is 0 then
6570      * the register must not exist for this cpu.
6571      */
6572     if (cpu->isar.dbgdidr != 0) {
6573         ARMCPRegInfo dbgdidr = {
6574             .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0,
6575             .opc1 = 0, .opc2 = 0,
6576             .access = PL0_R, .accessfn = access_tda,
6577             .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6578         };
6579         define_one_arm_cp_reg(cpu, &dbgdidr);
6580     }
6581 
6582     brps = arm_num_brps(cpu);
6583     wrps = arm_num_wrps(cpu);
6584     ctx_cmps = arm_num_ctx_cmps(cpu);
6585 
6586     assert(ctx_cmps <= brps);
6587 
6588     define_arm_cp_regs(cpu, debug_cp_reginfo);
6589 
6590     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6591         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6592     }
6593 
6594     for (i = 0; i < brps; i++) {
6595         char *dbgbvr_el1_name = g_strdup_printf("DBGBVR%d_EL1", i);
6596         char *dbgbcr_el1_name = g_strdup_printf("DBGBCR%d_EL1", i);
6597         ARMCPRegInfo dbgregs[] = {
6598             { .name = dbgbvr_el1_name, .state = ARM_CP_STATE_BOTH,
6599               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6600               .access = PL1_RW, .accessfn = access_tda,
6601               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6602               .writefn = dbgbvr_write, .raw_writefn = raw_write
6603             },
6604             { .name = dbgbcr_el1_name, .state = ARM_CP_STATE_BOTH,
6605               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6606               .access = PL1_RW, .accessfn = access_tda,
6607               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6608               .writefn = dbgbcr_write, .raw_writefn = raw_write
6609             },
6610         };
6611         define_arm_cp_regs(cpu, dbgregs);
6612         g_free(dbgbvr_el1_name);
6613         g_free(dbgbcr_el1_name);
6614     }
6615 
6616     for (i = 0; i < wrps; i++) {
6617         char *dbgwvr_el1_name = g_strdup_printf("DBGWVR%d_EL1", i);
6618         char *dbgwcr_el1_name = g_strdup_printf("DBGWCR%d_EL1", i);
6619         ARMCPRegInfo dbgregs[] = {
6620             { .name = dbgwvr_el1_name, .state = ARM_CP_STATE_BOTH,
6621               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6622               .access = PL1_RW, .accessfn = access_tda,
6623               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6624               .writefn = dbgwvr_write, .raw_writefn = raw_write
6625             },
6626             { .name = dbgwcr_el1_name, .state = ARM_CP_STATE_BOTH,
6627               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6628               .access = PL1_RW, .accessfn = access_tda,
6629               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6630               .writefn = dbgwcr_write, .raw_writefn = raw_write
6631             },
6632         };
6633         define_arm_cp_regs(cpu, dbgregs);
6634         g_free(dbgwvr_el1_name);
6635         g_free(dbgwcr_el1_name);
6636     }
6637 }
6638 
6639 static void define_pmu_regs(ARMCPU *cpu)
6640 {
6641     /*
6642      * v7 performance monitor control register: same implementor
6643      * field as main ID register, and we implement four counters in
6644      * addition to the cycle count register.
6645      */
6646     unsigned int i, pmcrn = pmu_num_counters(&cpu->env);
6647     ARMCPRegInfo pmcr = {
6648         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6649         .access = PL0_RW,
6650         .type = ARM_CP_IO | ARM_CP_ALIAS,
6651         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6652         .accessfn = pmreg_access, .writefn = pmcr_write,
6653         .raw_writefn = raw_write,
6654     };
6655     ARMCPRegInfo pmcr64 = {
6656         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6657         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6658         .access = PL0_RW, .accessfn = pmreg_access,
6659         .type = ARM_CP_IO,
6660         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6661         .resetvalue = cpu->isar.reset_pmcr_el0,
6662         .writefn = pmcr_write, .raw_writefn = raw_write,
6663     };
6664 
6665     define_one_arm_cp_reg(cpu, &pmcr);
6666     define_one_arm_cp_reg(cpu, &pmcr64);
6667     for (i = 0; i < pmcrn; i++) {
6668         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6669         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6670         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6671         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6672         ARMCPRegInfo pmev_regs[] = {
6673             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6674               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6675               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6676               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6677               .accessfn = pmreg_access_xevcntr },
6678             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6679               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6680               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access_xevcntr,
6681               .type = ARM_CP_IO,
6682               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6683               .raw_readfn = pmevcntr_rawread,
6684               .raw_writefn = pmevcntr_rawwrite },
6685             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6686               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6687               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6688               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6689               .accessfn = pmreg_access },
6690             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6691               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6692               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6693               .type = ARM_CP_IO,
6694               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6695               .raw_writefn = pmevtyper_rawwrite },
6696         };
6697         define_arm_cp_regs(cpu, pmev_regs);
6698         g_free(pmevcntr_name);
6699         g_free(pmevcntr_el0_name);
6700         g_free(pmevtyper_name);
6701         g_free(pmevtyper_el0_name);
6702     }
6703     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6704         ARMCPRegInfo v81_pmu_regs[] = {
6705             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6706               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6707               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6708               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6709             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6710               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6711               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6712               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6713         };
6714         define_arm_cp_regs(cpu, v81_pmu_regs);
6715     }
6716     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6717         static const ARMCPRegInfo v84_pmmir = {
6718             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6719             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6720             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6721             .resetvalue = 0
6722         };
6723         define_one_arm_cp_reg(cpu, &v84_pmmir);
6724     }
6725 }
6726 
6727 /* We don't know until after realize whether there's a GICv3
6728  * attached, and that is what registers the gicv3 sysregs.
6729  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6730  * at runtime.
6731  */
6732 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6733 {
6734     ARMCPU *cpu = env_archcpu(env);
6735     uint64_t pfr1 = cpu->isar.id_pfr1;
6736 
6737     if (env->gicv3state) {
6738         pfr1 |= 1 << 28;
6739     }
6740     return pfr1;
6741 }
6742 
6743 #ifndef CONFIG_USER_ONLY
6744 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6745 {
6746     ARMCPU *cpu = env_archcpu(env);
6747     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6748 
6749     if (env->gicv3state) {
6750         pfr0 |= 1 << 24;
6751     }
6752     return pfr0;
6753 }
6754 #endif
6755 
6756 /* Shared logic between LORID and the rest of the LOR* registers.
6757  * Secure state exclusion has already been dealt with.
6758  */
6759 static CPAccessResult access_lor_ns(CPUARMState *env,
6760                                     const ARMCPRegInfo *ri, bool isread)
6761 {
6762     int el = arm_current_el(env);
6763 
6764     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6765         return CP_ACCESS_TRAP_EL2;
6766     }
6767     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6768         return CP_ACCESS_TRAP_EL3;
6769     }
6770     return CP_ACCESS_OK;
6771 }
6772 
6773 static CPAccessResult access_lor_other(CPUARMState *env,
6774                                        const ARMCPRegInfo *ri, bool isread)
6775 {
6776     if (arm_is_secure_below_el3(env)) {
6777         /* Access denied in secure mode.  */
6778         return CP_ACCESS_TRAP;
6779     }
6780     return access_lor_ns(env, ri, isread);
6781 }
6782 
6783 /*
6784  * A trivial implementation of ARMv8.1-LOR leaves all of these
6785  * registers fixed at 0, which indicates that there are zero
6786  * supported Limited Ordering regions.
6787  */
6788 static const ARMCPRegInfo lor_reginfo[] = {
6789     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6790       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6791       .access = PL1_RW, .accessfn = access_lor_other,
6792       .type = ARM_CP_CONST, .resetvalue = 0 },
6793     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6794       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6795       .access = PL1_RW, .accessfn = access_lor_other,
6796       .type = ARM_CP_CONST, .resetvalue = 0 },
6797     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6798       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6799       .access = PL1_RW, .accessfn = access_lor_other,
6800       .type = ARM_CP_CONST, .resetvalue = 0 },
6801     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6802       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6803       .access = PL1_RW, .accessfn = access_lor_other,
6804       .type = ARM_CP_CONST, .resetvalue = 0 },
6805     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6806       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6807       .access = PL1_R, .accessfn = access_lor_ns,
6808       .type = ARM_CP_CONST, .resetvalue = 0 },
6809 };
6810 
6811 #ifdef TARGET_AARCH64
6812 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6813                                    bool isread)
6814 {
6815     int el = arm_current_el(env);
6816 
6817     if (el < 2 &&
6818         arm_is_el2_enabled(env) &&
6819         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6820         return CP_ACCESS_TRAP_EL2;
6821     }
6822     if (el < 3 &&
6823         arm_feature(env, ARM_FEATURE_EL3) &&
6824         !(env->cp15.scr_el3 & SCR_APK)) {
6825         return CP_ACCESS_TRAP_EL3;
6826     }
6827     return CP_ACCESS_OK;
6828 }
6829 
6830 static const ARMCPRegInfo pauth_reginfo[] = {
6831     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6832       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6833       .access = PL1_RW, .accessfn = access_pauth,
6834       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6835     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6836       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6837       .access = PL1_RW, .accessfn = access_pauth,
6838       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6839     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6840       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6841       .access = PL1_RW, .accessfn = access_pauth,
6842       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6843     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6844       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6845       .access = PL1_RW, .accessfn = access_pauth,
6846       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6847     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6848       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6849       .access = PL1_RW, .accessfn = access_pauth,
6850       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6851     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6852       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6853       .access = PL1_RW, .accessfn = access_pauth,
6854       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6855     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6856       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6857       .access = PL1_RW, .accessfn = access_pauth,
6858       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6859     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6860       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6861       .access = PL1_RW, .accessfn = access_pauth,
6862       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6863     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6864       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6865       .access = PL1_RW, .accessfn = access_pauth,
6866       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6867     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6868       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6869       .access = PL1_RW, .accessfn = access_pauth,
6870       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6871 };
6872 
6873 static const ARMCPRegInfo tlbirange_reginfo[] = {
6874     { .name = "TLBI_RVAE1IS", .state = ARM_CP_STATE_AA64,
6875       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 1,
6876       .access = PL1_W, .type = ARM_CP_NO_RAW,
6877       .writefn = tlbi_aa64_rvae1is_write },
6878     { .name = "TLBI_RVAAE1IS", .state = ARM_CP_STATE_AA64,
6879       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 3,
6880       .access = PL1_W, .type = ARM_CP_NO_RAW,
6881       .writefn = tlbi_aa64_rvae1is_write },
6882    { .name = "TLBI_RVALE1IS", .state = ARM_CP_STATE_AA64,
6883       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 5,
6884       .access = PL1_W, .type = ARM_CP_NO_RAW,
6885       .writefn = tlbi_aa64_rvae1is_write },
6886     { .name = "TLBI_RVAALE1IS", .state = ARM_CP_STATE_AA64,
6887       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 7,
6888       .access = PL1_W, .type = ARM_CP_NO_RAW,
6889       .writefn = tlbi_aa64_rvae1is_write },
6890     { .name = "TLBI_RVAE1OS", .state = ARM_CP_STATE_AA64,
6891       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
6892       .access = PL1_W, .type = ARM_CP_NO_RAW,
6893       .writefn = tlbi_aa64_rvae1is_write },
6894     { .name = "TLBI_RVAAE1OS", .state = ARM_CP_STATE_AA64,
6895       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 3,
6896       .access = PL1_W, .type = ARM_CP_NO_RAW,
6897       .writefn = tlbi_aa64_rvae1is_write },
6898    { .name = "TLBI_RVALE1OS", .state = ARM_CP_STATE_AA64,
6899       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 5,
6900       .access = PL1_W, .type = ARM_CP_NO_RAW,
6901       .writefn = tlbi_aa64_rvae1is_write },
6902     { .name = "TLBI_RVAALE1OS", .state = ARM_CP_STATE_AA64,
6903       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 7,
6904       .access = PL1_W, .type = ARM_CP_NO_RAW,
6905       .writefn = tlbi_aa64_rvae1is_write },
6906     { .name = "TLBI_RVAE1", .state = ARM_CP_STATE_AA64,
6907       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
6908       .access = PL1_W, .type = ARM_CP_NO_RAW,
6909       .writefn = tlbi_aa64_rvae1_write },
6910     { .name = "TLBI_RVAAE1", .state = ARM_CP_STATE_AA64,
6911       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 3,
6912       .access = PL1_W, .type = ARM_CP_NO_RAW,
6913       .writefn = tlbi_aa64_rvae1_write },
6914    { .name = "TLBI_RVALE1", .state = ARM_CP_STATE_AA64,
6915       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 5,
6916       .access = PL1_W, .type = ARM_CP_NO_RAW,
6917       .writefn = tlbi_aa64_rvae1_write },
6918     { .name = "TLBI_RVAALE1", .state = ARM_CP_STATE_AA64,
6919       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 7,
6920       .access = PL1_W, .type = ARM_CP_NO_RAW,
6921       .writefn = tlbi_aa64_rvae1_write },
6922     { .name = "TLBI_RIPAS2E1IS", .state = ARM_CP_STATE_AA64,
6923       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 2,
6924       .access = PL2_W, .type = ARM_CP_NOP },
6925     { .name = "TLBI_RIPAS2LE1IS", .state = ARM_CP_STATE_AA64,
6926       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 6,
6927       .access = PL2_W, .type = ARM_CP_NOP },
6928     { .name = "TLBI_RVAE2IS", .state = ARM_CP_STATE_AA64,
6929       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 1,
6930       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6931       .writefn = tlbi_aa64_rvae2is_write },
6932    { .name = "TLBI_RVALE2IS", .state = ARM_CP_STATE_AA64,
6933       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 5,
6934       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6935       .writefn = tlbi_aa64_rvae2is_write },
6936     { .name = "TLBI_RIPAS2E1", .state = ARM_CP_STATE_AA64,
6937       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 2,
6938       .access = PL2_W, .type = ARM_CP_NOP },
6939    { .name = "TLBI_RIPAS2LE1", .state = ARM_CP_STATE_AA64,
6940       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 6,
6941       .access = PL2_W, .type = ARM_CP_NOP },
6942    { .name = "TLBI_RVAE2OS", .state = ARM_CP_STATE_AA64,
6943       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 1,
6944       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6945       .writefn = tlbi_aa64_rvae2is_write },
6946    { .name = "TLBI_RVALE2OS", .state = ARM_CP_STATE_AA64,
6947       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 5,
6948       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6949       .writefn = tlbi_aa64_rvae2is_write },
6950     { .name = "TLBI_RVAE2", .state = ARM_CP_STATE_AA64,
6951       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 1,
6952       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6953       .writefn = tlbi_aa64_rvae2_write },
6954    { .name = "TLBI_RVALE2", .state = ARM_CP_STATE_AA64,
6955       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 5,
6956       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6957       .writefn = tlbi_aa64_rvae2_write },
6958    { .name = "TLBI_RVAE3IS", .state = ARM_CP_STATE_AA64,
6959       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 1,
6960       .access = PL3_W, .type = ARM_CP_NO_RAW,
6961       .writefn = tlbi_aa64_rvae3is_write },
6962    { .name = "TLBI_RVALE3IS", .state = ARM_CP_STATE_AA64,
6963       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 5,
6964       .access = PL3_W, .type = ARM_CP_NO_RAW,
6965       .writefn = tlbi_aa64_rvae3is_write },
6966    { .name = "TLBI_RVAE3OS", .state = ARM_CP_STATE_AA64,
6967       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 1,
6968       .access = PL3_W, .type = ARM_CP_NO_RAW,
6969       .writefn = tlbi_aa64_rvae3is_write },
6970    { .name = "TLBI_RVALE3OS", .state = ARM_CP_STATE_AA64,
6971       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 5,
6972       .access = PL3_W, .type = ARM_CP_NO_RAW,
6973       .writefn = tlbi_aa64_rvae3is_write },
6974    { .name = "TLBI_RVAE3", .state = ARM_CP_STATE_AA64,
6975       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 1,
6976       .access = PL3_W, .type = ARM_CP_NO_RAW,
6977       .writefn = tlbi_aa64_rvae3_write },
6978    { .name = "TLBI_RVALE3", .state = ARM_CP_STATE_AA64,
6979       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 5,
6980       .access = PL3_W, .type = ARM_CP_NO_RAW,
6981       .writefn = tlbi_aa64_rvae3_write },
6982 };
6983 
6984 static const ARMCPRegInfo tlbios_reginfo[] = {
6985     { .name = "TLBI_VMALLE1OS", .state = ARM_CP_STATE_AA64,
6986       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 0,
6987       .access = PL1_W, .type = ARM_CP_NO_RAW,
6988       .writefn = tlbi_aa64_vmalle1is_write },
6989     { .name = "TLBI_VAE1OS", .state = ARM_CP_STATE_AA64,
6990       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 1,
6991       .access = PL1_W, .type = ARM_CP_NO_RAW,
6992       .writefn = tlbi_aa64_vae1is_write },
6993     { .name = "TLBI_ASIDE1OS", .state = ARM_CP_STATE_AA64,
6994       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 2,
6995       .access = PL1_W, .type = ARM_CP_NO_RAW,
6996       .writefn = tlbi_aa64_vmalle1is_write },
6997     { .name = "TLBI_VAAE1OS", .state = ARM_CP_STATE_AA64,
6998       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 3,
6999       .access = PL1_W, .type = ARM_CP_NO_RAW,
7000       .writefn = tlbi_aa64_vae1is_write },
7001     { .name = "TLBI_VALE1OS", .state = ARM_CP_STATE_AA64,
7002       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 5,
7003       .access = PL1_W, .type = ARM_CP_NO_RAW,
7004       .writefn = tlbi_aa64_vae1is_write },
7005     { .name = "TLBI_VAALE1OS", .state = ARM_CP_STATE_AA64,
7006       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 7,
7007       .access = PL1_W, .type = ARM_CP_NO_RAW,
7008       .writefn = tlbi_aa64_vae1is_write },
7009     { .name = "TLBI_ALLE2OS", .state = ARM_CP_STATE_AA64,
7010       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 0,
7011       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
7012       .writefn = tlbi_aa64_alle2is_write },
7013     { .name = "TLBI_VAE2OS", .state = ARM_CP_STATE_AA64,
7014       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 1,
7015       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
7016       .writefn = tlbi_aa64_vae2is_write },
7017    { .name = "TLBI_ALLE1OS", .state = ARM_CP_STATE_AA64,
7018       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 4,
7019       .access = PL2_W, .type = ARM_CP_NO_RAW,
7020       .writefn = tlbi_aa64_alle1is_write },
7021     { .name = "TLBI_VALE2OS", .state = ARM_CP_STATE_AA64,
7022       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 5,
7023       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
7024       .writefn = tlbi_aa64_vae2is_write },
7025     { .name = "TLBI_VMALLS12E1OS", .state = ARM_CP_STATE_AA64,
7026       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 6,
7027       .access = PL2_W, .type = ARM_CP_NO_RAW,
7028       .writefn = tlbi_aa64_alle1is_write },
7029     { .name = "TLBI_IPAS2E1OS", .state = ARM_CP_STATE_AA64,
7030       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 0,
7031       .access = PL2_W, .type = ARM_CP_NOP },
7032     { .name = "TLBI_RIPAS2E1OS", .state = ARM_CP_STATE_AA64,
7033       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 3,
7034       .access = PL2_W, .type = ARM_CP_NOP },
7035     { .name = "TLBI_IPAS2LE1OS", .state = ARM_CP_STATE_AA64,
7036       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 4,
7037       .access = PL2_W, .type = ARM_CP_NOP },
7038     { .name = "TLBI_RIPAS2LE1OS", .state = ARM_CP_STATE_AA64,
7039       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 7,
7040       .access = PL2_W, .type = ARM_CP_NOP },
7041     { .name = "TLBI_ALLE3OS", .state = ARM_CP_STATE_AA64,
7042       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 0,
7043       .access = PL3_W, .type = ARM_CP_NO_RAW,
7044       .writefn = tlbi_aa64_alle3is_write },
7045     { .name = "TLBI_VAE3OS", .state = ARM_CP_STATE_AA64,
7046       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 1,
7047       .access = PL3_W, .type = ARM_CP_NO_RAW,
7048       .writefn = tlbi_aa64_vae3is_write },
7049     { .name = "TLBI_VALE3OS", .state = ARM_CP_STATE_AA64,
7050       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 5,
7051       .access = PL3_W, .type = ARM_CP_NO_RAW,
7052       .writefn = tlbi_aa64_vae3is_write },
7053 };
7054 
7055 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
7056 {
7057     Error *err = NULL;
7058     uint64_t ret;
7059 
7060     /* Success sets NZCV = 0000.  */
7061     env->NF = env->CF = env->VF = 0, env->ZF = 1;
7062 
7063     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
7064         /*
7065          * ??? Failed, for unknown reasons in the crypto subsystem.
7066          * The best we can do is log the reason and return the
7067          * timed-out indication to the guest.  There is no reason
7068          * we know to expect this failure to be transitory, so the
7069          * guest may well hang retrying the operation.
7070          */
7071         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
7072                       ri->name, error_get_pretty(err));
7073         error_free(err);
7074 
7075         env->ZF = 0; /* NZCF = 0100 */
7076         return 0;
7077     }
7078     return ret;
7079 }
7080 
7081 /* We do not support re-seeding, so the two registers operate the same.  */
7082 static const ARMCPRegInfo rndr_reginfo[] = {
7083     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
7084       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7085       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
7086       .access = PL0_R, .readfn = rndr_readfn },
7087     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
7088       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7089       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
7090       .access = PL0_R, .readfn = rndr_readfn },
7091 };
7092 
7093 #ifndef CONFIG_USER_ONLY
7094 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
7095                           uint64_t value)
7096 {
7097     ARMCPU *cpu = env_archcpu(env);
7098     /* CTR_EL0 System register -> DminLine, bits [19:16] */
7099     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
7100     uint64_t vaddr_in = (uint64_t) value;
7101     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
7102     void *haddr;
7103     int mem_idx = cpu_mmu_index(env, false);
7104 
7105     /* This won't be crossing page boundaries */
7106     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
7107     if (haddr) {
7108 
7109         ram_addr_t offset;
7110         MemoryRegion *mr;
7111 
7112         /* RCU lock is already being held */
7113         mr = memory_region_from_host(haddr, &offset);
7114 
7115         if (mr) {
7116             memory_region_writeback(mr, offset, dline_size);
7117         }
7118     }
7119 }
7120 
7121 static const ARMCPRegInfo dcpop_reg[] = {
7122     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
7123       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
7124       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7125       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7126 };
7127 
7128 static const ARMCPRegInfo dcpodp_reg[] = {
7129     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
7130       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
7131       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7132       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7133 };
7134 #endif /*CONFIG_USER_ONLY*/
7135 
7136 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
7137                                        bool isread)
7138 {
7139     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
7140         return CP_ACCESS_TRAP_EL2;
7141     }
7142 
7143     return CP_ACCESS_OK;
7144 }
7145 
7146 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
7147                                  bool isread)
7148 {
7149     int el = arm_current_el(env);
7150 
7151     if (el < 2 && arm_is_el2_enabled(env)) {
7152         uint64_t hcr = arm_hcr_el2_eff(env);
7153         if (!(hcr & HCR_ATA) && (!(hcr & HCR_E2H) || !(hcr & HCR_TGE))) {
7154             return CP_ACCESS_TRAP_EL2;
7155         }
7156     }
7157     if (el < 3 &&
7158         arm_feature(env, ARM_FEATURE_EL3) &&
7159         !(env->cp15.scr_el3 & SCR_ATA)) {
7160         return CP_ACCESS_TRAP_EL3;
7161     }
7162     return CP_ACCESS_OK;
7163 }
7164 
7165 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
7166 {
7167     return env->pstate & PSTATE_TCO;
7168 }
7169 
7170 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
7171 {
7172     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
7173 }
7174 
7175 static const ARMCPRegInfo mte_reginfo[] = {
7176     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
7177       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
7178       .access = PL1_RW, .accessfn = access_mte,
7179       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
7180     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
7181       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
7182       .access = PL1_RW, .accessfn = access_mte,
7183       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
7184     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
7185       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
7186       .access = PL2_RW, .accessfn = access_mte,
7187       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
7188     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
7189       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
7190       .access = PL3_RW,
7191       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
7192     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
7193       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
7194       .access = PL1_RW, .accessfn = access_mte,
7195       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
7196     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
7197       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
7198       .access = PL1_RW, .accessfn = access_mte,
7199       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
7200     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
7201       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
7202       .access = PL1_R, .accessfn = access_aa64_tid5,
7203       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
7204     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7205       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7206       .type = ARM_CP_NO_RAW,
7207       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
7208     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
7209       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
7210       .type = ARM_CP_NOP, .access = PL1_W,
7211       .accessfn = aa64_cacheop_poc_access },
7212     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
7213       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
7214       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7215     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
7216       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
7217       .type = ARM_CP_NOP, .access = PL1_W,
7218       .accessfn = aa64_cacheop_poc_access },
7219     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
7220       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
7221       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7222     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
7223       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
7224       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7225     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
7226       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
7227       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7228     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
7229       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
7230       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7231     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
7232       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
7233       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7234 };
7235 
7236 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
7237     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7238       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7239       .type = ARM_CP_CONST, .access = PL0_RW, },
7240 };
7241 
7242 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
7243     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
7244       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
7245       .type = ARM_CP_NOP, .access = PL0_W,
7246       .accessfn = aa64_cacheop_poc_access },
7247     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
7248       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
7249       .type = ARM_CP_NOP, .access = PL0_W,
7250       .accessfn = aa64_cacheop_poc_access },
7251     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
7252       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
7253       .type = ARM_CP_NOP, .access = PL0_W,
7254       .accessfn = aa64_cacheop_poc_access },
7255     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
7256       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
7257       .type = ARM_CP_NOP, .access = PL0_W,
7258       .accessfn = aa64_cacheop_poc_access },
7259     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
7260       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
7261       .type = ARM_CP_NOP, .access = PL0_W,
7262       .accessfn = aa64_cacheop_poc_access },
7263     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
7264       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
7265       .type = ARM_CP_NOP, .access = PL0_W,
7266       .accessfn = aa64_cacheop_poc_access },
7267     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
7268       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
7269       .type = ARM_CP_NOP, .access = PL0_W,
7270       .accessfn = aa64_cacheop_poc_access },
7271     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
7272       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
7273       .type = ARM_CP_NOP, .access = PL0_W,
7274       .accessfn = aa64_cacheop_poc_access },
7275     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7276       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7277       .access = PL0_W, .type = ARM_CP_DC_GVA,
7278 #ifndef CONFIG_USER_ONLY
7279       /* Avoid overhead of an access check that always passes in user-mode */
7280       .accessfn = aa64_zva_access,
7281 #endif
7282     },
7283     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7284       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7285       .access = PL0_W, .type = ARM_CP_DC_GZVA,
7286 #ifndef CONFIG_USER_ONLY
7287       /* Avoid overhead of an access check that always passes in user-mode */
7288       .accessfn = aa64_zva_access,
7289 #endif
7290     },
7291 };
7292 
7293 static CPAccessResult access_scxtnum(CPUARMState *env, const ARMCPRegInfo *ri,
7294                                      bool isread)
7295 {
7296     uint64_t hcr = arm_hcr_el2_eff(env);
7297     int el = arm_current_el(env);
7298 
7299     if (el == 0 && !((hcr & HCR_E2H) && (hcr & HCR_TGE))) {
7300         if (env->cp15.sctlr_el[1] & SCTLR_TSCXT) {
7301             if (hcr & HCR_TGE) {
7302                 return CP_ACCESS_TRAP_EL2;
7303             }
7304             return CP_ACCESS_TRAP;
7305         }
7306     } else if (el < 2 && (env->cp15.sctlr_el[2] & SCTLR_TSCXT)) {
7307         return CP_ACCESS_TRAP_EL2;
7308     }
7309     if (el < 2 && arm_is_el2_enabled(env) && !(hcr & HCR_ENSCXT)) {
7310         return CP_ACCESS_TRAP_EL2;
7311     }
7312     if (el < 3
7313         && arm_feature(env, ARM_FEATURE_EL3)
7314         && !(env->cp15.scr_el3 & SCR_ENSCXT)) {
7315         return CP_ACCESS_TRAP_EL3;
7316     }
7317     return CP_ACCESS_OK;
7318 }
7319 
7320 static const ARMCPRegInfo scxtnum_reginfo[] = {
7321     { .name = "SCXTNUM_EL0", .state = ARM_CP_STATE_AA64,
7322       .opc0 = 3, .opc1 = 3, .crn = 13, .crm = 0, .opc2 = 7,
7323       .access = PL0_RW, .accessfn = access_scxtnum,
7324       .fieldoffset = offsetof(CPUARMState, scxtnum_el[0]) },
7325     { .name = "SCXTNUM_EL1", .state = ARM_CP_STATE_AA64,
7326       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 7,
7327       .access = PL1_RW, .accessfn = access_scxtnum,
7328       .fieldoffset = offsetof(CPUARMState, scxtnum_el[1]) },
7329     { .name = "SCXTNUM_EL2", .state = ARM_CP_STATE_AA64,
7330       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 7,
7331       .access = PL2_RW, .accessfn = access_scxtnum,
7332       .fieldoffset = offsetof(CPUARMState, scxtnum_el[2]) },
7333     { .name = "SCXTNUM_EL3", .state = ARM_CP_STATE_AA64,
7334       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 7,
7335       .access = PL3_RW,
7336       .fieldoffset = offsetof(CPUARMState, scxtnum_el[3]) },
7337 };
7338 #endif /* TARGET_AARCH64 */
7339 
7340 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7341                                      bool isread)
7342 {
7343     int el = arm_current_el(env);
7344 
7345     if (el == 0) {
7346         uint64_t sctlr = arm_sctlr(env, el);
7347         if (!(sctlr & SCTLR_EnRCTX)) {
7348             return CP_ACCESS_TRAP;
7349         }
7350     } else if (el == 1) {
7351         uint64_t hcr = arm_hcr_el2_eff(env);
7352         if (hcr & HCR_NV) {
7353             return CP_ACCESS_TRAP_EL2;
7354         }
7355     }
7356     return CP_ACCESS_OK;
7357 }
7358 
7359 static const ARMCPRegInfo predinv_reginfo[] = {
7360     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7361       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7362       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7363     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7364       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7365       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7366     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7367       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7368       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7369     /*
7370      * Note the AArch32 opcodes have a different OPC1.
7371      */
7372     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7373       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7374       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7375     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7376       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7377       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7378     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7379       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7380       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7381 };
7382 
7383 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7384 {
7385     /* Read the high 32 bits of the current CCSIDR */
7386     return extract64(ccsidr_read(env, ri), 32, 32);
7387 }
7388 
7389 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7390     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7391       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7392       .access = PL1_R,
7393       .accessfn = access_aa64_tid2,
7394       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7395 };
7396 
7397 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7398                                        bool isread)
7399 {
7400     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7401         return CP_ACCESS_TRAP_EL2;
7402     }
7403 
7404     return CP_ACCESS_OK;
7405 }
7406 
7407 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7408                                        bool isread)
7409 {
7410     if (arm_feature(env, ARM_FEATURE_V8)) {
7411         return access_aa64_tid3(env, ri, isread);
7412     }
7413 
7414     return CP_ACCESS_OK;
7415 }
7416 
7417 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7418                                      bool isread)
7419 {
7420     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7421         return CP_ACCESS_TRAP_EL2;
7422     }
7423 
7424     return CP_ACCESS_OK;
7425 }
7426 
7427 static CPAccessResult access_joscr_jmcr(CPUARMState *env,
7428                                         const ARMCPRegInfo *ri, bool isread)
7429 {
7430     /*
7431      * HSTR.TJDBX traps JOSCR and JMCR accesses, but it exists only
7432      * in v7A, not in v8A.
7433      */
7434     if (!arm_feature(env, ARM_FEATURE_V8) &&
7435         arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
7436         (env->cp15.hstr_el2 & HSTR_TJDBX)) {
7437         return CP_ACCESS_TRAP_EL2;
7438     }
7439     return CP_ACCESS_OK;
7440 }
7441 
7442 static const ARMCPRegInfo jazelle_regs[] = {
7443     { .name = "JIDR",
7444       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7445       .access = PL1_R, .accessfn = access_jazelle,
7446       .type = ARM_CP_CONST, .resetvalue = 0 },
7447     { .name = "JOSCR",
7448       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7449       .accessfn = access_joscr_jmcr,
7450       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7451     { .name = "JMCR",
7452       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7453       .accessfn = access_joscr_jmcr,
7454       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7455 };
7456 
7457 static const ARMCPRegInfo contextidr_el2 = {
7458     .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7459     .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7460     .access = PL2_RW,
7461     .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2])
7462 };
7463 
7464 static const ARMCPRegInfo vhe_reginfo[] = {
7465     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7466       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7467       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7468       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7469 #ifndef CONFIG_USER_ONLY
7470     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7471       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7472       .fieldoffset =
7473         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7474       .type = ARM_CP_IO, .access = PL2_RW,
7475       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7476     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7477       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7478       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7479       .resetfn = gt_hv_timer_reset,
7480       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7481     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7482       .type = ARM_CP_IO,
7483       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7484       .access = PL2_RW,
7485       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7486       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7487     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7488       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7489       .type = ARM_CP_IO | ARM_CP_ALIAS,
7490       .access = PL2_RW, .accessfn = e2h_access,
7491       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7492       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7493     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7494       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7495       .type = ARM_CP_IO | ARM_CP_ALIAS,
7496       .access = PL2_RW, .accessfn = e2h_access,
7497       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7498       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7499     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7500       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7501       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7502       .access = PL2_RW, .accessfn = e2h_access,
7503       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7504     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7505       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7506       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7507       .access = PL2_RW, .accessfn = e2h_access,
7508       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7509     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7510       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7511       .type = ARM_CP_IO | ARM_CP_ALIAS,
7512       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7513       .access = PL2_RW, .accessfn = e2h_access,
7514       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7515     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7516       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7517       .type = ARM_CP_IO | ARM_CP_ALIAS,
7518       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7519       .access = PL2_RW, .accessfn = e2h_access,
7520       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7521 #endif
7522 };
7523 
7524 #ifndef CONFIG_USER_ONLY
7525 static const ARMCPRegInfo ats1e1_reginfo[] = {
7526     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7527       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7528       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7529       .writefn = ats_write64 },
7530     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7531       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7532       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7533       .writefn = ats_write64 },
7534 };
7535 
7536 static const ARMCPRegInfo ats1cp_reginfo[] = {
7537     { .name = "ATS1CPRP",
7538       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7539       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7540       .writefn = ats_write },
7541     { .name = "ATS1CPWP",
7542       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7543       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7544       .writefn = ats_write },
7545 };
7546 #endif
7547 
7548 /*
7549  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7550  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7551  * is non-zero, which is never for ARMv7, optionally in ARMv8
7552  * and mandatorily for ARMv8.2 and up.
7553  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7554  * implementation is RAZ/WI we can ignore this detail, as we
7555  * do for ACTLR.
7556  */
7557 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7558     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7559       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7560       .access = PL1_RW, .accessfn = access_tacr,
7561       .type = ARM_CP_CONST, .resetvalue = 0 },
7562     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7563       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7564       .access = PL2_RW, .type = ARM_CP_CONST,
7565       .resetvalue = 0 },
7566 };
7567 
7568 void register_cp_regs_for_features(ARMCPU *cpu)
7569 {
7570     /* Register all the coprocessor registers based on feature bits */
7571     CPUARMState *env = &cpu->env;
7572     if (arm_feature(env, ARM_FEATURE_M)) {
7573         /* M profile has no coprocessor registers */
7574         return;
7575     }
7576 
7577     define_arm_cp_regs(cpu, cp_reginfo);
7578     if (!arm_feature(env, ARM_FEATURE_V8)) {
7579         /* Must go early as it is full of wildcards that may be
7580          * overridden by later definitions.
7581          */
7582         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7583     }
7584 
7585     if (arm_feature(env, ARM_FEATURE_V6)) {
7586         /* The ID registers all have impdef reset values */
7587         ARMCPRegInfo v6_idregs[] = {
7588             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7589               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7590               .access = PL1_R, .type = ARM_CP_CONST,
7591               .accessfn = access_aa32_tid3,
7592               .resetvalue = cpu->isar.id_pfr0 },
7593             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7594              * the value of the GIC field until after we define these regs.
7595              */
7596             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7597               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7598               .access = PL1_R, .type = ARM_CP_NO_RAW,
7599               .accessfn = access_aa32_tid3,
7600               .readfn = id_pfr1_read,
7601               .writefn = arm_cp_write_ignore },
7602             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7603               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7604               .access = PL1_R, .type = ARM_CP_CONST,
7605               .accessfn = access_aa32_tid3,
7606               .resetvalue = cpu->isar.id_dfr0 },
7607             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7608               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7609               .access = PL1_R, .type = ARM_CP_CONST,
7610               .accessfn = access_aa32_tid3,
7611               .resetvalue = cpu->id_afr0 },
7612             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7613               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7614               .access = PL1_R, .type = ARM_CP_CONST,
7615               .accessfn = access_aa32_tid3,
7616               .resetvalue = cpu->isar.id_mmfr0 },
7617             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7618               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7619               .access = PL1_R, .type = ARM_CP_CONST,
7620               .accessfn = access_aa32_tid3,
7621               .resetvalue = cpu->isar.id_mmfr1 },
7622             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7623               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7624               .access = PL1_R, .type = ARM_CP_CONST,
7625               .accessfn = access_aa32_tid3,
7626               .resetvalue = cpu->isar.id_mmfr2 },
7627             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7628               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7629               .access = PL1_R, .type = ARM_CP_CONST,
7630               .accessfn = access_aa32_tid3,
7631               .resetvalue = cpu->isar.id_mmfr3 },
7632             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7633               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7634               .access = PL1_R, .type = ARM_CP_CONST,
7635               .accessfn = access_aa32_tid3,
7636               .resetvalue = cpu->isar.id_isar0 },
7637             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7638               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7639               .access = PL1_R, .type = ARM_CP_CONST,
7640               .accessfn = access_aa32_tid3,
7641               .resetvalue = cpu->isar.id_isar1 },
7642             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7643               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7644               .access = PL1_R, .type = ARM_CP_CONST,
7645               .accessfn = access_aa32_tid3,
7646               .resetvalue = cpu->isar.id_isar2 },
7647             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7648               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7649               .access = PL1_R, .type = ARM_CP_CONST,
7650               .accessfn = access_aa32_tid3,
7651               .resetvalue = cpu->isar.id_isar3 },
7652             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7653               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7654               .access = PL1_R, .type = ARM_CP_CONST,
7655               .accessfn = access_aa32_tid3,
7656               .resetvalue = cpu->isar.id_isar4 },
7657             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7658               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7659               .access = PL1_R, .type = ARM_CP_CONST,
7660               .accessfn = access_aa32_tid3,
7661               .resetvalue = cpu->isar.id_isar5 },
7662             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7663               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7664               .access = PL1_R, .type = ARM_CP_CONST,
7665               .accessfn = access_aa32_tid3,
7666               .resetvalue = cpu->isar.id_mmfr4 },
7667             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7668               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7669               .access = PL1_R, .type = ARM_CP_CONST,
7670               .accessfn = access_aa32_tid3,
7671               .resetvalue = cpu->isar.id_isar6 },
7672         };
7673         define_arm_cp_regs(cpu, v6_idregs);
7674         define_arm_cp_regs(cpu, v6_cp_reginfo);
7675     } else {
7676         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7677     }
7678     if (arm_feature(env, ARM_FEATURE_V6K)) {
7679         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7680     }
7681     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7682         !arm_feature(env, ARM_FEATURE_PMSA)) {
7683         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7684     }
7685     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7686         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7687     }
7688     if (arm_feature(env, ARM_FEATURE_V7)) {
7689         ARMCPRegInfo clidr = {
7690             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7691             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7692             .access = PL1_R, .type = ARM_CP_CONST,
7693             .accessfn = access_aa64_tid2,
7694             .resetvalue = cpu->clidr
7695         };
7696         define_one_arm_cp_reg(cpu, &clidr);
7697         define_arm_cp_regs(cpu, v7_cp_reginfo);
7698         define_debug_regs(cpu);
7699         define_pmu_regs(cpu);
7700     } else {
7701         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7702     }
7703     if (arm_feature(env, ARM_FEATURE_V8)) {
7704         /* AArch64 ID registers, which all have impdef reset values.
7705          * Note that within the ID register ranges the unused slots
7706          * must all RAZ, not UNDEF; future architecture versions may
7707          * define new registers here.
7708          */
7709         ARMCPRegInfo v8_idregs[] = {
7710             /*
7711              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7712              * emulation because we don't know the right value for the
7713              * GIC field until after we define these regs.
7714              */
7715             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7716               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7717               .access = PL1_R,
7718 #ifdef CONFIG_USER_ONLY
7719               .type = ARM_CP_CONST,
7720               .resetvalue = cpu->isar.id_aa64pfr0
7721 #else
7722               .type = ARM_CP_NO_RAW,
7723               .accessfn = access_aa64_tid3,
7724               .readfn = id_aa64pfr0_read,
7725               .writefn = arm_cp_write_ignore
7726 #endif
7727             },
7728             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7729               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7730               .access = PL1_R, .type = ARM_CP_CONST,
7731               .accessfn = access_aa64_tid3,
7732               .resetvalue = cpu->isar.id_aa64pfr1},
7733             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7734               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7735               .access = PL1_R, .type = ARM_CP_CONST,
7736               .accessfn = access_aa64_tid3,
7737               .resetvalue = 0 },
7738             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7739               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7740               .access = PL1_R, .type = ARM_CP_CONST,
7741               .accessfn = access_aa64_tid3,
7742               .resetvalue = 0 },
7743             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7744               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7745               .access = PL1_R, .type = ARM_CP_CONST,
7746               .accessfn = access_aa64_tid3,
7747               .resetvalue = cpu->isar.id_aa64zfr0 },
7748             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7749               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7750               .access = PL1_R, .type = ARM_CP_CONST,
7751               .accessfn = access_aa64_tid3,
7752               .resetvalue = 0 },
7753             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7754               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7755               .access = PL1_R, .type = ARM_CP_CONST,
7756               .accessfn = access_aa64_tid3,
7757               .resetvalue = 0 },
7758             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7759               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7760               .access = PL1_R, .type = ARM_CP_CONST,
7761               .accessfn = access_aa64_tid3,
7762               .resetvalue = 0 },
7763             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7764               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7765               .access = PL1_R, .type = ARM_CP_CONST,
7766               .accessfn = access_aa64_tid3,
7767               .resetvalue = cpu->isar.id_aa64dfr0 },
7768             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7769               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7770               .access = PL1_R, .type = ARM_CP_CONST,
7771               .accessfn = access_aa64_tid3,
7772               .resetvalue = cpu->isar.id_aa64dfr1 },
7773             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7774               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7775               .access = PL1_R, .type = ARM_CP_CONST,
7776               .accessfn = access_aa64_tid3,
7777               .resetvalue = 0 },
7778             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7779               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7780               .access = PL1_R, .type = ARM_CP_CONST,
7781               .accessfn = access_aa64_tid3,
7782               .resetvalue = 0 },
7783             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7784               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7785               .access = PL1_R, .type = ARM_CP_CONST,
7786               .accessfn = access_aa64_tid3,
7787               .resetvalue = cpu->id_aa64afr0 },
7788             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7789               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7790               .access = PL1_R, .type = ARM_CP_CONST,
7791               .accessfn = access_aa64_tid3,
7792               .resetvalue = cpu->id_aa64afr1 },
7793             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7794               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7795               .access = PL1_R, .type = ARM_CP_CONST,
7796               .accessfn = access_aa64_tid3,
7797               .resetvalue = 0 },
7798             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7799               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7800               .access = PL1_R, .type = ARM_CP_CONST,
7801               .accessfn = access_aa64_tid3,
7802               .resetvalue = 0 },
7803             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7804               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7805               .access = PL1_R, .type = ARM_CP_CONST,
7806               .accessfn = access_aa64_tid3,
7807               .resetvalue = cpu->isar.id_aa64isar0 },
7808             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7809               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7810               .access = PL1_R, .type = ARM_CP_CONST,
7811               .accessfn = access_aa64_tid3,
7812               .resetvalue = cpu->isar.id_aa64isar1 },
7813             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7814               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7815               .access = PL1_R, .type = ARM_CP_CONST,
7816               .accessfn = access_aa64_tid3,
7817               .resetvalue = 0 },
7818             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7819               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7820               .access = PL1_R, .type = ARM_CP_CONST,
7821               .accessfn = access_aa64_tid3,
7822               .resetvalue = 0 },
7823             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7824               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7825               .access = PL1_R, .type = ARM_CP_CONST,
7826               .accessfn = access_aa64_tid3,
7827               .resetvalue = 0 },
7828             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7829               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7830               .access = PL1_R, .type = ARM_CP_CONST,
7831               .accessfn = access_aa64_tid3,
7832               .resetvalue = 0 },
7833             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7834               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7835               .access = PL1_R, .type = ARM_CP_CONST,
7836               .accessfn = access_aa64_tid3,
7837               .resetvalue = 0 },
7838             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7839               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7840               .access = PL1_R, .type = ARM_CP_CONST,
7841               .accessfn = access_aa64_tid3,
7842               .resetvalue = 0 },
7843             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7844               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7845               .access = PL1_R, .type = ARM_CP_CONST,
7846               .accessfn = access_aa64_tid3,
7847               .resetvalue = cpu->isar.id_aa64mmfr0 },
7848             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7849               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7850               .access = PL1_R, .type = ARM_CP_CONST,
7851               .accessfn = access_aa64_tid3,
7852               .resetvalue = cpu->isar.id_aa64mmfr1 },
7853             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7854               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7855               .access = PL1_R, .type = ARM_CP_CONST,
7856               .accessfn = access_aa64_tid3,
7857               .resetvalue = cpu->isar.id_aa64mmfr2 },
7858             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7859               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7860               .access = PL1_R, .type = ARM_CP_CONST,
7861               .accessfn = access_aa64_tid3,
7862               .resetvalue = 0 },
7863             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7864               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7865               .access = PL1_R, .type = ARM_CP_CONST,
7866               .accessfn = access_aa64_tid3,
7867               .resetvalue = 0 },
7868             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7869               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7870               .access = PL1_R, .type = ARM_CP_CONST,
7871               .accessfn = access_aa64_tid3,
7872               .resetvalue = 0 },
7873             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7874               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7875               .access = PL1_R, .type = ARM_CP_CONST,
7876               .accessfn = access_aa64_tid3,
7877               .resetvalue = 0 },
7878             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7879               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7880               .access = PL1_R, .type = ARM_CP_CONST,
7881               .accessfn = access_aa64_tid3,
7882               .resetvalue = 0 },
7883             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7884               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7885               .access = PL1_R, .type = ARM_CP_CONST,
7886               .accessfn = access_aa64_tid3,
7887               .resetvalue = cpu->isar.mvfr0 },
7888             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7889               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7890               .access = PL1_R, .type = ARM_CP_CONST,
7891               .accessfn = access_aa64_tid3,
7892               .resetvalue = cpu->isar.mvfr1 },
7893             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7894               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7895               .access = PL1_R, .type = ARM_CP_CONST,
7896               .accessfn = access_aa64_tid3,
7897               .resetvalue = cpu->isar.mvfr2 },
7898             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7899               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7900               .access = PL1_R, .type = ARM_CP_CONST,
7901               .accessfn = access_aa64_tid3,
7902               .resetvalue = 0 },
7903             { .name = "ID_PFR2", .state = ARM_CP_STATE_BOTH,
7904               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7905               .access = PL1_R, .type = ARM_CP_CONST,
7906               .accessfn = access_aa64_tid3,
7907               .resetvalue = cpu->isar.id_pfr2 },
7908             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7909               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7910               .access = PL1_R, .type = ARM_CP_CONST,
7911               .accessfn = access_aa64_tid3,
7912               .resetvalue = 0 },
7913             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7914               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7915               .access = PL1_R, .type = ARM_CP_CONST,
7916               .accessfn = access_aa64_tid3,
7917               .resetvalue = 0 },
7918             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7919               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7920               .access = PL1_R, .type = ARM_CP_CONST,
7921               .accessfn = access_aa64_tid3,
7922               .resetvalue = 0 },
7923             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7924               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7925               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7926               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7927             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7928               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7929               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7930               .resetvalue = cpu->pmceid0 },
7931             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7932               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7933               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7934               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7935             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7936               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7937               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7938               .resetvalue = cpu->pmceid1 },
7939         };
7940 #ifdef CONFIG_USER_ONLY
7941         static const ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7942             { .name = "ID_AA64PFR0_EL1",
7943               .exported_bits = 0x000f000f00ff0000,
7944               .fixed_bits    = 0x0000000000000011 },
7945             { .name = "ID_AA64PFR1_EL1",
7946               .exported_bits = 0x00000000000000f0 },
7947             { .name = "ID_AA64PFR*_EL1_RESERVED",
7948               .is_glob = true                     },
7949             { .name = "ID_AA64ZFR0_EL1"           },
7950             { .name = "ID_AA64MMFR0_EL1",
7951               .fixed_bits    = 0x00000000ff000000 },
7952             { .name = "ID_AA64MMFR1_EL1"          },
7953             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7954               .is_glob = true                     },
7955             { .name = "ID_AA64DFR0_EL1",
7956               .fixed_bits    = 0x0000000000000006 },
7957             { .name = "ID_AA64DFR1_EL1"           },
7958             { .name = "ID_AA64DFR*_EL1_RESERVED",
7959               .is_glob = true                     },
7960             { .name = "ID_AA64AFR*",
7961               .is_glob = true                     },
7962             { .name = "ID_AA64ISAR0_EL1",
7963               .exported_bits = 0x00fffffff0fffff0 },
7964             { .name = "ID_AA64ISAR1_EL1",
7965               .exported_bits = 0x000000f0ffffffff },
7966             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7967               .is_glob = true                     },
7968         };
7969         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7970 #endif
7971         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7972         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7973             !arm_feature(env, ARM_FEATURE_EL2)) {
7974             ARMCPRegInfo rvbar = {
7975                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7976                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7977                 .access = PL1_R,
7978                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7979             };
7980             define_one_arm_cp_reg(cpu, &rvbar);
7981         }
7982         define_arm_cp_regs(cpu, v8_idregs);
7983         define_arm_cp_regs(cpu, v8_cp_reginfo);
7984     }
7985 
7986     /*
7987      * Register the base EL2 cpregs.
7988      * Pre v8, these registers are implemented only as part of the
7989      * Virtualization Extensions (EL2 present).  Beginning with v8,
7990      * if EL2 is missing but EL3 is enabled, mostly these become
7991      * RES0 from EL3, with some specific exceptions.
7992      */
7993     if (arm_feature(env, ARM_FEATURE_EL2)
7994         || (arm_feature(env, ARM_FEATURE_EL3)
7995             && arm_feature(env, ARM_FEATURE_V8))) {
7996         uint64_t vmpidr_def = mpidr_read_val(env);
7997         ARMCPRegInfo vpidr_regs[] = {
7998             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7999               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
8000               .access = PL2_RW, .accessfn = access_el3_aa32ns,
8001               .resetvalue = cpu->midr,
8002               .type = ARM_CP_ALIAS | ARM_CP_EL3_NO_EL2_C_NZ,
8003               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
8004             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
8005               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
8006               .access = PL2_RW, .resetvalue = cpu->midr,
8007               .type = ARM_CP_EL3_NO_EL2_C_NZ,
8008               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
8009             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
8010               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
8011               .access = PL2_RW, .accessfn = access_el3_aa32ns,
8012               .resetvalue = vmpidr_def,
8013               .type = ARM_CP_ALIAS | ARM_CP_EL3_NO_EL2_C_NZ,
8014               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
8015             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
8016               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
8017               .access = PL2_RW, .resetvalue = vmpidr_def,
8018               .type = ARM_CP_EL3_NO_EL2_C_NZ,
8019               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
8020         };
8021         /*
8022          * The only field of MDCR_EL2 that has a defined architectural reset
8023          * value is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N.
8024          */
8025         ARMCPRegInfo mdcr_el2 = {
8026             .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
8027             .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
8028             .access = PL2_RW, .resetvalue = pmu_num_counters(env),
8029             .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2),
8030         };
8031         define_one_arm_cp_reg(cpu, &mdcr_el2);
8032         define_arm_cp_regs(cpu, vpidr_regs);
8033         define_arm_cp_regs(cpu, el2_cp_reginfo);
8034         if (arm_feature(env, ARM_FEATURE_V8)) {
8035             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
8036         }
8037         if (cpu_isar_feature(aa64_sel2, cpu)) {
8038             define_arm_cp_regs(cpu, el2_sec_cp_reginfo);
8039         }
8040         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
8041         if (!arm_feature(env, ARM_FEATURE_EL3)) {
8042             ARMCPRegInfo rvbar = {
8043                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
8044                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
8045                 .access = PL2_R,
8046                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
8047             };
8048             define_one_arm_cp_reg(cpu, &rvbar);
8049         }
8050     }
8051 
8052     /* Register the base EL3 cpregs. */
8053     if (arm_feature(env, ARM_FEATURE_EL3)) {
8054         define_arm_cp_regs(cpu, el3_cp_reginfo);
8055         ARMCPRegInfo el3_regs[] = {
8056             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
8057               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
8058               .access = PL3_R,
8059               .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
8060             },
8061             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
8062               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
8063               .access = PL3_RW,
8064               .raw_writefn = raw_write, .writefn = sctlr_write,
8065               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
8066               .resetvalue = cpu->reset_sctlr },
8067         };
8068 
8069         define_arm_cp_regs(cpu, el3_regs);
8070     }
8071     /* The behaviour of NSACR is sufficiently various that we don't
8072      * try to describe it in a single reginfo:
8073      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
8074      *     reads as constant 0xc00 from NS EL1 and NS EL2
8075      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
8076      *  if v7 without EL3, register doesn't exist
8077      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
8078      */
8079     if (arm_feature(env, ARM_FEATURE_EL3)) {
8080         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8081             static const ARMCPRegInfo nsacr = {
8082                 .name = "NSACR", .type = ARM_CP_CONST,
8083                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8084                 .access = PL1_RW, .accessfn = nsacr_access,
8085                 .resetvalue = 0xc00
8086             };
8087             define_one_arm_cp_reg(cpu, &nsacr);
8088         } else {
8089             static const ARMCPRegInfo nsacr = {
8090                 .name = "NSACR",
8091                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8092                 .access = PL3_RW | PL1_R,
8093                 .resetvalue = 0,
8094                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
8095             };
8096             define_one_arm_cp_reg(cpu, &nsacr);
8097         }
8098     } else {
8099         if (arm_feature(env, ARM_FEATURE_V8)) {
8100             static const ARMCPRegInfo nsacr = {
8101                 .name = "NSACR", .type = ARM_CP_CONST,
8102                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8103                 .access = PL1_R,
8104                 .resetvalue = 0xc00
8105             };
8106             define_one_arm_cp_reg(cpu, &nsacr);
8107         }
8108     }
8109 
8110     if (arm_feature(env, ARM_FEATURE_PMSA)) {
8111         if (arm_feature(env, ARM_FEATURE_V6)) {
8112             /* PMSAv6 not implemented */
8113             assert(arm_feature(env, ARM_FEATURE_V7));
8114             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8115             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
8116         } else {
8117             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
8118         }
8119     } else {
8120         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8121         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
8122         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
8123         if (cpu_isar_feature(aa32_hpd, cpu)) {
8124             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
8125         }
8126     }
8127     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
8128         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
8129     }
8130     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
8131         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
8132     }
8133     if (arm_feature(env, ARM_FEATURE_VAPA)) {
8134         define_arm_cp_regs(cpu, vapa_cp_reginfo);
8135     }
8136     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
8137         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
8138     }
8139     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
8140         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
8141     }
8142     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
8143         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
8144     }
8145     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
8146         define_arm_cp_regs(cpu, omap_cp_reginfo);
8147     }
8148     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
8149         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
8150     }
8151     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8152         define_arm_cp_regs(cpu, xscale_cp_reginfo);
8153     }
8154     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
8155         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
8156     }
8157     if (arm_feature(env, ARM_FEATURE_LPAE)) {
8158         define_arm_cp_regs(cpu, lpae_cp_reginfo);
8159     }
8160     if (cpu_isar_feature(aa32_jazelle, cpu)) {
8161         define_arm_cp_regs(cpu, jazelle_regs);
8162     }
8163     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
8164      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
8165      * be read-only (ie write causes UNDEF exception).
8166      */
8167     {
8168         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
8169             /* Pre-v8 MIDR space.
8170              * Note that the MIDR isn't a simple constant register because
8171              * of the TI925 behaviour where writes to another register can
8172              * cause the MIDR value to change.
8173              *
8174              * Unimplemented registers in the c15 0 0 0 space default to
8175              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
8176              * and friends override accordingly.
8177              */
8178             { .name = "MIDR",
8179               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
8180               .access = PL1_R, .resetvalue = cpu->midr,
8181               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
8182               .readfn = midr_read,
8183               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8184               .type = ARM_CP_OVERRIDE },
8185             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
8186             { .name = "DUMMY",
8187               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
8188               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8189             { .name = "DUMMY",
8190               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
8191               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8192             { .name = "DUMMY",
8193               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
8194               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8195             { .name = "DUMMY",
8196               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
8197               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8198             { .name = "DUMMY",
8199               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
8200               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8201         };
8202         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
8203             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
8204               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
8205               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
8206               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8207               .readfn = midr_read },
8208             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
8209             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8210               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8211               .access = PL1_R, .resetvalue = cpu->midr },
8212             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8213               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
8214               .access = PL1_R, .resetvalue = cpu->midr },
8215             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
8216               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
8217               .access = PL1_R,
8218               .accessfn = access_aa64_tid1,
8219               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
8220         };
8221         ARMCPRegInfo id_cp_reginfo[] = {
8222             /* These are common to v8 and pre-v8 */
8223             { .name = "CTR",
8224               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
8225               .access = PL1_R, .accessfn = ctr_el0_access,
8226               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8227             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
8228               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
8229               .access = PL0_R, .accessfn = ctr_el0_access,
8230               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8231             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
8232             { .name = "TCMTR",
8233               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
8234               .access = PL1_R,
8235               .accessfn = access_aa32_tid1,
8236               .type = ARM_CP_CONST, .resetvalue = 0 },
8237         };
8238         /* TLBTR is specific to VMSA */
8239         ARMCPRegInfo id_tlbtr_reginfo = {
8240               .name = "TLBTR",
8241               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
8242               .access = PL1_R,
8243               .accessfn = access_aa32_tid1,
8244               .type = ARM_CP_CONST, .resetvalue = 0,
8245         };
8246         /* MPUIR is specific to PMSA V6+ */
8247         ARMCPRegInfo id_mpuir_reginfo = {
8248               .name = "MPUIR",
8249               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8250               .access = PL1_R, .type = ARM_CP_CONST,
8251               .resetvalue = cpu->pmsav7_dregion << 8
8252         };
8253         static const ARMCPRegInfo crn0_wi_reginfo = {
8254             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
8255             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
8256             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
8257         };
8258 #ifdef CONFIG_USER_ONLY
8259         static const ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
8260             { .name = "MIDR_EL1",
8261               .exported_bits = 0x00000000ffffffff },
8262             { .name = "REVIDR_EL1"                },
8263         };
8264         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
8265 #endif
8266         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
8267             arm_feature(env, ARM_FEATURE_STRONGARM)) {
8268             size_t i;
8269             /* Register the blanket "writes ignored" value first to cover the
8270              * whole space. Then update the specific ID registers to allow write
8271              * access, so that they ignore writes rather than causing them to
8272              * UNDEF.
8273              */
8274             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
8275             for (i = 0; i < ARRAY_SIZE(id_pre_v8_midr_cp_reginfo); ++i) {
8276                 id_pre_v8_midr_cp_reginfo[i].access = PL1_RW;
8277             }
8278             for (i = 0; i < ARRAY_SIZE(id_cp_reginfo); ++i) {
8279                 id_cp_reginfo[i].access = PL1_RW;
8280             }
8281             id_mpuir_reginfo.access = PL1_RW;
8282             id_tlbtr_reginfo.access = PL1_RW;
8283         }
8284         if (arm_feature(env, ARM_FEATURE_V8)) {
8285             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
8286         } else {
8287             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
8288         }
8289         define_arm_cp_regs(cpu, id_cp_reginfo);
8290         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
8291             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
8292         } else if (arm_feature(env, ARM_FEATURE_V7)) {
8293             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
8294         }
8295     }
8296 
8297     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
8298         ARMCPRegInfo mpidr_cp_reginfo[] = {
8299             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
8300               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
8301               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
8302         };
8303 #ifdef CONFIG_USER_ONLY
8304         static const ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
8305             { .name = "MPIDR_EL1",
8306               .fixed_bits = 0x0000000080000000 },
8307         };
8308         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
8309 #endif
8310         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
8311     }
8312 
8313     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
8314         ARMCPRegInfo auxcr_reginfo[] = {
8315             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
8316               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
8317               .access = PL1_RW, .accessfn = access_tacr,
8318               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
8319             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
8320               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
8321               .access = PL2_RW, .type = ARM_CP_CONST,
8322               .resetvalue = 0 },
8323             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8324               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8325               .access = PL3_RW, .type = ARM_CP_CONST,
8326               .resetvalue = 0 },
8327         };
8328         define_arm_cp_regs(cpu, auxcr_reginfo);
8329         if (cpu_isar_feature(aa32_ac2, cpu)) {
8330             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8331         }
8332     }
8333 
8334     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8335         /*
8336          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8337          * There are two flavours:
8338          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8339          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8340          *      32-bit register visible to AArch32 at a different encoding
8341          *      to the "flavour 1" register and with the bits rearranged to
8342          *      be able to squash a 64-bit address into the 32-bit view.
8343          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8344          * in future if we support AArch32-only configs of some of the
8345          * AArch64 cores we might need to add a specific feature flag
8346          * to indicate cores with "flavour 2" CBAR.
8347          */
8348         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8349             /* 32 bit view is [31:18] 0...0 [43:32]. */
8350             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8351                 | extract64(cpu->reset_cbar, 32, 12);
8352             ARMCPRegInfo cbar_reginfo[] = {
8353                 { .name = "CBAR",
8354                   .type = ARM_CP_CONST,
8355                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8356                   .access = PL1_R, .resetvalue = cbar32 },
8357                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8358                   .type = ARM_CP_CONST,
8359                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8360                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8361             };
8362             /* We don't implement a r/w 64 bit CBAR currently */
8363             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8364             define_arm_cp_regs(cpu, cbar_reginfo);
8365         } else {
8366             ARMCPRegInfo cbar = {
8367                 .name = "CBAR",
8368                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8369                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8370                 .fieldoffset = offsetof(CPUARMState,
8371                                         cp15.c15_config_base_address)
8372             };
8373             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8374                 cbar.access = PL1_R;
8375                 cbar.fieldoffset = 0;
8376                 cbar.type = ARM_CP_CONST;
8377             }
8378             define_one_arm_cp_reg(cpu, &cbar);
8379         }
8380     }
8381 
8382     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8383         static const ARMCPRegInfo vbar_cp_reginfo[] = {
8384             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8385               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8386               .access = PL1_RW, .writefn = vbar_write,
8387               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8388                                      offsetof(CPUARMState, cp15.vbar_ns) },
8389               .resetvalue = 0 },
8390         };
8391         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8392     }
8393 
8394     /* Generic registers whose values depend on the implementation */
8395     {
8396         ARMCPRegInfo sctlr = {
8397             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8398             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8399             .access = PL1_RW, .accessfn = access_tvm_trvm,
8400             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8401                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8402             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8403             .raw_writefn = raw_write,
8404         };
8405         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8406             /* Normally we would always end the TB on an SCTLR write, but Linux
8407              * arch/arm/mach-pxa/sleep.S expects two instructions following
8408              * an MMU enable to execute from cache.  Imitate this behaviour.
8409              */
8410             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8411         }
8412         define_one_arm_cp_reg(cpu, &sctlr);
8413     }
8414 
8415     if (cpu_isar_feature(aa64_lor, cpu)) {
8416         define_arm_cp_regs(cpu, lor_reginfo);
8417     }
8418     if (cpu_isar_feature(aa64_pan, cpu)) {
8419         define_one_arm_cp_reg(cpu, &pan_reginfo);
8420     }
8421 #ifndef CONFIG_USER_ONLY
8422     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8423         define_arm_cp_regs(cpu, ats1e1_reginfo);
8424     }
8425     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8426         define_arm_cp_regs(cpu, ats1cp_reginfo);
8427     }
8428 #endif
8429     if (cpu_isar_feature(aa64_uao, cpu)) {
8430         define_one_arm_cp_reg(cpu, &uao_reginfo);
8431     }
8432 
8433     if (cpu_isar_feature(aa64_dit, cpu)) {
8434         define_one_arm_cp_reg(cpu, &dit_reginfo);
8435     }
8436     if (cpu_isar_feature(aa64_ssbs, cpu)) {
8437         define_one_arm_cp_reg(cpu, &ssbs_reginfo);
8438     }
8439     if (cpu_isar_feature(any_ras, cpu)) {
8440         define_arm_cp_regs(cpu, minimal_ras_reginfo);
8441     }
8442 
8443     if (cpu_isar_feature(aa64_vh, cpu) ||
8444         cpu_isar_feature(aa64_debugv8p2, cpu)) {
8445         define_one_arm_cp_reg(cpu, &contextidr_el2);
8446     }
8447     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8448         define_arm_cp_regs(cpu, vhe_reginfo);
8449     }
8450 
8451     if (cpu_isar_feature(aa64_sve, cpu)) {
8452         define_arm_cp_regs(cpu, zcr_reginfo);
8453     }
8454 
8455     if (cpu_isar_feature(aa64_hcx, cpu)) {
8456         define_one_arm_cp_reg(cpu, &hcrx_el2_reginfo);
8457     }
8458 
8459 #ifdef TARGET_AARCH64
8460     if (cpu_isar_feature(aa64_pauth, cpu)) {
8461         define_arm_cp_regs(cpu, pauth_reginfo);
8462     }
8463     if (cpu_isar_feature(aa64_rndr, cpu)) {
8464         define_arm_cp_regs(cpu, rndr_reginfo);
8465     }
8466     if (cpu_isar_feature(aa64_tlbirange, cpu)) {
8467         define_arm_cp_regs(cpu, tlbirange_reginfo);
8468     }
8469     if (cpu_isar_feature(aa64_tlbios, cpu)) {
8470         define_arm_cp_regs(cpu, tlbios_reginfo);
8471     }
8472 #ifndef CONFIG_USER_ONLY
8473     /* Data Cache clean instructions up to PoP */
8474     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8475         define_one_arm_cp_reg(cpu, dcpop_reg);
8476 
8477         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8478             define_one_arm_cp_reg(cpu, dcpodp_reg);
8479         }
8480     }
8481 #endif /*CONFIG_USER_ONLY*/
8482 
8483     /*
8484      * If full MTE is enabled, add all of the system registers.
8485      * If only "instructions available at EL0" are enabled,
8486      * then define only a RAZ/WI version of PSTATE.TCO.
8487      */
8488     if (cpu_isar_feature(aa64_mte, cpu)) {
8489         define_arm_cp_regs(cpu, mte_reginfo);
8490         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8491     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8492         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8493         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8494     }
8495 
8496     if (cpu_isar_feature(aa64_scxtnum, cpu)) {
8497         define_arm_cp_regs(cpu, scxtnum_reginfo);
8498     }
8499 #endif
8500 
8501     if (cpu_isar_feature(any_predinv, cpu)) {
8502         define_arm_cp_regs(cpu, predinv_reginfo);
8503     }
8504 
8505     if (cpu_isar_feature(any_ccidx, cpu)) {
8506         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8507     }
8508 
8509 #ifndef CONFIG_USER_ONLY
8510     /*
8511      * Register redirections and aliases must be done last,
8512      * after the registers from the other extensions have been defined.
8513      */
8514     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8515         define_arm_vh_e2h_redirects_aliases(cpu);
8516     }
8517 #endif
8518 }
8519 
8520 /* Sort alphabetically by type name, except for "any". */
8521 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8522 {
8523     ObjectClass *class_a = (ObjectClass *)a;
8524     ObjectClass *class_b = (ObjectClass *)b;
8525     const char *name_a, *name_b;
8526 
8527     name_a = object_class_get_name(class_a);
8528     name_b = object_class_get_name(class_b);
8529     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8530         return 1;
8531     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8532         return -1;
8533     } else {
8534         return strcmp(name_a, name_b);
8535     }
8536 }
8537 
8538 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8539 {
8540     ObjectClass *oc = data;
8541     const char *typename;
8542     char *name;
8543 
8544     typename = object_class_get_name(oc);
8545     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8546     qemu_printf("  %s\n", name);
8547     g_free(name);
8548 }
8549 
8550 void arm_cpu_list(void)
8551 {
8552     GSList *list;
8553 
8554     list = object_class_get_list(TYPE_ARM_CPU, false);
8555     list = g_slist_sort(list, arm_cpu_list_compare);
8556     qemu_printf("Available CPUs:\n");
8557     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8558     g_slist_free(list);
8559 }
8560 
8561 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8562 {
8563     ObjectClass *oc = data;
8564     CpuDefinitionInfoList **cpu_list = user_data;
8565     CpuDefinitionInfo *info;
8566     const char *typename;
8567 
8568     typename = object_class_get_name(oc);
8569     info = g_malloc0(sizeof(*info));
8570     info->name = g_strndup(typename,
8571                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8572     info->q_typename = g_strdup(typename);
8573 
8574     QAPI_LIST_PREPEND(*cpu_list, info);
8575 }
8576 
8577 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8578 {
8579     CpuDefinitionInfoList *cpu_list = NULL;
8580     GSList *list;
8581 
8582     list = object_class_get_list(TYPE_ARM_CPU, false);
8583     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8584     g_slist_free(list);
8585 
8586     return cpu_list;
8587 }
8588 
8589 /*
8590  * Private utility function for define_one_arm_cp_reg_with_opaque():
8591  * add a single reginfo struct to the hash table.
8592  */
8593 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8594                                    void *opaque, CPState state,
8595                                    CPSecureState secstate,
8596                                    int crm, int opc1, int opc2,
8597                                    const char *name)
8598 {
8599     CPUARMState *env = &cpu->env;
8600     uint32_t key;
8601     ARMCPRegInfo *r2;
8602     bool is64 = r->type & ARM_CP_64BIT;
8603     bool ns = secstate & ARM_CP_SECSTATE_NS;
8604     int cp = r->cp;
8605     size_t name_len;
8606     bool make_const;
8607 
8608     switch (state) {
8609     case ARM_CP_STATE_AA32:
8610         /* We assume it is a cp15 register if the .cp field is left unset. */
8611         if (cp == 0 && r->state == ARM_CP_STATE_BOTH) {
8612             cp = 15;
8613         }
8614         key = ENCODE_CP_REG(cp, is64, ns, r->crn, crm, opc1, opc2);
8615         break;
8616     case ARM_CP_STATE_AA64:
8617         /*
8618          * To allow abbreviation of ARMCPRegInfo definitions, we treat
8619          * cp == 0 as equivalent to the value for "standard guest-visible
8620          * sysreg".  STATE_BOTH definitions are also always "standard sysreg"
8621          * in their AArch64 view (the .cp value may be non-zero for the
8622          * benefit of the AArch32 view).
8623          */
8624         if (cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8625             cp = CP_REG_ARM64_SYSREG_CP;
8626         }
8627         key = ENCODE_AA64_CP_REG(cp, r->crn, crm, r->opc0, opc1, opc2);
8628         break;
8629     default:
8630         g_assert_not_reached();
8631     }
8632 
8633     /* Overriding of an existing definition must be explicitly requested. */
8634     if (!(r->type & ARM_CP_OVERRIDE)) {
8635         const ARMCPRegInfo *oldreg = get_arm_cp_reginfo(cpu->cp_regs, key);
8636         if (oldreg) {
8637             assert(oldreg->type & ARM_CP_OVERRIDE);
8638         }
8639     }
8640 
8641     /*
8642      * Eliminate registers that are not present because the EL is missing.
8643      * Doing this here makes it easier to put all registers for a given
8644      * feature into the same ARMCPRegInfo array and define them all at once.
8645      */
8646     make_const = false;
8647     if (arm_feature(env, ARM_FEATURE_EL3)) {
8648         /*
8649          * An EL2 register without EL2 but with EL3 is (usually) RES0.
8650          * See rule RJFFP in section D1.1.3 of DDI0487H.a.
8651          */
8652         int min_el = ctz32(r->access) / 2;
8653         if (min_el == 2 && !arm_feature(env, ARM_FEATURE_EL2)) {
8654             if (r->type & ARM_CP_EL3_NO_EL2_UNDEF) {
8655                 return;
8656             }
8657             make_const = !(r->type & ARM_CP_EL3_NO_EL2_KEEP);
8658         }
8659     } else {
8660         CPAccessRights max_el = (arm_feature(env, ARM_FEATURE_EL2)
8661                                  ? PL2_RW : PL1_RW);
8662         if ((r->access & max_el) == 0) {
8663             return;
8664         }
8665     }
8666 
8667     /* Combine cpreg and name into one allocation. */
8668     name_len = strlen(name) + 1;
8669     r2 = g_malloc(sizeof(*r2) + name_len);
8670     *r2 = *r;
8671     r2->name = memcpy(r2 + 1, name, name_len);
8672 
8673     /*
8674      * Update fields to match the instantiation, overwiting wildcards
8675      * such as CP_ANY, ARM_CP_STATE_BOTH, or ARM_CP_SECSTATE_BOTH.
8676      */
8677     r2->cp = cp;
8678     r2->crm = crm;
8679     r2->opc1 = opc1;
8680     r2->opc2 = opc2;
8681     r2->state = state;
8682     r2->secure = secstate;
8683     if (opaque) {
8684         r2->opaque = opaque;
8685     }
8686 
8687     if (make_const) {
8688         /* This should not have been a very special register to begin. */
8689         int old_special = r2->type & ARM_CP_SPECIAL_MASK;
8690         assert(old_special == 0 || old_special == ARM_CP_NOP);
8691         /*
8692          * Set the special function to CONST, retaining the other flags.
8693          * This is important for e.g. ARM_CP_SVE so that we still
8694          * take the SVE trap if CPTR_EL3.EZ == 0.
8695          */
8696         r2->type = (r2->type & ~ARM_CP_SPECIAL_MASK) | ARM_CP_CONST;
8697         /*
8698          * Usually, these registers become RES0, but there are a few
8699          * special cases like VPIDR_EL2 which have a constant non-zero
8700          * value with writes ignored.
8701          */
8702         if (!(r->type & ARM_CP_EL3_NO_EL2_C_NZ)) {
8703             r2->resetvalue = 0;
8704         }
8705         /*
8706          * ARM_CP_CONST has precedence, so removing the callbacks and
8707          * offsets are not strictly necessary, but it is potentially
8708          * less confusing to debug later.
8709          */
8710         r2->readfn = NULL;
8711         r2->writefn = NULL;
8712         r2->raw_readfn = NULL;
8713         r2->raw_writefn = NULL;
8714         r2->resetfn = NULL;
8715         r2->fieldoffset = 0;
8716         r2->bank_fieldoffsets[0] = 0;
8717         r2->bank_fieldoffsets[1] = 0;
8718     } else {
8719         bool isbanked = r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1];
8720 
8721         if (isbanked) {
8722             /*
8723              * Register is banked (using both entries in array).
8724              * Overwriting fieldoffset as the array is only used to define
8725              * banked registers but later only fieldoffset is used.
8726              */
8727             r2->fieldoffset = r->bank_fieldoffsets[ns];
8728         }
8729         if (state == ARM_CP_STATE_AA32) {
8730             if (isbanked) {
8731                 /*
8732                  * If the register is banked then we don't need to migrate or
8733                  * reset the 32-bit instance in certain cases:
8734                  *
8735                  * 1) If the register has both 32-bit and 64-bit instances
8736                  *    then we can count on the 64-bit instance taking care
8737                  *    of the non-secure bank.
8738                  * 2) If ARMv8 is enabled then we can count on a 64-bit
8739                  *    version taking care of the secure bank.  This requires
8740                  *    that separate 32 and 64-bit definitions are provided.
8741                  */
8742                 if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8743                     (arm_feature(env, ARM_FEATURE_V8) && !ns)) {
8744                     r2->type |= ARM_CP_ALIAS;
8745                 }
8746             } else if ((secstate != r->secure) && !ns) {
8747                 /*
8748                  * The register is not banked so we only want to allow
8749                  * migration of the non-secure instance.
8750                  */
8751                 r2->type |= ARM_CP_ALIAS;
8752             }
8753 
8754             if (HOST_BIG_ENDIAN &&
8755                 r->state == ARM_CP_STATE_BOTH && r2->fieldoffset) {
8756                 r2->fieldoffset += sizeof(uint32_t);
8757             }
8758         }
8759     }
8760 
8761     /*
8762      * By convention, for wildcarded registers only the first
8763      * entry is used for migration; the others are marked as
8764      * ALIAS so we don't try to transfer the register
8765      * multiple times. Special registers (ie NOP/WFI) are
8766      * never migratable and not even raw-accessible.
8767      */
8768     if (r2->type & ARM_CP_SPECIAL_MASK) {
8769         r2->type |= ARM_CP_NO_RAW;
8770     }
8771     if (((r->crm == CP_ANY) && crm != 0) ||
8772         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8773         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8774         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8775     }
8776 
8777     /*
8778      * Check that raw accesses are either forbidden or handled. Note that
8779      * we can't assert this earlier because the setup of fieldoffset for
8780      * banked registers has to be done first.
8781      */
8782     if (!(r2->type & ARM_CP_NO_RAW)) {
8783         assert(!raw_accessors_invalid(r2));
8784     }
8785 
8786     g_hash_table_insert(cpu->cp_regs, (gpointer)(uintptr_t)key, r2);
8787 }
8788 
8789 
8790 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8791                                        const ARMCPRegInfo *r, void *opaque)
8792 {
8793     /* Define implementations of coprocessor registers.
8794      * We store these in a hashtable because typically
8795      * there are less than 150 registers in a space which
8796      * is 16*16*16*8*8 = 262144 in size.
8797      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8798      * If a register is defined twice then the second definition is
8799      * used, so this can be used to define some generic registers and
8800      * then override them with implementation specific variations.
8801      * At least one of the original and the second definition should
8802      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8803      * against accidental use.
8804      *
8805      * The state field defines whether the register is to be
8806      * visible in the AArch32 or AArch64 execution state. If the
8807      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8808      * reginfo structure for the AArch32 view, which sees the lower
8809      * 32 bits of the 64 bit register.
8810      *
8811      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8812      * be wildcarded. AArch64 registers are always considered to be 64
8813      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8814      * the register, if any.
8815      */
8816     int crm, opc1, opc2;
8817     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8818     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8819     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8820     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8821     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8822     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8823     CPState state;
8824 
8825     /* 64 bit registers have only CRm and Opc1 fields */
8826     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8827     /* op0 only exists in the AArch64 encodings */
8828     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8829     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8830     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8831     /*
8832      * This API is only for Arm's system coprocessors (14 and 15) or
8833      * (M-profile or v7A-and-earlier only) for implementation defined
8834      * coprocessors in the range 0..7.  Our decode assumes this, since
8835      * 8..13 can be used for other insns including VFP and Neon. See
8836      * valid_cp() in translate.c.  Assert here that we haven't tried
8837      * to use an invalid coprocessor number.
8838      */
8839     switch (r->state) {
8840     case ARM_CP_STATE_BOTH:
8841         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8842         if (r->cp == 0) {
8843             break;
8844         }
8845         /* fall through */
8846     case ARM_CP_STATE_AA32:
8847         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8848             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8849             assert(r->cp >= 14 && r->cp <= 15);
8850         } else {
8851             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8852         }
8853         break;
8854     case ARM_CP_STATE_AA64:
8855         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8856         break;
8857     default:
8858         g_assert_not_reached();
8859     }
8860     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8861      * encodes a minimum access level for the register. We roll this
8862      * runtime check into our general permission check code, so check
8863      * here that the reginfo's specified permissions are strict enough
8864      * to encompass the generic architectural permission check.
8865      */
8866     if (r->state != ARM_CP_STATE_AA32) {
8867         CPAccessRights mask;
8868         switch (r->opc1) {
8869         case 0:
8870             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8871             mask = PL0U_R | PL1_RW;
8872             break;
8873         case 1: case 2:
8874             /* min_EL EL1 */
8875             mask = PL1_RW;
8876             break;
8877         case 3:
8878             /* min_EL EL0 */
8879             mask = PL0_RW;
8880             break;
8881         case 4:
8882         case 5:
8883             /* min_EL EL2 */
8884             mask = PL2_RW;
8885             break;
8886         case 6:
8887             /* min_EL EL3 */
8888             mask = PL3_RW;
8889             break;
8890         case 7:
8891             /* min_EL EL1, secure mode only (we don't check the latter) */
8892             mask = PL1_RW;
8893             break;
8894         default:
8895             /* broken reginfo with out-of-range opc1 */
8896             g_assert_not_reached();
8897         }
8898         /* assert our permissions are not too lax (stricter is fine) */
8899         assert((r->access & ~mask) == 0);
8900     }
8901 
8902     /* Check that the register definition has enough info to handle
8903      * reads and writes if they are permitted.
8904      */
8905     if (!(r->type & (ARM_CP_SPECIAL_MASK | ARM_CP_CONST))) {
8906         if (r->access & PL3_R) {
8907             assert((r->fieldoffset ||
8908                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8909                    r->readfn);
8910         }
8911         if (r->access & PL3_W) {
8912             assert((r->fieldoffset ||
8913                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8914                    r->writefn);
8915         }
8916     }
8917 
8918     for (crm = crmmin; crm <= crmmax; crm++) {
8919         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8920             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8921                 for (state = ARM_CP_STATE_AA32;
8922                      state <= ARM_CP_STATE_AA64; state++) {
8923                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8924                         continue;
8925                     }
8926                     if (state == ARM_CP_STATE_AA32) {
8927                         /* Under AArch32 CP registers can be common
8928                          * (same for secure and non-secure world) or banked.
8929                          */
8930                         char *name;
8931 
8932                         switch (r->secure) {
8933                         case ARM_CP_SECSTATE_S:
8934                         case ARM_CP_SECSTATE_NS:
8935                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8936                                                    r->secure, crm, opc1, opc2,
8937                                                    r->name);
8938                             break;
8939                         case ARM_CP_SECSTATE_BOTH:
8940                             name = g_strdup_printf("%s_S", r->name);
8941                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8942                                                    ARM_CP_SECSTATE_S,
8943                                                    crm, opc1, opc2, name);
8944                             g_free(name);
8945                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8946                                                    ARM_CP_SECSTATE_NS,
8947                                                    crm, opc1, opc2, r->name);
8948                             break;
8949                         default:
8950                             g_assert_not_reached();
8951                         }
8952                     } else {
8953                         /* AArch64 registers get mapped to non-secure instance
8954                          * of AArch32 */
8955                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8956                                                ARM_CP_SECSTATE_NS,
8957                                                crm, opc1, opc2, r->name);
8958                     }
8959                 }
8960             }
8961         }
8962     }
8963 }
8964 
8965 /* Define a whole list of registers */
8966 void define_arm_cp_regs_with_opaque_len(ARMCPU *cpu, const ARMCPRegInfo *regs,
8967                                         void *opaque, size_t len)
8968 {
8969     size_t i;
8970     for (i = 0; i < len; ++i) {
8971         define_one_arm_cp_reg_with_opaque(cpu, regs + i, opaque);
8972     }
8973 }
8974 
8975 /*
8976  * Modify ARMCPRegInfo for access from userspace.
8977  *
8978  * This is a data driven modification directed by
8979  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8980  * user-space cannot alter any values and dynamic values pertaining to
8981  * execution state are hidden from user space view anyway.
8982  */
8983 void modify_arm_cp_regs_with_len(ARMCPRegInfo *regs, size_t regs_len,
8984                                  const ARMCPRegUserSpaceInfo *mods,
8985                                  size_t mods_len)
8986 {
8987     for (size_t mi = 0; mi < mods_len; ++mi) {
8988         const ARMCPRegUserSpaceInfo *m = mods + mi;
8989         GPatternSpec *pat = NULL;
8990 
8991         if (m->is_glob) {
8992             pat = g_pattern_spec_new(m->name);
8993         }
8994         for (size_t ri = 0; ri < regs_len; ++ri) {
8995             ARMCPRegInfo *r = regs + ri;
8996 
8997             if (pat && g_pattern_match_string(pat, r->name)) {
8998                 r->type = ARM_CP_CONST;
8999                 r->access = PL0U_R;
9000                 r->resetvalue = 0;
9001                 /* continue */
9002             } else if (strcmp(r->name, m->name) == 0) {
9003                 r->type = ARM_CP_CONST;
9004                 r->access = PL0U_R;
9005                 r->resetvalue &= m->exported_bits;
9006                 r->resetvalue |= m->fixed_bits;
9007                 break;
9008             }
9009         }
9010         if (pat) {
9011             g_pattern_spec_free(pat);
9012         }
9013     }
9014 }
9015 
9016 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
9017 {
9018     return g_hash_table_lookup(cpregs, (gpointer)(uintptr_t)encoded_cp);
9019 }
9020 
9021 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
9022                          uint64_t value)
9023 {
9024     /* Helper coprocessor write function for write-ignore registers */
9025 }
9026 
9027 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
9028 {
9029     /* Helper coprocessor write function for read-as-zero registers */
9030     return 0;
9031 }
9032 
9033 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
9034 {
9035     /* Helper coprocessor reset function for do-nothing-on-reset registers */
9036 }
9037 
9038 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
9039 {
9040     /* Return true if it is not valid for us to switch to
9041      * this CPU mode (ie all the UNPREDICTABLE cases in
9042      * the ARM ARM CPSRWriteByInstr pseudocode).
9043      */
9044 
9045     /* Changes to or from Hyp via MSR and CPS are illegal. */
9046     if (write_type == CPSRWriteByInstr &&
9047         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
9048          mode == ARM_CPU_MODE_HYP)) {
9049         return 1;
9050     }
9051 
9052     switch (mode) {
9053     case ARM_CPU_MODE_USR:
9054         return 0;
9055     case ARM_CPU_MODE_SYS:
9056     case ARM_CPU_MODE_SVC:
9057     case ARM_CPU_MODE_ABT:
9058     case ARM_CPU_MODE_UND:
9059     case ARM_CPU_MODE_IRQ:
9060     case ARM_CPU_MODE_FIQ:
9061         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
9062          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
9063          */
9064         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
9065          * and CPS are treated as illegal mode changes.
9066          */
9067         if (write_type == CPSRWriteByInstr &&
9068             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
9069             (arm_hcr_el2_eff(env) & HCR_TGE)) {
9070             return 1;
9071         }
9072         return 0;
9073     case ARM_CPU_MODE_HYP:
9074         return !arm_is_el2_enabled(env) || arm_current_el(env) < 2;
9075     case ARM_CPU_MODE_MON:
9076         return arm_current_el(env) < 3;
9077     default:
9078         return 1;
9079     }
9080 }
9081 
9082 uint32_t cpsr_read(CPUARMState *env)
9083 {
9084     int ZF;
9085     ZF = (env->ZF == 0);
9086     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
9087         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
9088         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
9089         | ((env->condexec_bits & 0xfc) << 8)
9090         | (env->GE << 16) | (env->daif & CPSR_AIF);
9091 }
9092 
9093 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
9094                 CPSRWriteType write_type)
9095 {
9096     uint32_t changed_daif;
9097     bool rebuild_hflags = (write_type != CPSRWriteRaw) &&
9098         (mask & (CPSR_M | CPSR_E | CPSR_IL));
9099 
9100     if (mask & CPSR_NZCV) {
9101         env->ZF = (~val) & CPSR_Z;
9102         env->NF = val;
9103         env->CF = (val >> 29) & 1;
9104         env->VF = (val << 3) & 0x80000000;
9105     }
9106     if (mask & CPSR_Q)
9107         env->QF = ((val & CPSR_Q) != 0);
9108     if (mask & CPSR_T)
9109         env->thumb = ((val & CPSR_T) != 0);
9110     if (mask & CPSR_IT_0_1) {
9111         env->condexec_bits &= ~3;
9112         env->condexec_bits |= (val >> 25) & 3;
9113     }
9114     if (mask & CPSR_IT_2_7) {
9115         env->condexec_bits &= 3;
9116         env->condexec_bits |= (val >> 8) & 0xfc;
9117     }
9118     if (mask & CPSR_GE) {
9119         env->GE = (val >> 16) & 0xf;
9120     }
9121 
9122     /* In a V7 implementation that includes the security extensions but does
9123      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
9124      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
9125      * bits respectively.
9126      *
9127      * In a V8 implementation, it is permitted for privileged software to
9128      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
9129      */
9130     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
9131         arm_feature(env, ARM_FEATURE_EL3) &&
9132         !arm_feature(env, ARM_FEATURE_EL2) &&
9133         !arm_is_secure(env)) {
9134 
9135         changed_daif = (env->daif ^ val) & mask;
9136 
9137         if (changed_daif & CPSR_A) {
9138             /* Check to see if we are allowed to change the masking of async
9139              * abort exceptions from a non-secure state.
9140              */
9141             if (!(env->cp15.scr_el3 & SCR_AW)) {
9142                 qemu_log_mask(LOG_GUEST_ERROR,
9143                               "Ignoring attempt to switch CPSR_A flag from "
9144                               "non-secure world with SCR.AW bit clear\n");
9145                 mask &= ~CPSR_A;
9146             }
9147         }
9148 
9149         if (changed_daif & CPSR_F) {
9150             /* Check to see if we are allowed to change the masking of FIQ
9151              * exceptions from a non-secure state.
9152              */
9153             if (!(env->cp15.scr_el3 & SCR_FW)) {
9154                 qemu_log_mask(LOG_GUEST_ERROR,
9155                               "Ignoring attempt to switch CPSR_F flag from "
9156                               "non-secure world with SCR.FW bit clear\n");
9157                 mask &= ~CPSR_F;
9158             }
9159 
9160             /* Check whether non-maskable FIQ (NMFI) support is enabled.
9161              * If this bit is set software is not allowed to mask
9162              * FIQs, but is allowed to set CPSR_F to 0.
9163              */
9164             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
9165                 (val & CPSR_F)) {
9166                 qemu_log_mask(LOG_GUEST_ERROR,
9167                               "Ignoring attempt to enable CPSR_F flag "
9168                               "(non-maskable FIQ [NMFI] support enabled)\n");
9169                 mask &= ~CPSR_F;
9170             }
9171         }
9172     }
9173 
9174     env->daif &= ~(CPSR_AIF & mask);
9175     env->daif |= val & CPSR_AIF & mask;
9176 
9177     if (write_type != CPSRWriteRaw &&
9178         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
9179         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
9180             /* Note that we can only get here in USR mode if this is a
9181              * gdb stub write; for this case we follow the architectural
9182              * behaviour for guest writes in USR mode of ignoring an attempt
9183              * to switch mode. (Those are caught by translate.c for writes
9184              * triggered by guest instructions.)
9185              */
9186             mask &= ~CPSR_M;
9187         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
9188             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
9189              * v7, and has defined behaviour in v8:
9190              *  + leave CPSR.M untouched
9191              *  + allow changes to the other CPSR fields
9192              *  + set PSTATE.IL
9193              * For user changes via the GDB stub, we don't set PSTATE.IL,
9194              * as this would be unnecessarily harsh for a user error.
9195              */
9196             mask &= ~CPSR_M;
9197             if (write_type != CPSRWriteByGDBStub &&
9198                 arm_feature(env, ARM_FEATURE_V8)) {
9199                 mask |= CPSR_IL;
9200                 val |= CPSR_IL;
9201             }
9202             qemu_log_mask(LOG_GUEST_ERROR,
9203                           "Illegal AArch32 mode switch attempt from %s to %s\n",
9204                           aarch32_mode_name(env->uncached_cpsr),
9205                           aarch32_mode_name(val));
9206         } else {
9207             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
9208                           write_type == CPSRWriteExceptionReturn ?
9209                           "Exception return from AArch32" :
9210                           "AArch32 mode switch from",
9211                           aarch32_mode_name(env->uncached_cpsr),
9212                           aarch32_mode_name(val), env->regs[15]);
9213             switch_mode(env, val & CPSR_M);
9214         }
9215     }
9216     mask &= ~CACHED_CPSR_BITS;
9217     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
9218     if (rebuild_hflags) {
9219         arm_rebuild_hflags(env);
9220     }
9221 }
9222 
9223 /* Sign/zero extend */
9224 uint32_t HELPER(sxtb16)(uint32_t x)
9225 {
9226     uint32_t res;
9227     res = (uint16_t)(int8_t)x;
9228     res |= (uint32_t)(int8_t)(x >> 16) << 16;
9229     return res;
9230 }
9231 
9232 static void handle_possible_div0_trap(CPUARMState *env, uintptr_t ra)
9233 {
9234     /*
9235      * Take a division-by-zero exception if necessary; otherwise return
9236      * to get the usual non-trapping division behaviour (result of 0)
9237      */
9238     if (arm_feature(env, ARM_FEATURE_M)
9239         && (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_DIV_0_TRP_MASK)) {
9240         raise_exception_ra(env, EXCP_DIVBYZERO, 0, 1, ra);
9241     }
9242 }
9243 
9244 uint32_t HELPER(uxtb16)(uint32_t x)
9245 {
9246     uint32_t res;
9247     res = (uint16_t)(uint8_t)x;
9248     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
9249     return res;
9250 }
9251 
9252 int32_t HELPER(sdiv)(CPUARMState *env, int32_t num, int32_t den)
9253 {
9254     if (den == 0) {
9255         handle_possible_div0_trap(env, GETPC());
9256         return 0;
9257     }
9258     if (num == INT_MIN && den == -1) {
9259         return INT_MIN;
9260     }
9261     return num / den;
9262 }
9263 
9264 uint32_t HELPER(udiv)(CPUARMState *env, uint32_t num, uint32_t den)
9265 {
9266     if (den == 0) {
9267         handle_possible_div0_trap(env, GETPC());
9268         return 0;
9269     }
9270     return num / den;
9271 }
9272 
9273 uint32_t HELPER(rbit)(uint32_t x)
9274 {
9275     return revbit32(x);
9276 }
9277 
9278 #ifdef CONFIG_USER_ONLY
9279 
9280 static void switch_mode(CPUARMState *env, int mode)
9281 {
9282     ARMCPU *cpu = env_archcpu(env);
9283 
9284     if (mode != ARM_CPU_MODE_USR) {
9285         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
9286     }
9287 }
9288 
9289 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9290                                  uint32_t cur_el, bool secure)
9291 {
9292     return 1;
9293 }
9294 
9295 void aarch64_sync_64_to_32(CPUARMState *env)
9296 {
9297     g_assert_not_reached();
9298 }
9299 
9300 #else
9301 
9302 static void switch_mode(CPUARMState *env, int mode)
9303 {
9304     int old_mode;
9305     int i;
9306 
9307     old_mode = env->uncached_cpsr & CPSR_M;
9308     if (mode == old_mode)
9309         return;
9310 
9311     if (old_mode == ARM_CPU_MODE_FIQ) {
9312         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
9313         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
9314     } else if (mode == ARM_CPU_MODE_FIQ) {
9315         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
9316         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
9317     }
9318 
9319     i = bank_number(old_mode);
9320     env->banked_r13[i] = env->regs[13];
9321     env->banked_spsr[i] = env->spsr;
9322 
9323     i = bank_number(mode);
9324     env->regs[13] = env->banked_r13[i];
9325     env->spsr = env->banked_spsr[i];
9326 
9327     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
9328     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
9329 }
9330 
9331 /* Physical Interrupt Target EL Lookup Table
9332  *
9333  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
9334  *
9335  * The below multi-dimensional table is used for looking up the target
9336  * exception level given numerous condition criteria.  Specifically, the
9337  * target EL is based on SCR and HCR routing controls as well as the
9338  * currently executing EL and secure state.
9339  *
9340  *    Dimensions:
9341  *    target_el_table[2][2][2][2][2][4]
9342  *                    |  |  |  |  |  +--- Current EL
9343  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
9344  *                    |  |  |  +--------- HCR mask override
9345  *                    |  |  +------------ SCR exec state control
9346  *                    |  +--------------- SCR mask override
9347  *                    +------------------ 32-bit(0)/64-bit(1) EL3
9348  *
9349  *    The table values are as such:
9350  *    0-3 = EL0-EL3
9351  *     -1 = Cannot occur
9352  *
9353  * The ARM ARM target EL table includes entries indicating that an "exception
9354  * is not taken".  The two cases where this is applicable are:
9355  *    1) An exception is taken from EL3 but the SCR does not have the exception
9356  *    routed to EL3.
9357  *    2) An exception is taken from EL2 but the HCR does not have the exception
9358  *    routed to EL2.
9359  * In these two cases, the below table contain a target of EL1.  This value is
9360  * returned as it is expected that the consumer of the table data will check
9361  * for "target EL >= current EL" to ensure the exception is not taken.
9362  *
9363  *            SCR     HCR
9364  *         64  EA     AMO                 From
9365  *        BIT IRQ     IMO      Non-secure         Secure
9366  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
9367  */
9368 static const int8_t target_el_table[2][2][2][2][2][4] = {
9369     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9370        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
9371       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9372        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
9373      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9374        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
9375       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9376        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
9377     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
9378        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 2,  2, -1,  1 },},},
9379       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1,  1,  1 },},
9380        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 2,  2,  2,  1 },},},},
9381      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
9382        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
9383       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},
9384        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},},},},
9385 };
9386 
9387 /*
9388  * Determine the target EL for physical exceptions
9389  */
9390 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9391                                  uint32_t cur_el, bool secure)
9392 {
9393     CPUARMState *env = cs->env_ptr;
9394     bool rw;
9395     bool scr;
9396     bool hcr;
9397     int target_el;
9398     /* Is the highest EL AArch64? */
9399     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9400     uint64_t hcr_el2;
9401 
9402     if (arm_feature(env, ARM_FEATURE_EL3)) {
9403         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9404     } else {
9405         /* Either EL2 is the highest EL (and so the EL2 register width
9406          * is given by is64); or there is no EL2 or EL3, in which case
9407          * the value of 'rw' does not affect the table lookup anyway.
9408          */
9409         rw = is64;
9410     }
9411 
9412     hcr_el2 = arm_hcr_el2_eff(env);
9413     switch (excp_idx) {
9414     case EXCP_IRQ:
9415         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9416         hcr = hcr_el2 & HCR_IMO;
9417         break;
9418     case EXCP_FIQ:
9419         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9420         hcr = hcr_el2 & HCR_FMO;
9421         break;
9422     default:
9423         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9424         hcr = hcr_el2 & HCR_AMO;
9425         break;
9426     };
9427 
9428     /*
9429      * For these purposes, TGE and AMO/IMO/FMO both force the
9430      * interrupt to EL2.  Fold TGE into the bit extracted above.
9431      */
9432     hcr |= (hcr_el2 & HCR_TGE) != 0;
9433 
9434     /* Perform a table-lookup for the target EL given the current state */
9435     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9436 
9437     assert(target_el > 0);
9438 
9439     return target_el;
9440 }
9441 
9442 void arm_log_exception(CPUState *cs)
9443 {
9444     int idx = cs->exception_index;
9445 
9446     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9447         const char *exc = NULL;
9448         static const char * const excnames[] = {
9449             [EXCP_UDEF] = "Undefined Instruction",
9450             [EXCP_SWI] = "SVC",
9451             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9452             [EXCP_DATA_ABORT] = "Data Abort",
9453             [EXCP_IRQ] = "IRQ",
9454             [EXCP_FIQ] = "FIQ",
9455             [EXCP_BKPT] = "Breakpoint",
9456             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9457             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9458             [EXCP_HVC] = "Hypervisor Call",
9459             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9460             [EXCP_SMC] = "Secure Monitor Call",
9461             [EXCP_VIRQ] = "Virtual IRQ",
9462             [EXCP_VFIQ] = "Virtual FIQ",
9463             [EXCP_SEMIHOST] = "Semihosting call",
9464             [EXCP_NOCP] = "v7M NOCP UsageFault",
9465             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9466             [EXCP_STKOF] = "v8M STKOF UsageFault",
9467             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9468             [EXCP_LSERR] = "v8M LSERR UsageFault",
9469             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9470             [EXCP_DIVBYZERO] = "v7M DIVBYZERO UsageFault",
9471             [EXCP_VSERR] = "Virtual SERR",
9472         };
9473 
9474         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9475             exc = excnames[idx];
9476         }
9477         if (!exc) {
9478             exc = "unknown";
9479         }
9480         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s] on CPU %d\n",
9481                       idx, exc, cs->cpu_index);
9482     }
9483 }
9484 
9485 /*
9486  * Function used to synchronize QEMU's AArch64 register set with AArch32
9487  * register set.  This is necessary when switching between AArch32 and AArch64
9488  * execution state.
9489  */
9490 void aarch64_sync_32_to_64(CPUARMState *env)
9491 {
9492     int i;
9493     uint32_t mode = env->uncached_cpsr & CPSR_M;
9494 
9495     /* We can blanket copy R[0:7] to X[0:7] */
9496     for (i = 0; i < 8; i++) {
9497         env->xregs[i] = env->regs[i];
9498     }
9499 
9500     /*
9501      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9502      * Otherwise, they come from the banked user regs.
9503      */
9504     if (mode == ARM_CPU_MODE_FIQ) {
9505         for (i = 8; i < 13; i++) {
9506             env->xregs[i] = env->usr_regs[i - 8];
9507         }
9508     } else {
9509         for (i = 8; i < 13; i++) {
9510             env->xregs[i] = env->regs[i];
9511         }
9512     }
9513 
9514     /*
9515      * Registers x13-x23 are the various mode SP and FP registers. Registers
9516      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9517      * from the mode banked register.
9518      */
9519     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9520         env->xregs[13] = env->regs[13];
9521         env->xregs[14] = env->regs[14];
9522     } else {
9523         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9524         /* HYP is an exception in that it is copied from r14 */
9525         if (mode == ARM_CPU_MODE_HYP) {
9526             env->xregs[14] = env->regs[14];
9527         } else {
9528             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9529         }
9530     }
9531 
9532     if (mode == ARM_CPU_MODE_HYP) {
9533         env->xregs[15] = env->regs[13];
9534     } else {
9535         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9536     }
9537 
9538     if (mode == ARM_CPU_MODE_IRQ) {
9539         env->xregs[16] = env->regs[14];
9540         env->xregs[17] = env->regs[13];
9541     } else {
9542         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9543         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9544     }
9545 
9546     if (mode == ARM_CPU_MODE_SVC) {
9547         env->xregs[18] = env->regs[14];
9548         env->xregs[19] = env->regs[13];
9549     } else {
9550         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9551         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9552     }
9553 
9554     if (mode == ARM_CPU_MODE_ABT) {
9555         env->xregs[20] = env->regs[14];
9556         env->xregs[21] = env->regs[13];
9557     } else {
9558         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9559         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9560     }
9561 
9562     if (mode == ARM_CPU_MODE_UND) {
9563         env->xregs[22] = env->regs[14];
9564         env->xregs[23] = env->regs[13];
9565     } else {
9566         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9567         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9568     }
9569 
9570     /*
9571      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9572      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9573      * FIQ bank for r8-r14.
9574      */
9575     if (mode == ARM_CPU_MODE_FIQ) {
9576         for (i = 24; i < 31; i++) {
9577             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9578         }
9579     } else {
9580         for (i = 24; i < 29; i++) {
9581             env->xregs[i] = env->fiq_regs[i - 24];
9582         }
9583         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9584         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9585     }
9586 
9587     env->pc = env->regs[15];
9588 }
9589 
9590 /*
9591  * Function used to synchronize QEMU's AArch32 register set with AArch64
9592  * register set.  This is necessary when switching between AArch32 and AArch64
9593  * execution state.
9594  */
9595 void aarch64_sync_64_to_32(CPUARMState *env)
9596 {
9597     int i;
9598     uint32_t mode = env->uncached_cpsr & CPSR_M;
9599 
9600     /* We can blanket copy X[0:7] to R[0:7] */
9601     for (i = 0; i < 8; i++) {
9602         env->regs[i] = env->xregs[i];
9603     }
9604 
9605     /*
9606      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9607      * Otherwise, we copy x8-x12 into the banked user regs.
9608      */
9609     if (mode == ARM_CPU_MODE_FIQ) {
9610         for (i = 8; i < 13; i++) {
9611             env->usr_regs[i - 8] = env->xregs[i];
9612         }
9613     } else {
9614         for (i = 8; i < 13; i++) {
9615             env->regs[i] = env->xregs[i];
9616         }
9617     }
9618 
9619     /*
9620      * Registers r13 & r14 depend on the current mode.
9621      * If we are in a given mode, we copy the corresponding x registers to r13
9622      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9623      * for the mode.
9624      */
9625     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9626         env->regs[13] = env->xregs[13];
9627         env->regs[14] = env->xregs[14];
9628     } else {
9629         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9630 
9631         /*
9632          * HYP is an exception in that it does not have its own banked r14 but
9633          * shares the USR r14
9634          */
9635         if (mode == ARM_CPU_MODE_HYP) {
9636             env->regs[14] = env->xregs[14];
9637         } else {
9638             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9639         }
9640     }
9641 
9642     if (mode == ARM_CPU_MODE_HYP) {
9643         env->regs[13] = env->xregs[15];
9644     } else {
9645         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9646     }
9647 
9648     if (mode == ARM_CPU_MODE_IRQ) {
9649         env->regs[14] = env->xregs[16];
9650         env->regs[13] = env->xregs[17];
9651     } else {
9652         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9653         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9654     }
9655 
9656     if (mode == ARM_CPU_MODE_SVC) {
9657         env->regs[14] = env->xregs[18];
9658         env->regs[13] = env->xregs[19];
9659     } else {
9660         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9661         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9662     }
9663 
9664     if (mode == ARM_CPU_MODE_ABT) {
9665         env->regs[14] = env->xregs[20];
9666         env->regs[13] = env->xregs[21];
9667     } else {
9668         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9669         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9670     }
9671 
9672     if (mode == ARM_CPU_MODE_UND) {
9673         env->regs[14] = env->xregs[22];
9674         env->regs[13] = env->xregs[23];
9675     } else {
9676         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9677         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9678     }
9679 
9680     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9681      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9682      * FIQ bank for r8-r14.
9683      */
9684     if (mode == ARM_CPU_MODE_FIQ) {
9685         for (i = 24; i < 31; i++) {
9686             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9687         }
9688     } else {
9689         for (i = 24; i < 29; i++) {
9690             env->fiq_regs[i - 24] = env->xregs[i];
9691         }
9692         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9693         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9694     }
9695 
9696     env->regs[15] = env->pc;
9697 }
9698 
9699 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9700                                    uint32_t mask, uint32_t offset,
9701                                    uint32_t newpc)
9702 {
9703     int new_el;
9704 
9705     /* Change the CPU state so as to actually take the exception. */
9706     switch_mode(env, new_mode);
9707 
9708     /*
9709      * For exceptions taken to AArch32 we must clear the SS bit in both
9710      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9711      */
9712     env->pstate &= ~PSTATE_SS;
9713     env->spsr = cpsr_read(env);
9714     /* Clear IT bits.  */
9715     env->condexec_bits = 0;
9716     /* Switch to the new mode, and to the correct instruction set.  */
9717     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9718 
9719     /* This must be after mode switching. */
9720     new_el = arm_current_el(env);
9721 
9722     /* Set new mode endianness */
9723     env->uncached_cpsr &= ~CPSR_E;
9724     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9725         env->uncached_cpsr |= CPSR_E;
9726     }
9727     /* J and IL must always be cleared for exception entry */
9728     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9729     env->daif |= mask;
9730 
9731     if (cpu_isar_feature(aa32_ssbs, env_archcpu(env))) {
9732         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_32) {
9733             env->uncached_cpsr |= CPSR_SSBS;
9734         } else {
9735             env->uncached_cpsr &= ~CPSR_SSBS;
9736         }
9737     }
9738 
9739     if (new_mode == ARM_CPU_MODE_HYP) {
9740         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9741         env->elr_el[2] = env->regs[15];
9742     } else {
9743         /* CPSR.PAN is normally preserved preserved unless...  */
9744         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9745             switch (new_el) {
9746             case 3:
9747                 if (!arm_is_secure_below_el3(env)) {
9748                     /* ... the target is EL3, from non-secure state.  */
9749                     env->uncached_cpsr &= ~CPSR_PAN;
9750                     break;
9751                 }
9752                 /* ... the target is EL3, from secure state ... */
9753                 /* fall through */
9754             case 1:
9755                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9756                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9757                     env->uncached_cpsr |= CPSR_PAN;
9758                 }
9759                 break;
9760             }
9761         }
9762         /*
9763          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9764          * and we should just guard the thumb mode on V4
9765          */
9766         if (arm_feature(env, ARM_FEATURE_V4T)) {
9767             env->thumb =
9768                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9769         }
9770         env->regs[14] = env->regs[15] + offset;
9771     }
9772     env->regs[15] = newpc;
9773     arm_rebuild_hflags(env);
9774 }
9775 
9776 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9777 {
9778     /*
9779      * Handle exception entry to Hyp mode; this is sufficiently
9780      * different to entry to other AArch32 modes that we handle it
9781      * separately here.
9782      *
9783      * The vector table entry used is always the 0x14 Hyp mode entry point,
9784      * unless this is an UNDEF/SVC/HVC/abort taken from Hyp to Hyp.
9785      * The offset applied to the preferred return address is always zero
9786      * (see DDI0487C.a section G1.12.3).
9787      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9788      */
9789     uint32_t addr, mask;
9790     ARMCPU *cpu = ARM_CPU(cs);
9791     CPUARMState *env = &cpu->env;
9792 
9793     switch (cs->exception_index) {
9794     case EXCP_UDEF:
9795         addr = 0x04;
9796         break;
9797     case EXCP_SWI:
9798         addr = 0x08;
9799         break;
9800     case EXCP_BKPT:
9801         /* Fall through to prefetch abort.  */
9802     case EXCP_PREFETCH_ABORT:
9803         env->cp15.ifar_s = env->exception.vaddress;
9804         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9805                       (uint32_t)env->exception.vaddress);
9806         addr = 0x0c;
9807         break;
9808     case EXCP_DATA_ABORT:
9809         env->cp15.dfar_s = env->exception.vaddress;
9810         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9811                       (uint32_t)env->exception.vaddress);
9812         addr = 0x10;
9813         break;
9814     case EXCP_IRQ:
9815         addr = 0x18;
9816         break;
9817     case EXCP_FIQ:
9818         addr = 0x1c;
9819         break;
9820     case EXCP_HVC:
9821         addr = 0x08;
9822         break;
9823     case EXCP_HYP_TRAP:
9824         addr = 0x14;
9825         break;
9826     default:
9827         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9828     }
9829 
9830     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9831         if (!arm_feature(env, ARM_FEATURE_V8)) {
9832             /*
9833              * QEMU syndrome values are v8-style. v7 has the IL bit
9834              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9835              * If this is a v7 CPU, squash the IL bit in those cases.
9836              */
9837             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9838                 (cs->exception_index == EXCP_DATA_ABORT &&
9839                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9840                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9841                 env->exception.syndrome &= ~ARM_EL_IL;
9842             }
9843         }
9844         env->cp15.esr_el[2] = env->exception.syndrome;
9845     }
9846 
9847     if (arm_current_el(env) != 2 && addr < 0x14) {
9848         addr = 0x14;
9849     }
9850 
9851     mask = 0;
9852     if (!(env->cp15.scr_el3 & SCR_EA)) {
9853         mask |= CPSR_A;
9854     }
9855     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9856         mask |= CPSR_I;
9857     }
9858     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9859         mask |= CPSR_F;
9860     }
9861 
9862     addr += env->cp15.hvbar;
9863 
9864     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9865 }
9866 
9867 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9868 {
9869     ARMCPU *cpu = ARM_CPU(cs);
9870     CPUARMState *env = &cpu->env;
9871     uint32_t addr;
9872     uint32_t mask;
9873     int new_mode;
9874     uint32_t offset;
9875     uint32_t moe;
9876 
9877     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9878     switch (syn_get_ec(env->exception.syndrome)) {
9879     case EC_BREAKPOINT:
9880     case EC_BREAKPOINT_SAME_EL:
9881         moe = 1;
9882         break;
9883     case EC_WATCHPOINT:
9884     case EC_WATCHPOINT_SAME_EL:
9885         moe = 10;
9886         break;
9887     case EC_AA32_BKPT:
9888         moe = 3;
9889         break;
9890     case EC_VECTORCATCH:
9891         moe = 5;
9892         break;
9893     default:
9894         moe = 0;
9895         break;
9896     }
9897 
9898     if (moe) {
9899         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9900     }
9901 
9902     if (env->exception.target_el == 2) {
9903         arm_cpu_do_interrupt_aarch32_hyp(cs);
9904         return;
9905     }
9906 
9907     switch (cs->exception_index) {
9908     case EXCP_UDEF:
9909         new_mode = ARM_CPU_MODE_UND;
9910         addr = 0x04;
9911         mask = CPSR_I;
9912         if (env->thumb)
9913             offset = 2;
9914         else
9915             offset = 4;
9916         break;
9917     case EXCP_SWI:
9918         new_mode = ARM_CPU_MODE_SVC;
9919         addr = 0x08;
9920         mask = CPSR_I;
9921         /* The PC already points to the next instruction.  */
9922         offset = 0;
9923         break;
9924     case EXCP_BKPT:
9925         /* Fall through to prefetch abort.  */
9926     case EXCP_PREFETCH_ABORT:
9927         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9928         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9929         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9930                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9931         new_mode = ARM_CPU_MODE_ABT;
9932         addr = 0x0c;
9933         mask = CPSR_A | CPSR_I;
9934         offset = 4;
9935         break;
9936     case EXCP_DATA_ABORT:
9937         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9938         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9939         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9940                       env->exception.fsr,
9941                       (uint32_t)env->exception.vaddress);
9942         new_mode = ARM_CPU_MODE_ABT;
9943         addr = 0x10;
9944         mask = CPSR_A | CPSR_I;
9945         offset = 8;
9946         break;
9947     case EXCP_IRQ:
9948         new_mode = ARM_CPU_MODE_IRQ;
9949         addr = 0x18;
9950         /* Disable IRQ and imprecise data aborts.  */
9951         mask = CPSR_A | CPSR_I;
9952         offset = 4;
9953         if (env->cp15.scr_el3 & SCR_IRQ) {
9954             /* IRQ routed to monitor mode */
9955             new_mode = ARM_CPU_MODE_MON;
9956             mask |= CPSR_F;
9957         }
9958         break;
9959     case EXCP_FIQ:
9960         new_mode = ARM_CPU_MODE_FIQ;
9961         addr = 0x1c;
9962         /* Disable FIQ, IRQ and imprecise data aborts.  */
9963         mask = CPSR_A | CPSR_I | CPSR_F;
9964         if (env->cp15.scr_el3 & SCR_FIQ) {
9965             /* FIQ routed to monitor mode */
9966             new_mode = ARM_CPU_MODE_MON;
9967         }
9968         offset = 4;
9969         break;
9970     case EXCP_VIRQ:
9971         new_mode = ARM_CPU_MODE_IRQ;
9972         addr = 0x18;
9973         /* Disable IRQ and imprecise data aborts.  */
9974         mask = CPSR_A | CPSR_I;
9975         offset = 4;
9976         break;
9977     case EXCP_VFIQ:
9978         new_mode = ARM_CPU_MODE_FIQ;
9979         addr = 0x1c;
9980         /* Disable FIQ, IRQ and imprecise data aborts.  */
9981         mask = CPSR_A | CPSR_I | CPSR_F;
9982         offset = 4;
9983         break;
9984     case EXCP_VSERR:
9985         {
9986             /*
9987              * Note that this is reported as a data abort, but the DFAR
9988              * has an UNKNOWN value.  Construct the SError syndrome from
9989              * AET and ExT fields.
9990              */
9991             ARMMMUFaultInfo fi = { .type = ARMFault_AsyncExternal, };
9992 
9993             if (extended_addresses_enabled(env)) {
9994                 env->exception.fsr = arm_fi_to_lfsc(&fi);
9995             } else {
9996                 env->exception.fsr = arm_fi_to_sfsc(&fi);
9997             }
9998             env->exception.fsr |= env->cp15.vsesr_el2 & 0xd000;
9999             A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
10000             qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x\n",
10001                           env->exception.fsr);
10002 
10003             new_mode = ARM_CPU_MODE_ABT;
10004             addr = 0x10;
10005             mask = CPSR_A | CPSR_I;
10006             offset = 8;
10007         }
10008         break;
10009     case EXCP_SMC:
10010         new_mode = ARM_CPU_MODE_MON;
10011         addr = 0x08;
10012         mask = CPSR_A | CPSR_I | CPSR_F;
10013         offset = 0;
10014         break;
10015     default:
10016         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10017         return; /* Never happens.  Keep compiler happy.  */
10018     }
10019 
10020     if (new_mode == ARM_CPU_MODE_MON) {
10021         addr += env->cp15.mvbar;
10022     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
10023         /* High vectors. When enabled, base address cannot be remapped. */
10024         addr += 0xffff0000;
10025     } else {
10026         /* ARM v7 architectures provide a vector base address register to remap
10027          * the interrupt vector table.
10028          * This register is only followed in non-monitor mode, and is banked.
10029          * Note: only bits 31:5 are valid.
10030          */
10031         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
10032     }
10033 
10034     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
10035         env->cp15.scr_el3 &= ~SCR_NS;
10036     }
10037 
10038     take_aarch32_exception(env, new_mode, mask, offset, addr);
10039 }
10040 
10041 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
10042 {
10043     /*
10044      * Return the register number of the AArch64 view of the AArch32
10045      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
10046      * be that of the AArch32 mode the exception came from.
10047      */
10048     int mode = env->uncached_cpsr & CPSR_M;
10049 
10050     switch (aarch32_reg) {
10051     case 0 ... 7:
10052         return aarch32_reg;
10053     case 8 ... 12:
10054         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
10055     case 13:
10056         switch (mode) {
10057         case ARM_CPU_MODE_USR:
10058         case ARM_CPU_MODE_SYS:
10059             return 13;
10060         case ARM_CPU_MODE_HYP:
10061             return 15;
10062         case ARM_CPU_MODE_IRQ:
10063             return 17;
10064         case ARM_CPU_MODE_SVC:
10065             return 19;
10066         case ARM_CPU_MODE_ABT:
10067             return 21;
10068         case ARM_CPU_MODE_UND:
10069             return 23;
10070         case ARM_CPU_MODE_FIQ:
10071             return 29;
10072         default:
10073             g_assert_not_reached();
10074         }
10075     case 14:
10076         switch (mode) {
10077         case ARM_CPU_MODE_USR:
10078         case ARM_CPU_MODE_SYS:
10079         case ARM_CPU_MODE_HYP:
10080             return 14;
10081         case ARM_CPU_MODE_IRQ:
10082             return 16;
10083         case ARM_CPU_MODE_SVC:
10084             return 18;
10085         case ARM_CPU_MODE_ABT:
10086             return 20;
10087         case ARM_CPU_MODE_UND:
10088             return 22;
10089         case ARM_CPU_MODE_FIQ:
10090             return 30;
10091         default:
10092             g_assert_not_reached();
10093         }
10094     case 15:
10095         return 31;
10096     default:
10097         g_assert_not_reached();
10098     }
10099 }
10100 
10101 static uint32_t cpsr_read_for_spsr_elx(CPUARMState *env)
10102 {
10103     uint32_t ret = cpsr_read(env);
10104 
10105     /* Move DIT to the correct location for SPSR_ELx */
10106     if (ret & CPSR_DIT) {
10107         ret &= ~CPSR_DIT;
10108         ret |= PSTATE_DIT;
10109     }
10110     /* Merge PSTATE.SS into SPSR_ELx */
10111     ret |= env->pstate & PSTATE_SS;
10112 
10113     return ret;
10114 }
10115 
10116 /* Handle exception entry to a target EL which is using AArch64 */
10117 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
10118 {
10119     ARMCPU *cpu = ARM_CPU(cs);
10120     CPUARMState *env = &cpu->env;
10121     unsigned int new_el = env->exception.target_el;
10122     target_ulong addr = env->cp15.vbar_el[new_el];
10123     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
10124     unsigned int old_mode;
10125     unsigned int cur_el = arm_current_el(env);
10126     int rt;
10127 
10128     /*
10129      * Note that new_el can never be 0.  If cur_el is 0, then
10130      * el0_a64 is is_a64(), else el0_a64 is ignored.
10131      */
10132     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
10133 
10134     if (cur_el < new_el) {
10135         /* Entry vector offset depends on whether the implemented EL
10136          * immediately lower than the target level is using AArch32 or AArch64
10137          */
10138         bool is_aa64;
10139         uint64_t hcr;
10140 
10141         switch (new_el) {
10142         case 3:
10143             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
10144             break;
10145         case 2:
10146             hcr = arm_hcr_el2_eff(env);
10147             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
10148                 is_aa64 = (hcr & HCR_RW) != 0;
10149                 break;
10150             }
10151             /* fall through */
10152         case 1:
10153             is_aa64 = is_a64(env);
10154             break;
10155         default:
10156             g_assert_not_reached();
10157         }
10158 
10159         if (is_aa64) {
10160             addr += 0x400;
10161         } else {
10162             addr += 0x600;
10163         }
10164     } else if (pstate_read(env) & PSTATE_SP) {
10165         addr += 0x200;
10166     }
10167 
10168     switch (cs->exception_index) {
10169     case EXCP_PREFETCH_ABORT:
10170     case EXCP_DATA_ABORT:
10171         env->cp15.far_el[new_el] = env->exception.vaddress;
10172         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
10173                       env->cp15.far_el[new_el]);
10174         /* fall through */
10175     case EXCP_BKPT:
10176     case EXCP_UDEF:
10177     case EXCP_SWI:
10178     case EXCP_HVC:
10179     case EXCP_HYP_TRAP:
10180     case EXCP_SMC:
10181         switch (syn_get_ec(env->exception.syndrome)) {
10182         case EC_ADVSIMDFPACCESSTRAP:
10183             /*
10184              * QEMU internal FP/SIMD syndromes from AArch32 include the
10185              * TA and coproc fields which are only exposed if the exception
10186              * is taken to AArch32 Hyp mode. Mask them out to get a valid
10187              * AArch64 format syndrome.
10188              */
10189             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
10190             break;
10191         case EC_CP14RTTRAP:
10192         case EC_CP15RTTRAP:
10193         case EC_CP14DTTRAP:
10194             /*
10195              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
10196              * the raw register field from the insn; when taking this to
10197              * AArch64 we must convert it to the AArch64 view of the register
10198              * number. Notice that we read a 4-bit AArch32 register number and
10199              * write back a 5-bit AArch64 one.
10200              */
10201             rt = extract32(env->exception.syndrome, 5, 4);
10202             rt = aarch64_regnum(env, rt);
10203             env->exception.syndrome = deposit32(env->exception.syndrome,
10204                                                 5, 5, rt);
10205             break;
10206         case EC_CP15RRTTRAP:
10207         case EC_CP14RRTTRAP:
10208             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
10209             rt = extract32(env->exception.syndrome, 5, 4);
10210             rt = aarch64_regnum(env, rt);
10211             env->exception.syndrome = deposit32(env->exception.syndrome,
10212                                                 5, 5, rt);
10213             rt = extract32(env->exception.syndrome, 10, 4);
10214             rt = aarch64_regnum(env, rt);
10215             env->exception.syndrome = deposit32(env->exception.syndrome,
10216                                                 10, 5, rt);
10217             break;
10218         }
10219         env->cp15.esr_el[new_el] = env->exception.syndrome;
10220         break;
10221     case EXCP_IRQ:
10222     case EXCP_VIRQ:
10223         addr += 0x80;
10224         break;
10225     case EXCP_FIQ:
10226     case EXCP_VFIQ:
10227         addr += 0x100;
10228         break;
10229     case EXCP_VSERR:
10230         addr += 0x180;
10231         /* Construct the SError syndrome from IDS and ISS fields. */
10232         env->exception.syndrome = syn_serror(env->cp15.vsesr_el2 & 0x1ffffff);
10233         env->cp15.esr_el[new_el] = env->exception.syndrome;
10234         break;
10235     default:
10236         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10237     }
10238 
10239     if (is_a64(env)) {
10240         old_mode = pstate_read(env);
10241         aarch64_save_sp(env, arm_current_el(env));
10242         env->elr_el[new_el] = env->pc;
10243     } else {
10244         old_mode = cpsr_read_for_spsr_elx(env);
10245         env->elr_el[new_el] = env->regs[15];
10246 
10247         aarch64_sync_32_to_64(env);
10248 
10249         env->condexec_bits = 0;
10250     }
10251     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
10252 
10253     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
10254                   env->elr_el[new_el]);
10255 
10256     if (cpu_isar_feature(aa64_pan, cpu)) {
10257         /* The value of PSTATE.PAN is normally preserved, except when ... */
10258         new_mode |= old_mode & PSTATE_PAN;
10259         switch (new_el) {
10260         case 2:
10261             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
10262             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
10263                 != (HCR_E2H | HCR_TGE)) {
10264                 break;
10265             }
10266             /* fall through */
10267         case 1:
10268             /* ... the target is EL1 ... */
10269             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
10270             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
10271                 new_mode |= PSTATE_PAN;
10272             }
10273             break;
10274         }
10275     }
10276     if (cpu_isar_feature(aa64_mte, cpu)) {
10277         new_mode |= PSTATE_TCO;
10278     }
10279 
10280     if (cpu_isar_feature(aa64_ssbs, cpu)) {
10281         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_64) {
10282             new_mode |= PSTATE_SSBS;
10283         } else {
10284             new_mode &= ~PSTATE_SSBS;
10285         }
10286     }
10287 
10288     pstate_write(env, PSTATE_DAIF | new_mode);
10289     env->aarch64 = true;
10290     aarch64_restore_sp(env, new_el);
10291     helper_rebuild_hflags_a64(env, new_el);
10292 
10293     env->pc = addr;
10294 
10295     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10296                   new_el, env->pc, pstate_read(env));
10297 }
10298 
10299 /*
10300  * Do semihosting call and set the appropriate return value. All the
10301  * permission and validity checks have been done at translate time.
10302  *
10303  * We only see semihosting exceptions in TCG only as they are not
10304  * trapped to the hypervisor in KVM.
10305  */
10306 #ifdef CONFIG_TCG
10307 static void handle_semihosting(CPUState *cs)
10308 {
10309     ARMCPU *cpu = ARM_CPU(cs);
10310     CPUARMState *env = &cpu->env;
10311 
10312     if (is_a64(env)) {
10313         qemu_log_mask(CPU_LOG_INT,
10314                       "...handling as semihosting call 0x%" PRIx64 "\n",
10315                       env->xregs[0]);
10316         env->xregs[0] = do_common_semihosting(cs);
10317         env->pc += 4;
10318     } else {
10319         qemu_log_mask(CPU_LOG_INT,
10320                       "...handling as semihosting call 0x%x\n",
10321                       env->regs[0]);
10322         env->regs[0] = do_common_semihosting(cs);
10323         env->regs[15] += env->thumb ? 2 : 4;
10324     }
10325 }
10326 #endif
10327 
10328 /* Handle a CPU exception for A and R profile CPUs.
10329  * Do any appropriate logging, handle PSCI calls, and then hand off
10330  * to the AArch64-entry or AArch32-entry function depending on the
10331  * target exception level's register width.
10332  *
10333  * Note: this is used for both TCG (as the do_interrupt tcg op),
10334  *       and KVM to re-inject guest debug exceptions, and to
10335  *       inject a Synchronous-External-Abort.
10336  */
10337 void arm_cpu_do_interrupt(CPUState *cs)
10338 {
10339     ARMCPU *cpu = ARM_CPU(cs);
10340     CPUARMState *env = &cpu->env;
10341     unsigned int new_el = env->exception.target_el;
10342 
10343     assert(!arm_feature(env, ARM_FEATURE_M));
10344 
10345     arm_log_exception(cs);
10346     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10347                   new_el);
10348     if (qemu_loglevel_mask(CPU_LOG_INT)
10349         && !excp_is_internal(cs->exception_index)) {
10350         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10351                       syn_get_ec(env->exception.syndrome),
10352                       env->exception.syndrome);
10353     }
10354 
10355     if (arm_is_psci_call(cpu, cs->exception_index)) {
10356         arm_handle_psci_call(cpu);
10357         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10358         return;
10359     }
10360 
10361     /*
10362      * Semihosting semantics depend on the register width of the code
10363      * that caused the exception, not the target exception level, so
10364      * must be handled here.
10365      */
10366 #ifdef CONFIG_TCG
10367     if (cs->exception_index == EXCP_SEMIHOST) {
10368         handle_semihosting(cs);
10369         return;
10370     }
10371 #endif
10372 
10373     /* Hooks may change global state so BQL should be held, also the
10374      * BQL needs to be held for any modification of
10375      * cs->interrupt_request.
10376      */
10377     g_assert(qemu_mutex_iothread_locked());
10378 
10379     arm_call_pre_el_change_hook(cpu);
10380 
10381     assert(!excp_is_internal(cs->exception_index));
10382     if (arm_el_is_aa64(env, new_el)) {
10383         arm_cpu_do_interrupt_aarch64(cs);
10384     } else {
10385         arm_cpu_do_interrupt_aarch32(cs);
10386     }
10387 
10388     arm_call_el_change_hook(cpu);
10389 
10390     if (!kvm_enabled()) {
10391         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10392     }
10393 }
10394 #endif /* !CONFIG_USER_ONLY */
10395 
10396 uint64_t arm_sctlr(CPUARMState *env, int el)
10397 {
10398     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
10399     if (el == 0) {
10400         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
10401         el = (mmu_idx == ARMMMUIdx_E20_0 || mmu_idx == ARMMMUIdx_SE20_0)
10402              ? 2 : 1;
10403     }
10404     return env->cp15.sctlr_el[el];
10405 }
10406 
10407 /* Return the SCTLR value which controls this address translation regime */
10408 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10409 {
10410     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10411 }
10412 
10413 #ifndef CONFIG_USER_ONLY
10414 
10415 /* Return true if the specified stage of address translation is disabled */
10416 static inline bool regime_translation_disabled(CPUARMState *env,
10417                                                ARMMMUIdx mmu_idx)
10418 {
10419     uint64_t hcr_el2;
10420 
10421     if (arm_feature(env, ARM_FEATURE_M)) {
10422         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10423                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10424         case R_V7M_MPU_CTRL_ENABLE_MASK:
10425             /* Enabled, but not for HardFault and NMI */
10426             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10427         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10428             /* Enabled for all cases */
10429             return false;
10430         case 0:
10431         default:
10432             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10433              * we warned about that in armv7m_nvic.c when the guest set it.
10434              */
10435             return true;
10436         }
10437     }
10438 
10439     hcr_el2 = arm_hcr_el2_eff(env);
10440 
10441     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10442         /* HCR.DC means HCR.VM behaves as 1 */
10443         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10444     }
10445 
10446     if (hcr_el2 & HCR_TGE) {
10447         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10448         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10449             return true;
10450         }
10451     }
10452 
10453     if ((hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
10454         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10455         return true;
10456     }
10457 
10458     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10459 }
10460 
10461 static inline bool regime_translation_big_endian(CPUARMState *env,
10462                                                  ARMMMUIdx mmu_idx)
10463 {
10464     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10465 }
10466 
10467 /* Return the TTBR associated with this translation regime */
10468 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10469                                    int ttbrn)
10470 {
10471     if (mmu_idx == ARMMMUIdx_Stage2) {
10472         return env->cp15.vttbr_el2;
10473     }
10474     if (mmu_idx == ARMMMUIdx_Stage2_S) {
10475         return env->cp15.vsttbr_el2;
10476     }
10477     if (ttbrn == 0) {
10478         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10479     } else {
10480         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10481     }
10482 }
10483 
10484 #endif /* !CONFIG_USER_ONLY */
10485 
10486 /* Convert a possible stage1+2 MMU index into the appropriate
10487  * stage 1 MMU index
10488  */
10489 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10490 {
10491     switch (mmu_idx) {
10492     case ARMMMUIdx_SE10_0:
10493         return ARMMMUIdx_Stage1_SE0;
10494     case ARMMMUIdx_SE10_1:
10495         return ARMMMUIdx_Stage1_SE1;
10496     case ARMMMUIdx_SE10_1_PAN:
10497         return ARMMMUIdx_Stage1_SE1_PAN;
10498     case ARMMMUIdx_E10_0:
10499         return ARMMMUIdx_Stage1_E0;
10500     case ARMMMUIdx_E10_1:
10501         return ARMMMUIdx_Stage1_E1;
10502     case ARMMMUIdx_E10_1_PAN:
10503         return ARMMMUIdx_Stage1_E1_PAN;
10504     default:
10505         return mmu_idx;
10506     }
10507 }
10508 
10509 /* Return true if the translation regime is using LPAE format page tables */
10510 static inline bool regime_using_lpae_format(CPUARMState *env,
10511                                             ARMMMUIdx mmu_idx)
10512 {
10513     int el = regime_el(env, mmu_idx);
10514     if (el == 2 || arm_el_is_aa64(env, el)) {
10515         return true;
10516     }
10517     if (arm_feature(env, ARM_FEATURE_LPAE)
10518         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10519         return true;
10520     }
10521     return false;
10522 }
10523 
10524 /* Returns true if the stage 1 translation regime is using LPAE format page
10525  * tables. Used when raising alignment exceptions, whose FSR changes depending
10526  * on whether the long or short descriptor format is in use. */
10527 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10528 {
10529     mmu_idx = stage_1_mmu_idx(mmu_idx);
10530 
10531     return regime_using_lpae_format(env, mmu_idx);
10532 }
10533 
10534 #ifndef CONFIG_USER_ONLY
10535 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10536 {
10537     switch (mmu_idx) {
10538     case ARMMMUIdx_SE10_0:
10539     case ARMMMUIdx_E20_0:
10540     case ARMMMUIdx_SE20_0:
10541     case ARMMMUIdx_Stage1_E0:
10542     case ARMMMUIdx_Stage1_SE0:
10543     case ARMMMUIdx_MUser:
10544     case ARMMMUIdx_MSUser:
10545     case ARMMMUIdx_MUserNegPri:
10546     case ARMMMUIdx_MSUserNegPri:
10547         return true;
10548     default:
10549         return false;
10550     case ARMMMUIdx_E10_0:
10551     case ARMMMUIdx_E10_1:
10552     case ARMMMUIdx_E10_1_PAN:
10553         g_assert_not_reached();
10554     }
10555 }
10556 
10557 /* Translate section/page access permissions to page
10558  * R/W protection flags
10559  *
10560  * @env:         CPUARMState
10561  * @mmu_idx:     MMU index indicating required translation regime
10562  * @ap:          The 3-bit access permissions (AP[2:0])
10563  * @domain_prot: The 2-bit domain access permissions
10564  */
10565 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10566                                 int ap, int domain_prot)
10567 {
10568     bool is_user = regime_is_user(env, mmu_idx);
10569 
10570     if (domain_prot == 3) {
10571         return PAGE_READ | PAGE_WRITE;
10572     }
10573 
10574     switch (ap) {
10575     case 0:
10576         if (arm_feature(env, ARM_FEATURE_V7)) {
10577             return 0;
10578         }
10579         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10580         case SCTLR_S:
10581             return is_user ? 0 : PAGE_READ;
10582         case SCTLR_R:
10583             return PAGE_READ;
10584         default:
10585             return 0;
10586         }
10587     case 1:
10588         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10589     case 2:
10590         if (is_user) {
10591             return PAGE_READ;
10592         } else {
10593             return PAGE_READ | PAGE_WRITE;
10594         }
10595     case 3:
10596         return PAGE_READ | PAGE_WRITE;
10597     case 4: /* Reserved.  */
10598         return 0;
10599     case 5:
10600         return is_user ? 0 : PAGE_READ;
10601     case 6:
10602         return PAGE_READ;
10603     case 7:
10604         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10605             return 0;
10606         }
10607         return PAGE_READ;
10608     default:
10609         g_assert_not_reached();
10610     }
10611 }
10612 
10613 /* Translate section/page access permissions to page
10614  * R/W protection flags.
10615  *
10616  * @ap:      The 2-bit simple AP (AP[2:1])
10617  * @is_user: TRUE if accessing from PL0
10618  */
10619 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10620 {
10621     switch (ap) {
10622     case 0:
10623         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10624     case 1:
10625         return PAGE_READ | PAGE_WRITE;
10626     case 2:
10627         return is_user ? 0 : PAGE_READ;
10628     case 3:
10629         return PAGE_READ;
10630     default:
10631         g_assert_not_reached();
10632     }
10633 }
10634 
10635 static inline int
10636 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10637 {
10638     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10639 }
10640 
10641 /* Translate S2 section/page access permissions to protection flags
10642  *
10643  * @env:     CPUARMState
10644  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10645  * @xn:      XN (execute-never) bits
10646  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10647  */
10648 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10649 {
10650     int prot = 0;
10651 
10652     if (s2ap & 1) {
10653         prot |= PAGE_READ;
10654     }
10655     if (s2ap & 2) {
10656         prot |= PAGE_WRITE;
10657     }
10658 
10659     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10660         switch (xn) {
10661         case 0:
10662             prot |= PAGE_EXEC;
10663             break;
10664         case 1:
10665             if (s1_is_el0) {
10666                 prot |= PAGE_EXEC;
10667             }
10668             break;
10669         case 2:
10670             break;
10671         case 3:
10672             if (!s1_is_el0) {
10673                 prot |= PAGE_EXEC;
10674             }
10675             break;
10676         default:
10677             g_assert_not_reached();
10678         }
10679     } else {
10680         if (!extract32(xn, 1, 1)) {
10681             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10682                 prot |= PAGE_EXEC;
10683             }
10684         }
10685     }
10686     return prot;
10687 }
10688 
10689 /* Translate section/page access permissions to protection flags
10690  *
10691  * @env:     CPUARMState
10692  * @mmu_idx: MMU index indicating required translation regime
10693  * @is_aa64: TRUE if AArch64
10694  * @ap:      The 2-bit simple AP (AP[2:1])
10695  * @ns:      NS (non-secure) bit
10696  * @xn:      XN (execute-never) bit
10697  * @pxn:     PXN (privileged execute-never) bit
10698  */
10699 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10700                       int ap, int ns, int xn, int pxn)
10701 {
10702     bool is_user = regime_is_user(env, mmu_idx);
10703     int prot_rw, user_rw;
10704     bool have_wxn;
10705     int wxn = 0;
10706 
10707     assert(mmu_idx != ARMMMUIdx_Stage2);
10708     assert(mmu_idx != ARMMMUIdx_Stage2_S);
10709 
10710     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10711     if (is_user) {
10712         prot_rw = user_rw;
10713     } else {
10714         if (user_rw && regime_is_pan(env, mmu_idx)) {
10715             /* PAN forbids data accesses but doesn't affect insn fetch */
10716             prot_rw = 0;
10717         } else {
10718             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10719         }
10720     }
10721 
10722     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10723         return prot_rw;
10724     }
10725 
10726     /* TODO have_wxn should be replaced with
10727      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10728      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10729      * compatible processors have EL2, which is required for [U]WXN.
10730      */
10731     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10732 
10733     if (have_wxn) {
10734         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10735     }
10736 
10737     if (is_aa64) {
10738         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10739             xn = pxn || (user_rw & PAGE_WRITE);
10740         }
10741     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10742         switch (regime_el(env, mmu_idx)) {
10743         case 1:
10744         case 3:
10745             if (is_user) {
10746                 xn = xn || !(user_rw & PAGE_READ);
10747             } else {
10748                 int uwxn = 0;
10749                 if (have_wxn) {
10750                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10751                 }
10752                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10753                      (uwxn && (user_rw & PAGE_WRITE));
10754             }
10755             break;
10756         case 2:
10757             break;
10758         }
10759     } else {
10760         xn = wxn = 0;
10761     }
10762 
10763     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10764         return prot_rw;
10765     }
10766     return prot_rw | PAGE_EXEC;
10767 }
10768 
10769 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10770                                      uint32_t *table, uint32_t address)
10771 {
10772     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10773     TCR *tcr = regime_tcr(env, mmu_idx);
10774 
10775     if (address & tcr->mask) {
10776         if (tcr->raw_tcr & TTBCR_PD1) {
10777             /* Translation table walk disabled for TTBR1 */
10778             return false;
10779         }
10780         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10781     } else {
10782         if (tcr->raw_tcr & TTBCR_PD0) {
10783             /* Translation table walk disabled for TTBR0 */
10784             return false;
10785         }
10786         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10787     }
10788     *table |= (address >> 18) & 0x3ffc;
10789     return true;
10790 }
10791 
10792 static bool ptw_attrs_are_device(CPUARMState *env, ARMCacheAttrs cacheattrs)
10793 {
10794     /*
10795      * For an S1 page table walk, the stage 1 attributes are always
10796      * some form of "this is Normal memory". The combined S1+S2
10797      * attributes are therefore only Device if stage 2 specifies Device.
10798      * With HCR_EL2.FWB == 0 this is when descriptor bits [5:4] are 0b00,
10799      * ie when cacheattrs.attrs bits [3:2] are 0b00.
10800      * With HCR_EL2.FWB == 1 this is when descriptor bit [4] is 0, ie
10801      * when cacheattrs.attrs bit [2] is 0.
10802      */
10803     assert(cacheattrs.is_s2_format);
10804     if (arm_hcr_el2_eff(env) & HCR_FWB) {
10805         return (cacheattrs.attrs & 0x4) == 0;
10806     } else {
10807         return (cacheattrs.attrs & 0xc) == 0;
10808     }
10809 }
10810 
10811 /* Translate a S1 pagetable walk through S2 if needed.  */
10812 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10813                                hwaddr addr, bool *is_secure,
10814                                ARMMMUFaultInfo *fi)
10815 {
10816     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10817         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10818         target_ulong s2size;
10819         hwaddr s2pa;
10820         int s2prot;
10821         int ret;
10822         ARMMMUIdx s2_mmu_idx = *is_secure ? ARMMMUIdx_Stage2_S
10823                                           : ARMMMUIdx_Stage2;
10824         ARMCacheAttrs cacheattrs = {};
10825         MemTxAttrs txattrs = {};
10826 
10827         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, s2_mmu_idx, false,
10828                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10829                                  &cacheattrs);
10830         if (ret) {
10831             assert(fi->type != ARMFault_None);
10832             fi->s2addr = addr;
10833             fi->stage2 = true;
10834             fi->s1ptw = true;
10835             fi->s1ns = !*is_secure;
10836             return ~0;
10837         }
10838         if ((arm_hcr_el2_eff(env) & HCR_PTW) &&
10839             ptw_attrs_are_device(env, cacheattrs)) {
10840             /*
10841              * PTW set and S1 walk touched S2 Device memory:
10842              * generate Permission fault.
10843              */
10844             fi->type = ARMFault_Permission;
10845             fi->s2addr = addr;
10846             fi->stage2 = true;
10847             fi->s1ptw = true;
10848             fi->s1ns = !*is_secure;
10849             return ~0;
10850         }
10851 
10852         if (arm_is_secure_below_el3(env)) {
10853             /* Check if page table walk is to secure or non-secure PA space. */
10854             if (*is_secure) {
10855                 *is_secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
10856             } else {
10857                 *is_secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
10858             }
10859         } else {
10860             assert(!*is_secure);
10861         }
10862 
10863         addr = s2pa;
10864     }
10865     return addr;
10866 }
10867 
10868 /* All loads done in the course of a page table walk go through here. */
10869 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10870                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10871 {
10872     ARMCPU *cpu = ARM_CPU(cs);
10873     CPUARMState *env = &cpu->env;
10874     MemTxAttrs attrs = {};
10875     MemTxResult result = MEMTX_OK;
10876     AddressSpace *as;
10877     uint32_t data;
10878 
10879     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10880     attrs.secure = is_secure;
10881     as = arm_addressspace(cs, attrs);
10882     if (fi->s1ptw) {
10883         return 0;
10884     }
10885     if (regime_translation_big_endian(env, mmu_idx)) {
10886         data = address_space_ldl_be(as, addr, attrs, &result);
10887     } else {
10888         data = address_space_ldl_le(as, addr, attrs, &result);
10889     }
10890     if (result == MEMTX_OK) {
10891         return data;
10892     }
10893     fi->type = ARMFault_SyncExternalOnWalk;
10894     fi->ea = arm_extabort_type(result);
10895     return 0;
10896 }
10897 
10898 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10899                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10900 {
10901     ARMCPU *cpu = ARM_CPU(cs);
10902     CPUARMState *env = &cpu->env;
10903     MemTxAttrs attrs = {};
10904     MemTxResult result = MEMTX_OK;
10905     AddressSpace *as;
10906     uint64_t data;
10907 
10908     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10909     attrs.secure = is_secure;
10910     as = arm_addressspace(cs, attrs);
10911     if (fi->s1ptw) {
10912         return 0;
10913     }
10914     if (regime_translation_big_endian(env, mmu_idx)) {
10915         data = address_space_ldq_be(as, addr, attrs, &result);
10916     } else {
10917         data = address_space_ldq_le(as, addr, attrs, &result);
10918     }
10919     if (result == MEMTX_OK) {
10920         return data;
10921     }
10922     fi->type = ARMFault_SyncExternalOnWalk;
10923     fi->ea = arm_extabort_type(result);
10924     return 0;
10925 }
10926 
10927 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10928                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10929                              hwaddr *phys_ptr, int *prot,
10930                              target_ulong *page_size,
10931                              ARMMMUFaultInfo *fi)
10932 {
10933     CPUState *cs = env_cpu(env);
10934     int level = 1;
10935     uint32_t table;
10936     uint32_t desc;
10937     int type;
10938     int ap;
10939     int domain = 0;
10940     int domain_prot;
10941     hwaddr phys_addr;
10942     uint32_t dacr;
10943 
10944     /* Pagetable walk.  */
10945     /* Lookup l1 descriptor.  */
10946     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10947         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10948         fi->type = ARMFault_Translation;
10949         goto do_fault;
10950     }
10951     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10952                        mmu_idx, fi);
10953     if (fi->type != ARMFault_None) {
10954         goto do_fault;
10955     }
10956     type = (desc & 3);
10957     domain = (desc >> 5) & 0x0f;
10958     if (regime_el(env, mmu_idx) == 1) {
10959         dacr = env->cp15.dacr_ns;
10960     } else {
10961         dacr = env->cp15.dacr_s;
10962     }
10963     domain_prot = (dacr >> (domain * 2)) & 3;
10964     if (type == 0) {
10965         /* Section translation fault.  */
10966         fi->type = ARMFault_Translation;
10967         goto do_fault;
10968     }
10969     if (type != 2) {
10970         level = 2;
10971     }
10972     if (domain_prot == 0 || domain_prot == 2) {
10973         fi->type = ARMFault_Domain;
10974         goto do_fault;
10975     }
10976     if (type == 2) {
10977         /* 1Mb section.  */
10978         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10979         ap = (desc >> 10) & 3;
10980         *page_size = 1024 * 1024;
10981     } else {
10982         /* Lookup l2 entry.  */
10983         if (type == 1) {
10984             /* Coarse pagetable.  */
10985             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10986         } else {
10987             /* Fine pagetable.  */
10988             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10989         }
10990         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10991                            mmu_idx, fi);
10992         if (fi->type != ARMFault_None) {
10993             goto do_fault;
10994         }
10995         switch (desc & 3) {
10996         case 0: /* Page translation fault.  */
10997             fi->type = ARMFault_Translation;
10998             goto do_fault;
10999         case 1: /* 64k page.  */
11000             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11001             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
11002             *page_size = 0x10000;
11003             break;
11004         case 2: /* 4k page.  */
11005             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11006             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
11007             *page_size = 0x1000;
11008             break;
11009         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
11010             if (type == 1) {
11011                 /* ARMv6/XScale extended small page format */
11012                 if (arm_feature(env, ARM_FEATURE_XSCALE)
11013                     || arm_feature(env, ARM_FEATURE_V6)) {
11014                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11015                     *page_size = 0x1000;
11016                 } else {
11017                     /* UNPREDICTABLE in ARMv5; we choose to take a
11018                      * page translation fault.
11019                      */
11020                     fi->type = ARMFault_Translation;
11021                     goto do_fault;
11022                 }
11023             } else {
11024                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
11025                 *page_size = 0x400;
11026             }
11027             ap = (desc >> 4) & 3;
11028             break;
11029         default:
11030             /* Never happens, but compiler isn't smart enough to tell.  */
11031             g_assert_not_reached();
11032         }
11033     }
11034     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11035     *prot |= *prot ? PAGE_EXEC : 0;
11036     if (!(*prot & (1 << access_type))) {
11037         /* Access permission fault.  */
11038         fi->type = ARMFault_Permission;
11039         goto do_fault;
11040     }
11041     *phys_ptr = phys_addr;
11042     return false;
11043 do_fault:
11044     fi->domain = domain;
11045     fi->level = level;
11046     return true;
11047 }
11048 
11049 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
11050                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
11051                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
11052                              target_ulong *page_size, ARMMMUFaultInfo *fi)
11053 {
11054     CPUState *cs = env_cpu(env);
11055     ARMCPU *cpu = env_archcpu(env);
11056     int level = 1;
11057     uint32_t table;
11058     uint32_t desc;
11059     uint32_t xn;
11060     uint32_t pxn = 0;
11061     int type;
11062     int ap;
11063     int domain = 0;
11064     int domain_prot;
11065     hwaddr phys_addr;
11066     uint32_t dacr;
11067     bool ns;
11068 
11069     /* Pagetable walk.  */
11070     /* Lookup l1 descriptor.  */
11071     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
11072         /* Section translation fault if page walk is disabled by PD0 or PD1 */
11073         fi->type = ARMFault_Translation;
11074         goto do_fault;
11075     }
11076     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11077                        mmu_idx, fi);
11078     if (fi->type != ARMFault_None) {
11079         goto do_fault;
11080     }
11081     type = (desc & 3);
11082     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
11083         /* Section translation fault, or attempt to use the encoding
11084          * which is Reserved on implementations without PXN.
11085          */
11086         fi->type = ARMFault_Translation;
11087         goto do_fault;
11088     }
11089     if ((type == 1) || !(desc & (1 << 18))) {
11090         /* Page or Section.  */
11091         domain = (desc >> 5) & 0x0f;
11092     }
11093     if (regime_el(env, mmu_idx) == 1) {
11094         dacr = env->cp15.dacr_ns;
11095     } else {
11096         dacr = env->cp15.dacr_s;
11097     }
11098     if (type == 1) {
11099         level = 2;
11100     }
11101     domain_prot = (dacr >> (domain * 2)) & 3;
11102     if (domain_prot == 0 || domain_prot == 2) {
11103         /* Section or Page domain fault */
11104         fi->type = ARMFault_Domain;
11105         goto do_fault;
11106     }
11107     if (type != 1) {
11108         if (desc & (1 << 18)) {
11109             /* Supersection.  */
11110             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
11111             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
11112             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
11113             *page_size = 0x1000000;
11114         } else {
11115             /* Section.  */
11116             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
11117             *page_size = 0x100000;
11118         }
11119         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
11120         xn = desc & (1 << 4);
11121         pxn = desc & 1;
11122         ns = extract32(desc, 19, 1);
11123     } else {
11124         if (cpu_isar_feature(aa32_pxn, cpu)) {
11125             pxn = (desc >> 2) & 1;
11126         }
11127         ns = extract32(desc, 3, 1);
11128         /* Lookup l2 entry.  */
11129         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11130         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11131                            mmu_idx, fi);
11132         if (fi->type != ARMFault_None) {
11133             goto do_fault;
11134         }
11135         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
11136         switch (desc & 3) {
11137         case 0: /* Page translation fault.  */
11138             fi->type = ARMFault_Translation;
11139             goto do_fault;
11140         case 1: /* 64k page.  */
11141             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11142             xn = desc & (1 << 15);
11143             *page_size = 0x10000;
11144             break;
11145         case 2: case 3: /* 4k page.  */
11146             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11147             xn = desc & 1;
11148             *page_size = 0x1000;
11149             break;
11150         default:
11151             /* Never happens, but compiler isn't smart enough to tell.  */
11152             g_assert_not_reached();
11153         }
11154     }
11155     if (domain_prot == 3) {
11156         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11157     } else {
11158         if (pxn && !regime_is_user(env, mmu_idx)) {
11159             xn = 1;
11160         }
11161         if (xn && access_type == MMU_INST_FETCH) {
11162             fi->type = ARMFault_Permission;
11163             goto do_fault;
11164         }
11165 
11166         if (arm_feature(env, ARM_FEATURE_V6K) &&
11167                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
11168             /* The simplified model uses AP[0] as an access control bit.  */
11169             if ((ap & 1) == 0) {
11170                 /* Access flag fault.  */
11171                 fi->type = ARMFault_AccessFlag;
11172                 goto do_fault;
11173             }
11174             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
11175         } else {
11176             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11177         }
11178         if (*prot && !xn) {
11179             *prot |= PAGE_EXEC;
11180         }
11181         if (!(*prot & (1 << access_type))) {
11182             /* Access permission fault.  */
11183             fi->type = ARMFault_Permission;
11184             goto do_fault;
11185         }
11186     }
11187     if (ns) {
11188         /* The NS bit will (as required by the architecture) have no effect if
11189          * the CPU doesn't support TZ or this is a non-secure translation
11190          * regime, because the attribute will already be non-secure.
11191          */
11192         attrs->secure = false;
11193     }
11194     *phys_ptr = phys_addr;
11195     return false;
11196 do_fault:
11197     fi->domain = domain;
11198     fi->level = level;
11199     return true;
11200 }
11201 
11202 /*
11203  * check_s2_mmu_setup
11204  * @cpu:        ARMCPU
11205  * @is_aa64:    True if the translation regime is in AArch64 state
11206  * @startlevel: Suggested starting level
11207  * @inputsize:  Bitsize of IPAs
11208  * @stride:     Page-table stride (See the ARM ARM)
11209  *
11210  * Returns true if the suggested S2 translation parameters are OK and
11211  * false otherwise.
11212  */
11213 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
11214                                int inputsize, int stride, int outputsize)
11215 {
11216     const int grainsize = stride + 3;
11217     int startsizecheck;
11218 
11219     /*
11220      * Negative levels are usually not allowed...
11221      * Except for FEAT_LPA2, 4k page table, 52-bit address space, which
11222      * begins with level -1.  Note that previous feature tests will have
11223      * eliminated this combination if it is not enabled.
11224      */
11225     if (level < (inputsize == 52 && stride == 9 ? -1 : 0)) {
11226         return false;
11227     }
11228 
11229     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
11230     if (startsizecheck < 1 || startsizecheck > stride + 4) {
11231         return false;
11232     }
11233 
11234     if (is_aa64) {
11235         switch (stride) {
11236         case 13: /* 64KB Pages.  */
11237             if (level == 0 || (level == 1 && outputsize <= 42)) {
11238                 return false;
11239             }
11240             break;
11241         case 11: /* 16KB Pages.  */
11242             if (level == 0 || (level == 1 && outputsize <= 40)) {
11243                 return false;
11244             }
11245             break;
11246         case 9: /* 4KB Pages.  */
11247             if (level == 0 && outputsize <= 42) {
11248                 return false;
11249             }
11250             break;
11251         default:
11252             g_assert_not_reached();
11253         }
11254 
11255         /* Inputsize checks.  */
11256         if (inputsize > outputsize &&
11257             (arm_el_is_aa64(&cpu->env, 1) || inputsize > 40)) {
11258             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
11259             return false;
11260         }
11261     } else {
11262         /* AArch32 only supports 4KB pages. Assert on that.  */
11263         assert(stride == 9);
11264 
11265         if (level == 0) {
11266             return false;
11267         }
11268     }
11269     return true;
11270 }
11271 
11272 /* Translate from the 4-bit stage 2 representation of
11273  * memory attributes (without cache-allocation hints) to
11274  * the 8-bit representation of the stage 1 MAIR registers
11275  * (which includes allocation hints).
11276  *
11277  * ref: shared/translation/attrs/S2AttrDecode()
11278  *      .../S2ConvertAttrsHints()
11279  */
11280 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11281 {
11282     uint8_t hiattr = extract32(s2attrs, 2, 2);
11283     uint8_t loattr = extract32(s2attrs, 0, 2);
11284     uint8_t hihint = 0, lohint = 0;
11285 
11286     if (hiattr != 0) { /* normal memory */
11287         if (arm_hcr_el2_eff(env) & HCR_CD) { /* cache disabled */
11288             hiattr = loattr = 1; /* non-cacheable */
11289         } else {
11290             if (hiattr != 1) { /* Write-through or write-back */
11291                 hihint = 3; /* RW allocate */
11292             }
11293             if (loattr != 1) { /* Write-through or write-back */
11294                 lohint = 3; /* RW allocate */
11295             }
11296         }
11297     }
11298 
11299     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11300 }
11301 #endif /* !CONFIG_USER_ONLY */
11302 
11303 /* This mapping is common between ID_AA64MMFR0.PARANGE and TCR_ELx.{I}PS. */
11304 static const uint8_t pamax_map[] = {
11305     [0] = 32,
11306     [1] = 36,
11307     [2] = 40,
11308     [3] = 42,
11309     [4] = 44,
11310     [5] = 48,
11311     [6] = 52,
11312 };
11313 
11314 /* The cpu-specific constant value of PAMax; also used by hw/arm/virt. */
11315 unsigned int arm_pamax(ARMCPU *cpu)
11316 {
11317     unsigned int parange =
11318         FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11319 
11320     /*
11321      * id_aa64mmfr0 is a read-only register so values outside of the
11322      * supported mappings can be considered an implementation error.
11323      */
11324     assert(parange < ARRAY_SIZE(pamax_map));
11325     return pamax_map[parange];
11326 }
11327 
11328 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
11329 {
11330     if (regime_has_2_ranges(mmu_idx)) {
11331         return extract64(tcr, 37, 2);
11332     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11333         return 0; /* VTCR_EL2 */
11334     } else {
11335         /* Replicate the single TBI bit so we always have 2 bits.  */
11336         return extract32(tcr, 20, 1) * 3;
11337     }
11338 }
11339 
11340 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
11341 {
11342     if (regime_has_2_ranges(mmu_idx)) {
11343         return extract64(tcr, 51, 2);
11344     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11345         return 0; /* VTCR_EL2 */
11346     } else {
11347         /* Replicate the single TBID bit so we always have 2 bits.  */
11348         return extract32(tcr, 29, 1) * 3;
11349     }
11350 }
11351 
11352 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
11353 {
11354     if (regime_has_2_ranges(mmu_idx)) {
11355         return extract64(tcr, 57, 2);
11356     } else {
11357         /* Replicate the single TCMA bit so we always have 2 bits.  */
11358         return extract32(tcr, 30, 1) * 3;
11359     }
11360 }
11361 
11362 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11363                                    ARMMMUIdx mmu_idx, bool data)
11364 {
11365     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11366     bool epd, hpd, using16k, using64k, tsz_oob, ds;
11367     int select, tsz, tbi, max_tsz, min_tsz, ps, sh;
11368     ARMCPU *cpu = env_archcpu(env);
11369 
11370     if (!regime_has_2_ranges(mmu_idx)) {
11371         select = 0;
11372         tsz = extract32(tcr, 0, 6);
11373         using64k = extract32(tcr, 14, 1);
11374         using16k = extract32(tcr, 15, 1);
11375         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11376             /* VTCR_EL2 */
11377             hpd = false;
11378         } else {
11379             hpd = extract32(tcr, 24, 1);
11380         }
11381         epd = false;
11382         sh = extract32(tcr, 12, 2);
11383         ps = extract32(tcr, 16, 3);
11384         ds = extract64(tcr, 32, 1);
11385     } else {
11386         /*
11387          * Bit 55 is always between the two regions, and is canonical for
11388          * determining if address tagging is enabled.
11389          */
11390         select = extract64(va, 55, 1);
11391         if (!select) {
11392             tsz = extract32(tcr, 0, 6);
11393             epd = extract32(tcr, 7, 1);
11394             sh = extract32(tcr, 12, 2);
11395             using64k = extract32(tcr, 14, 1);
11396             using16k = extract32(tcr, 15, 1);
11397             hpd = extract64(tcr, 41, 1);
11398         } else {
11399             int tg = extract32(tcr, 30, 2);
11400             using16k = tg == 1;
11401             using64k = tg == 3;
11402             tsz = extract32(tcr, 16, 6);
11403             epd = extract32(tcr, 23, 1);
11404             sh = extract32(tcr, 28, 2);
11405             hpd = extract64(tcr, 42, 1);
11406         }
11407         ps = extract64(tcr, 32, 3);
11408         ds = extract64(tcr, 59, 1);
11409     }
11410 
11411     if (cpu_isar_feature(aa64_st, cpu)) {
11412         max_tsz = 48 - using64k;
11413     } else {
11414         max_tsz = 39;
11415     }
11416 
11417     /*
11418      * DS is RES0 unless FEAT_LPA2 is supported for the given page size;
11419      * adjust the effective value of DS, as documented.
11420      */
11421     min_tsz = 16;
11422     if (using64k) {
11423         if (cpu_isar_feature(aa64_lva, cpu)) {
11424             min_tsz = 12;
11425         }
11426         ds = false;
11427     } else if (ds) {
11428         switch (mmu_idx) {
11429         case ARMMMUIdx_Stage2:
11430         case ARMMMUIdx_Stage2_S:
11431             if (using16k) {
11432                 ds = cpu_isar_feature(aa64_tgran16_2_lpa2, cpu);
11433             } else {
11434                 ds = cpu_isar_feature(aa64_tgran4_2_lpa2, cpu);
11435             }
11436             break;
11437         default:
11438             if (using16k) {
11439                 ds = cpu_isar_feature(aa64_tgran16_lpa2, cpu);
11440             } else {
11441                 ds = cpu_isar_feature(aa64_tgran4_lpa2, cpu);
11442             }
11443             break;
11444         }
11445         if (ds) {
11446             min_tsz = 12;
11447         }
11448     }
11449 
11450     if (tsz > max_tsz) {
11451         tsz = max_tsz;
11452         tsz_oob = true;
11453     } else if (tsz < min_tsz) {
11454         tsz = min_tsz;
11455         tsz_oob = true;
11456     } else {
11457         tsz_oob = false;
11458     }
11459 
11460     /* Present TBI as a composite with TBID.  */
11461     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11462     if (!data) {
11463         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11464     }
11465     tbi = (tbi >> select) & 1;
11466 
11467     return (ARMVAParameters) {
11468         .tsz = tsz,
11469         .ps = ps,
11470         .sh = sh,
11471         .select = select,
11472         .tbi = tbi,
11473         .epd = epd,
11474         .hpd = hpd,
11475         .using16k = using16k,
11476         .using64k = using64k,
11477         .tsz_oob = tsz_oob,
11478         .ds = ds,
11479     };
11480 }
11481 
11482 #ifndef CONFIG_USER_ONLY
11483 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11484                                           ARMMMUIdx mmu_idx)
11485 {
11486     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11487     uint32_t el = regime_el(env, mmu_idx);
11488     int select, tsz;
11489     bool epd, hpd;
11490 
11491     assert(mmu_idx != ARMMMUIdx_Stage2_S);
11492 
11493     if (mmu_idx == ARMMMUIdx_Stage2) {
11494         /* VTCR */
11495         bool sext = extract32(tcr, 4, 1);
11496         bool sign = extract32(tcr, 3, 1);
11497 
11498         /*
11499          * If the sign-extend bit is not the same as t0sz[3], the result
11500          * is unpredictable. Flag this as a guest error.
11501          */
11502         if (sign != sext) {
11503             qemu_log_mask(LOG_GUEST_ERROR,
11504                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11505         }
11506         tsz = sextract32(tcr, 0, 4) + 8;
11507         select = 0;
11508         hpd = false;
11509         epd = false;
11510     } else if (el == 2) {
11511         /* HTCR */
11512         tsz = extract32(tcr, 0, 3);
11513         select = 0;
11514         hpd = extract64(tcr, 24, 1);
11515         epd = false;
11516     } else {
11517         int t0sz = extract32(tcr, 0, 3);
11518         int t1sz = extract32(tcr, 16, 3);
11519 
11520         if (t1sz == 0) {
11521             select = va > (0xffffffffu >> t0sz);
11522         } else {
11523             /* Note that we will detect errors later.  */
11524             select = va >= ~(0xffffffffu >> t1sz);
11525         }
11526         if (!select) {
11527             tsz = t0sz;
11528             epd = extract32(tcr, 7, 1);
11529             hpd = extract64(tcr, 41, 1);
11530         } else {
11531             tsz = t1sz;
11532             epd = extract32(tcr, 23, 1);
11533             hpd = extract64(tcr, 42, 1);
11534         }
11535         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11536         hpd &= extract32(tcr, 6, 1);
11537     }
11538 
11539     return (ARMVAParameters) {
11540         .tsz = tsz,
11541         .select = select,
11542         .epd = epd,
11543         .hpd = hpd,
11544     };
11545 }
11546 
11547 /**
11548  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
11549  *
11550  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11551  * prot and page_size may not be filled in, and the populated fsr value provides
11552  * information on why the translation aborted, in the format of a long-format
11553  * DFSR/IFSR fault register, with the following caveats:
11554  *  * the WnR bit is never set (the caller must do this).
11555  *
11556  * @env: CPUARMState
11557  * @address: virtual address to get physical address for
11558  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
11559  * @mmu_idx: MMU index indicating required translation regime
11560  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
11561  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
11562  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
11563  * @phys_ptr: set to the physical address corresponding to the virtual address
11564  * @attrs: set to the memory transaction attributes to use
11565  * @prot: set to the permissions for the page containing phys_ptr
11566  * @page_size_ptr: set to the size of the page containing phys_ptr
11567  * @fi: set to fault info if the translation fails
11568  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11569  */
11570 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
11571                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11572                                bool s1_is_el0,
11573                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11574                                target_ulong *page_size_ptr,
11575                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11576 {
11577     ARMCPU *cpu = env_archcpu(env);
11578     CPUState *cs = CPU(cpu);
11579     /* Read an LPAE long-descriptor translation table. */
11580     ARMFaultType fault_type = ARMFault_Translation;
11581     uint32_t level;
11582     ARMVAParameters param;
11583     uint64_t ttbr;
11584     hwaddr descaddr, indexmask, indexmask_grainsize;
11585     uint32_t tableattrs;
11586     target_ulong page_size;
11587     uint32_t attrs;
11588     int32_t stride;
11589     int addrsize, inputsize, outputsize;
11590     TCR *tcr = regime_tcr(env, mmu_idx);
11591     int ap, ns, xn, pxn;
11592     uint32_t el = regime_el(env, mmu_idx);
11593     uint64_t descaddrmask;
11594     bool aarch64 = arm_el_is_aa64(env, el);
11595     bool guarded = false;
11596 
11597     /* TODO: This code does not support shareability levels. */
11598     if (aarch64) {
11599         int ps;
11600 
11601         param = aa64_va_parameters(env, address, mmu_idx,
11602                                    access_type != MMU_INST_FETCH);
11603         level = 0;
11604 
11605         /*
11606          * If TxSZ is programmed to a value larger than the maximum,
11607          * or smaller than the effective minimum, it is IMPLEMENTATION
11608          * DEFINED whether we behave as if the field were programmed
11609          * within bounds, or if a level 0 Translation fault is generated.
11610          *
11611          * With FEAT_LVA, fault on less than minimum becomes required,
11612          * so our choice is to always raise the fault.
11613          */
11614         if (param.tsz_oob) {
11615             fault_type = ARMFault_Translation;
11616             goto do_fault;
11617         }
11618 
11619         addrsize = 64 - 8 * param.tbi;
11620         inputsize = 64 - param.tsz;
11621 
11622         /*
11623          * Bound PS by PARANGE to find the effective output address size.
11624          * ID_AA64MMFR0 is a read-only register so values outside of the
11625          * supported mappings can be considered an implementation error.
11626          */
11627         ps = FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11628         ps = MIN(ps, param.ps);
11629         assert(ps < ARRAY_SIZE(pamax_map));
11630         outputsize = pamax_map[ps];
11631     } else {
11632         param = aa32_va_parameters(env, address, mmu_idx);
11633         level = 1;
11634         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11635         inputsize = addrsize - param.tsz;
11636         outputsize = 40;
11637     }
11638 
11639     /*
11640      * We determined the region when collecting the parameters, but we
11641      * have not yet validated that the address is valid for the region.
11642      * Extract the top bits and verify that they all match select.
11643      *
11644      * For aa32, if inputsize == addrsize, then we have selected the
11645      * region by exclusion in aa32_va_parameters and there is no more
11646      * validation to do here.
11647      */
11648     if (inputsize < addrsize) {
11649         target_ulong top_bits = sextract64(address, inputsize,
11650                                            addrsize - inputsize);
11651         if (-top_bits != param.select) {
11652             /* The gap between the two regions is a Translation fault */
11653             fault_type = ARMFault_Translation;
11654             goto do_fault;
11655         }
11656     }
11657 
11658     if (param.using64k) {
11659         stride = 13;
11660     } else if (param.using16k) {
11661         stride = 11;
11662     } else {
11663         stride = 9;
11664     }
11665 
11666     /* Note that QEMU ignores shareability and cacheability attributes,
11667      * so we don't need to do anything with the SH, ORGN, IRGN fields
11668      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11669      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11670      * implement any ASID-like capability so we can ignore it (instead
11671      * we will always flush the TLB any time the ASID is changed).
11672      */
11673     ttbr = regime_ttbr(env, mmu_idx, param.select);
11674 
11675     /* Here we should have set up all the parameters for the translation:
11676      * inputsize, ttbr, epd, stride, tbi
11677      */
11678 
11679     if (param.epd) {
11680         /* Translation table walk disabled => Translation fault on TLB miss
11681          * Note: This is always 0 on 64-bit EL2 and EL3.
11682          */
11683         goto do_fault;
11684     }
11685 
11686     if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
11687         /* The starting level depends on the virtual address size (which can
11688          * be up to 48 bits) and the translation granule size. It indicates
11689          * the number of strides (stride bits at a time) needed to
11690          * consume the bits of the input address. In the pseudocode this is:
11691          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11692          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11693          * our 'stride + 3' and 'stride' is our 'stride'.
11694          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11695          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11696          * = 4 - (inputsize - 4) / stride;
11697          */
11698         level = 4 - (inputsize - 4) / stride;
11699     } else {
11700         /* For stage 2 translations the starting level is specified by the
11701          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11702          */
11703         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11704         uint32_t sl2 = extract64(tcr->raw_tcr, 33, 1);
11705         uint32_t startlevel;
11706         bool ok;
11707 
11708         /* SL2 is RES0 unless DS=1 & 4kb granule. */
11709         if (param.ds && stride == 9 && sl2) {
11710             if (sl0 != 0) {
11711                 level = 0;
11712                 fault_type = ARMFault_Translation;
11713                 goto do_fault;
11714             }
11715             startlevel = -1;
11716         } else if (!aarch64 || stride == 9) {
11717             /* AArch32 or 4KB pages */
11718             startlevel = 2 - sl0;
11719 
11720             if (cpu_isar_feature(aa64_st, cpu)) {
11721                 startlevel &= 3;
11722             }
11723         } else {
11724             /* 16KB or 64KB pages */
11725             startlevel = 3 - sl0;
11726         }
11727 
11728         /* Check that the starting level is valid. */
11729         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11730                                 inputsize, stride, outputsize);
11731         if (!ok) {
11732             fault_type = ARMFault_Translation;
11733             goto do_fault;
11734         }
11735         level = startlevel;
11736     }
11737 
11738     indexmask_grainsize = MAKE_64BIT_MASK(0, stride + 3);
11739     indexmask = MAKE_64BIT_MASK(0, inputsize - (stride * (4 - level)));
11740 
11741     /* Now we can extract the actual base address from the TTBR */
11742     descaddr = extract64(ttbr, 0, 48);
11743 
11744     /*
11745      * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [5:2] of TTBR.
11746      *
11747      * Otherwise, if the base address is out of range, raise AddressSizeFault.
11748      * In the pseudocode, this is !IsZero(baseregister<47:outputsize>),
11749      * but we've just cleared the bits above 47, so simplify the test.
11750      */
11751     if (outputsize > 48) {
11752         descaddr |= extract64(ttbr, 2, 4) << 48;
11753     } else if (descaddr >> outputsize) {
11754         level = 0;
11755         fault_type = ARMFault_AddressSize;
11756         goto do_fault;
11757     }
11758 
11759     /*
11760      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11761      * and also to mask out CnP (bit 0) which could validly be non-zero.
11762      */
11763     descaddr &= ~indexmask;
11764 
11765     /*
11766      * For AArch32, the address field in the descriptor goes up to bit 39
11767      * for both v7 and v8.  However, for v8 the SBZ bits [47:40] must be 0
11768      * or an AddressSize fault is raised.  So for v8 we extract those SBZ
11769      * bits as part of the address, which will be checked via outputsize.
11770      * For AArch64, the address field goes up to bit 47, or 49 with FEAT_LPA2;
11771      * the highest bits of a 52-bit output are placed elsewhere.
11772      */
11773     if (param.ds) {
11774         descaddrmask = MAKE_64BIT_MASK(0, 50);
11775     } else if (arm_feature(env, ARM_FEATURE_V8)) {
11776         descaddrmask = MAKE_64BIT_MASK(0, 48);
11777     } else {
11778         descaddrmask = MAKE_64BIT_MASK(0, 40);
11779     }
11780     descaddrmask &= ~indexmask_grainsize;
11781 
11782     /* Secure accesses start with the page table in secure memory and
11783      * can be downgraded to non-secure at any step. Non-secure accesses
11784      * remain non-secure. We implement this by just ORing in the NSTable/NS
11785      * bits at each step.
11786      */
11787     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11788     for (;;) {
11789         uint64_t descriptor;
11790         bool nstable;
11791 
11792         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11793         descaddr &= ~7ULL;
11794         nstable = extract32(tableattrs, 4, 1);
11795         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11796         if (fi->type != ARMFault_None) {
11797             goto do_fault;
11798         }
11799 
11800         if (!(descriptor & 1) ||
11801             (!(descriptor & 2) && (level == 3))) {
11802             /* Invalid, or the Reserved level 3 encoding */
11803             goto do_fault;
11804         }
11805 
11806         descaddr = descriptor & descaddrmask;
11807 
11808         /*
11809          * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [15:12]
11810          * of descriptor.  For FEAT_LPA2 and effective DS, bits [51:50] of
11811          * descaddr are in [9:8].  Otherwise, if descaddr is out of range,
11812          * raise AddressSizeFault.
11813          */
11814         if (outputsize > 48) {
11815             if (param.ds) {
11816                 descaddr |= extract64(descriptor, 8, 2) << 50;
11817             } else {
11818                 descaddr |= extract64(descriptor, 12, 4) << 48;
11819             }
11820         } else if (descaddr >> outputsize) {
11821             fault_type = ARMFault_AddressSize;
11822             goto do_fault;
11823         }
11824 
11825         if ((descriptor & 2) && (level < 3)) {
11826             /* Table entry. The top five bits are attributes which may
11827              * propagate down through lower levels of the table (and
11828              * which are all arranged so that 0 means "no effect", so
11829              * we can gather them up by ORing in the bits at each level).
11830              */
11831             tableattrs |= extract64(descriptor, 59, 5);
11832             level++;
11833             indexmask = indexmask_grainsize;
11834             continue;
11835         }
11836         /*
11837          * Block entry at level 1 or 2, or page entry at level 3.
11838          * These are basically the same thing, although the number
11839          * of bits we pull in from the vaddr varies. Note that although
11840          * descaddrmask masks enough of the low bits of the descriptor
11841          * to give a correct page or table address, the address field
11842          * in a block descriptor is smaller; so we need to explicitly
11843          * clear the lower bits here before ORing in the low vaddr bits.
11844          */
11845         page_size = (1ULL << ((stride * (4 - level)) + 3));
11846         descaddr &= ~(page_size - 1);
11847         descaddr |= (address & (page_size - 1));
11848         /* Extract attributes from the descriptor */
11849         attrs = extract64(descriptor, 2, 10)
11850             | (extract64(descriptor, 52, 12) << 10);
11851 
11852         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11853             /* Stage 2 table descriptors do not include any attribute fields */
11854             break;
11855         }
11856         /* Merge in attributes from table descriptors */
11857         attrs |= nstable << 3; /* NS */
11858         guarded = extract64(descriptor, 50, 1);  /* GP */
11859         if (param.hpd) {
11860             /* HPD disables all the table attributes except NSTable.  */
11861             break;
11862         }
11863         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11864         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11865          * means "force PL1 access only", which means forcing AP[1] to 0.
11866          */
11867         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11868         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11869         break;
11870     }
11871     /* Here descaddr is the final physical address, and attributes
11872      * are all in attrs.
11873      */
11874     fault_type = ARMFault_AccessFlag;
11875     if ((attrs & (1 << 8)) == 0) {
11876         /* Access flag */
11877         goto do_fault;
11878     }
11879 
11880     ap = extract32(attrs, 4, 2);
11881 
11882     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11883         ns = mmu_idx == ARMMMUIdx_Stage2;
11884         xn = extract32(attrs, 11, 2);
11885         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11886     } else {
11887         ns = extract32(attrs, 3, 1);
11888         xn = extract32(attrs, 12, 1);
11889         pxn = extract32(attrs, 11, 1);
11890         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11891     }
11892 
11893     fault_type = ARMFault_Permission;
11894     if (!(*prot & (1 << access_type))) {
11895         goto do_fault;
11896     }
11897 
11898     if (ns) {
11899         /* The NS bit will (as required by the architecture) have no effect if
11900          * the CPU doesn't support TZ or this is a non-secure translation
11901          * regime, because the attribute will already be non-secure.
11902          */
11903         txattrs->secure = false;
11904     }
11905     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11906     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11907         arm_tlb_bti_gp(txattrs) = true;
11908     }
11909 
11910     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11911         cacheattrs->is_s2_format = true;
11912         cacheattrs->attrs = extract32(attrs, 0, 4);
11913     } else {
11914         /* Index into MAIR registers for cache attributes */
11915         uint8_t attrindx = extract32(attrs, 0, 3);
11916         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11917         assert(attrindx <= 7);
11918         cacheattrs->is_s2_format = false;
11919         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11920     }
11921 
11922     /*
11923      * For FEAT_LPA2 and effective DS, the SH field in the attributes
11924      * was re-purposed for output address bits.  The SH attribute in
11925      * that case comes from TCR_ELx, which we extracted earlier.
11926      */
11927     if (param.ds) {
11928         cacheattrs->shareability = param.sh;
11929     } else {
11930         cacheattrs->shareability = extract32(attrs, 6, 2);
11931     }
11932 
11933     *phys_ptr = descaddr;
11934     *page_size_ptr = page_size;
11935     return false;
11936 
11937 do_fault:
11938     fi->type = fault_type;
11939     fi->level = level;
11940     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11941     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2 ||
11942                                mmu_idx == ARMMMUIdx_Stage2_S);
11943     fi->s1ns = mmu_idx == ARMMMUIdx_Stage2;
11944     return true;
11945 }
11946 
11947 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11948                                                 ARMMMUIdx mmu_idx,
11949                                                 int32_t address, int *prot)
11950 {
11951     if (!arm_feature(env, ARM_FEATURE_M)) {
11952         *prot = PAGE_READ | PAGE_WRITE;
11953         switch (address) {
11954         case 0xF0000000 ... 0xFFFFFFFF:
11955             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11956                 /* hivecs execing is ok */
11957                 *prot |= PAGE_EXEC;
11958             }
11959             break;
11960         case 0x00000000 ... 0x7FFFFFFF:
11961             *prot |= PAGE_EXEC;
11962             break;
11963         }
11964     } else {
11965         /* Default system address map for M profile cores.
11966          * The architecture specifies which regions are execute-never;
11967          * at the MPU level no other checks are defined.
11968          */
11969         switch (address) {
11970         case 0x00000000 ... 0x1fffffff: /* ROM */
11971         case 0x20000000 ... 0x3fffffff: /* SRAM */
11972         case 0x60000000 ... 0x7fffffff: /* RAM */
11973         case 0x80000000 ... 0x9fffffff: /* RAM */
11974             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11975             break;
11976         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11977         case 0xa0000000 ... 0xbfffffff: /* Device */
11978         case 0xc0000000 ... 0xdfffffff: /* Device */
11979         case 0xe0000000 ... 0xffffffff: /* System */
11980             *prot = PAGE_READ | PAGE_WRITE;
11981             break;
11982         default:
11983             g_assert_not_reached();
11984         }
11985     }
11986 }
11987 
11988 static bool pmsav7_use_background_region(ARMCPU *cpu,
11989                                          ARMMMUIdx mmu_idx, bool is_user)
11990 {
11991     /* Return true if we should use the default memory map as a
11992      * "background" region if there are no hits against any MPU regions.
11993      */
11994     CPUARMState *env = &cpu->env;
11995 
11996     if (is_user) {
11997         return false;
11998     }
11999 
12000     if (arm_feature(env, ARM_FEATURE_M)) {
12001         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
12002             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
12003     } else {
12004         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
12005     }
12006 }
12007 
12008 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
12009 {
12010     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
12011     return arm_feature(env, ARM_FEATURE_M) &&
12012         extract32(address, 20, 12) == 0xe00;
12013 }
12014 
12015 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
12016 {
12017     /* True if address is in the M profile system region
12018      * 0xe0000000 - 0xffffffff
12019      */
12020     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
12021 }
12022 
12023 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
12024                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12025                                  hwaddr *phys_ptr, int *prot,
12026                                  target_ulong *page_size,
12027                                  ARMMMUFaultInfo *fi)
12028 {
12029     ARMCPU *cpu = env_archcpu(env);
12030     int n;
12031     bool is_user = regime_is_user(env, mmu_idx);
12032 
12033     *phys_ptr = address;
12034     *page_size = TARGET_PAGE_SIZE;
12035     *prot = 0;
12036 
12037     if (regime_translation_disabled(env, mmu_idx) ||
12038         m_is_ppb_region(env, address)) {
12039         /* MPU disabled or M profile PPB access: use default memory map.
12040          * The other case which uses the default memory map in the
12041          * v7M ARM ARM pseudocode is exception vector reads from the vector
12042          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
12043          * which always does a direct read using address_space_ldl(), rather
12044          * than going via this function, so we don't need to check that here.
12045          */
12046         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12047     } else { /* MPU enabled */
12048         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12049             /* region search */
12050             uint32_t base = env->pmsav7.drbar[n];
12051             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
12052             uint32_t rmask;
12053             bool srdis = false;
12054 
12055             if (!(env->pmsav7.drsr[n] & 0x1)) {
12056                 continue;
12057             }
12058 
12059             if (!rsize) {
12060                 qemu_log_mask(LOG_GUEST_ERROR,
12061                               "DRSR[%d]: Rsize field cannot be 0\n", n);
12062                 continue;
12063             }
12064             rsize++;
12065             rmask = (1ull << rsize) - 1;
12066 
12067             if (base & rmask) {
12068                 qemu_log_mask(LOG_GUEST_ERROR,
12069                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
12070                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
12071                               n, base, rmask);
12072                 continue;
12073             }
12074 
12075             if (address < base || address > base + rmask) {
12076                 /*
12077                  * Address not in this region. We must check whether the
12078                  * region covers addresses in the same page as our address.
12079                  * In that case we must not report a size that covers the
12080                  * whole page for a subsequent hit against a different MPU
12081                  * region or the background region, because it would result in
12082                  * incorrect TLB hits for subsequent accesses to addresses that
12083                  * are in this MPU region.
12084                  */
12085                 if (ranges_overlap(base, rmask,
12086                                    address & TARGET_PAGE_MASK,
12087                                    TARGET_PAGE_SIZE)) {
12088                     *page_size = 1;
12089                 }
12090                 continue;
12091             }
12092 
12093             /* Region matched */
12094 
12095             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
12096                 int i, snd;
12097                 uint32_t srdis_mask;
12098 
12099                 rsize -= 3; /* sub region size (power of 2) */
12100                 snd = ((address - base) >> rsize) & 0x7;
12101                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
12102 
12103                 srdis_mask = srdis ? 0x3 : 0x0;
12104                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
12105                     /* This will check in groups of 2, 4 and then 8, whether
12106                      * the subregion bits are consistent. rsize is incremented
12107                      * back up to give the region size, considering consistent
12108                      * adjacent subregions as one region. Stop testing if rsize
12109                      * is already big enough for an entire QEMU page.
12110                      */
12111                     int snd_rounded = snd & ~(i - 1);
12112                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
12113                                                      snd_rounded + 8, i);
12114                     if (srdis_mask ^ srdis_multi) {
12115                         break;
12116                     }
12117                     srdis_mask = (srdis_mask << i) | srdis_mask;
12118                     rsize++;
12119                 }
12120             }
12121             if (srdis) {
12122                 continue;
12123             }
12124             if (rsize < TARGET_PAGE_BITS) {
12125                 *page_size = 1 << rsize;
12126             }
12127             break;
12128         }
12129 
12130         if (n == -1) { /* no hits */
12131             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12132                 /* background fault */
12133                 fi->type = ARMFault_Background;
12134                 return true;
12135             }
12136             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12137         } else { /* a MPU hit! */
12138             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
12139             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
12140 
12141             if (m_is_system_region(env, address)) {
12142                 /* System space is always execute never */
12143                 xn = 1;
12144             }
12145 
12146             if (is_user) { /* User mode AP bit decoding */
12147                 switch (ap) {
12148                 case 0:
12149                 case 1:
12150                 case 5:
12151                     break; /* no access */
12152                 case 3:
12153                     *prot |= PAGE_WRITE;
12154                     /* fall through */
12155                 case 2:
12156                 case 6:
12157                     *prot |= PAGE_READ | PAGE_EXEC;
12158                     break;
12159                 case 7:
12160                     /* for v7M, same as 6; for R profile a reserved value */
12161                     if (arm_feature(env, ARM_FEATURE_M)) {
12162                         *prot |= PAGE_READ | PAGE_EXEC;
12163                         break;
12164                     }
12165                     /* fall through */
12166                 default:
12167                     qemu_log_mask(LOG_GUEST_ERROR,
12168                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12169                                   PRIx32 "\n", n, ap);
12170                 }
12171             } else { /* Priv. mode AP bits decoding */
12172                 switch (ap) {
12173                 case 0:
12174                     break; /* no access */
12175                 case 1:
12176                 case 2:
12177                 case 3:
12178                     *prot |= PAGE_WRITE;
12179                     /* fall through */
12180                 case 5:
12181                 case 6:
12182                     *prot |= PAGE_READ | PAGE_EXEC;
12183                     break;
12184                 case 7:
12185                     /* for v7M, same as 6; for R profile a reserved value */
12186                     if (arm_feature(env, ARM_FEATURE_M)) {
12187                         *prot |= PAGE_READ | PAGE_EXEC;
12188                         break;
12189                     }
12190                     /* fall through */
12191                 default:
12192                     qemu_log_mask(LOG_GUEST_ERROR,
12193                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12194                                   PRIx32 "\n", n, ap);
12195                 }
12196             }
12197 
12198             /* execute never */
12199             if (xn) {
12200                 *prot &= ~PAGE_EXEC;
12201             }
12202         }
12203     }
12204 
12205     fi->type = ARMFault_Permission;
12206     fi->level = 1;
12207     return !(*prot & (1 << access_type));
12208 }
12209 
12210 static bool v8m_is_sau_exempt(CPUARMState *env,
12211                               uint32_t address, MMUAccessType access_type)
12212 {
12213     /* The architecture specifies that certain address ranges are
12214      * exempt from v8M SAU/IDAU checks.
12215      */
12216     return
12217         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
12218         (address >= 0xe0000000 && address <= 0xe0002fff) ||
12219         (address >= 0xe000e000 && address <= 0xe000efff) ||
12220         (address >= 0xe002e000 && address <= 0xe002efff) ||
12221         (address >= 0xe0040000 && address <= 0xe0041fff) ||
12222         (address >= 0xe00ff000 && address <= 0xe00fffff);
12223 }
12224 
12225 void v8m_security_lookup(CPUARMState *env, uint32_t address,
12226                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
12227                                 V8M_SAttributes *sattrs)
12228 {
12229     /* Look up the security attributes for this address. Compare the
12230      * pseudocode SecurityCheck() function.
12231      * We assume the caller has zero-initialized *sattrs.
12232      */
12233     ARMCPU *cpu = env_archcpu(env);
12234     int r;
12235     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
12236     int idau_region = IREGION_NOTVALID;
12237     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12238     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12239 
12240     if (cpu->idau) {
12241         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
12242         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
12243 
12244         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
12245                    &idau_nsc);
12246     }
12247 
12248     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
12249         /* 0xf0000000..0xffffffff is always S for insn fetches */
12250         return;
12251     }
12252 
12253     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
12254         sattrs->ns = !regime_is_secure(env, mmu_idx);
12255         return;
12256     }
12257 
12258     if (idau_region != IREGION_NOTVALID) {
12259         sattrs->irvalid = true;
12260         sattrs->iregion = idau_region;
12261     }
12262 
12263     switch (env->sau.ctrl & 3) {
12264     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
12265         break;
12266     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
12267         sattrs->ns = true;
12268         break;
12269     default: /* SAU.ENABLE == 1 */
12270         for (r = 0; r < cpu->sau_sregion; r++) {
12271             if (env->sau.rlar[r] & 1) {
12272                 uint32_t base = env->sau.rbar[r] & ~0x1f;
12273                 uint32_t limit = env->sau.rlar[r] | 0x1f;
12274 
12275                 if (base <= address && limit >= address) {
12276                     if (base > addr_page_base || limit < addr_page_limit) {
12277                         sattrs->subpage = true;
12278                     }
12279                     if (sattrs->srvalid) {
12280                         /* If we hit in more than one region then we must report
12281                          * as Secure, not NS-Callable, with no valid region
12282                          * number info.
12283                          */
12284                         sattrs->ns = false;
12285                         sattrs->nsc = false;
12286                         sattrs->sregion = 0;
12287                         sattrs->srvalid = false;
12288                         break;
12289                     } else {
12290                         if (env->sau.rlar[r] & 2) {
12291                             sattrs->nsc = true;
12292                         } else {
12293                             sattrs->ns = true;
12294                         }
12295                         sattrs->srvalid = true;
12296                         sattrs->sregion = r;
12297                     }
12298                 } else {
12299                     /*
12300                      * Address not in this region. We must check whether the
12301                      * region covers addresses in the same page as our address.
12302                      * In that case we must not report a size that covers the
12303                      * whole page for a subsequent hit against a different MPU
12304                      * region or the background region, because it would result
12305                      * in incorrect TLB hits for subsequent accesses to
12306                      * addresses that are in this MPU region.
12307                      */
12308                     if (limit >= base &&
12309                         ranges_overlap(base, limit - base + 1,
12310                                        addr_page_base,
12311                                        TARGET_PAGE_SIZE)) {
12312                         sattrs->subpage = true;
12313                     }
12314                 }
12315             }
12316         }
12317         break;
12318     }
12319 
12320     /*
12321      * The IDAU will override the SAU lookup results if it specifies
12322      * higher security than the SAU does.
12323      */
12324     if (!idau_ns) {
12325         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12326             sattrs->ns = false;
12327             sattrs->nsc = idau_nsc;
12328         }
12329     }
12330 }
12331 
12332 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12333                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12334                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12335                               int *prot, bool *is_subpage,
12336                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12337 {
12338     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12339      * that a full phys-to-virt translation does).
12340      * mregion is (if not NULL) set to the region number which matched,
12341      * or -1 if no region number is returned (MPU off, address did not
12342      * hit a region, address hit in multiple regions).
12343      * We set is_subpage to true if the region hit doesn't cover the
12344      * entire TARGET_PAGE the address is within.
12345      */
12346     ARMCPU *cpu = env_archcpu(env);
12347     bool is_user = regime_is_user(env, mmu_idx);
12348     uint32_t secure = regime_is_secure(env, mmu_idx);
12349     int n;
12350     int matchregion = -1;
12351     bool hit = false;
12352     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12353     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12354 
12355     *is_subpage = false;
12356     *phys_ptr = address;
12357     *prot = 0;
12358     if (mregion) {
12359         *mregion = -1;
12360     }
12361 
12362     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12363      * was an exception vector read from the vector table (which is always
12364      * done using the default system address map), because those accesses
12365      * are done in arm_v7m_load_vector(), which always does a direct
12366      * read using address_space_ldl(), rather than going via this function.
12367      */
12368     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12369         hit = true;
12370     } else if (m_is_ppb_region(env, address)) {
12371         hit = true;
12372     } else {
12373         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12374             hit = true;
12375         }
12376 
12377         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12378             /* region search */
12379             /* Note that the base address is bits [31:5] from the register
12380              * with bits [4:0] all zeroes, but the limit address is bits
12381              * [31:5] from the register with bits [4:0] all ones.
12382              */
12383             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12384             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12385 
12386             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12387                 /* Region disabled */
12388                 continue;
12389             }
12390 
12391             if (address < base || address > limit) {
12392                 /*
12393                  * Address not in this region. We must check whether the
12394                  * region covers addresses in the same page as our address.
12395                  * In that case we must not report a size that covers the
12396                  * whole page for a subsequent hit against a different MPU
12397                  * region or the background region, because it would result in
12398                  * incorrect TLB hits for subsequent accesses to addresses that
12399                  * are in this MPU region.
12400                  */
12401                 if (limit >= base &&
12402                     ranges_overlap(base, limit - base + 1,
12403                                    addr_page_base,
12404                                    TARGET_PAGE_SIZE)) {
12405                     *is_subpage = true;
12406                 }
12407                 continue;
12408             }
12409 
12410             if (base > addr_page_base || limit < addr_page_limit) {
12411                 *is_subpage = true;
12412             }
12413 
12414             if (matchregion != -1) {
12415                 /* Multiple regions match -- always a failure (unlike
12416                  * PMSAv7 where highest-numbered-region wins)
12417                  */
12418                 fi->type = ARMFault_Permission;
12419                 fi->level = 1;
12420                 return true;
12421             }
12422 
12423             matchregion = n;
12424             hit = true;
12425         }
12426     }
12427 
12428     if (!hit) {
12429         /* background fault */
12430         fi->type = ARMFault_Background;
12431         return true;
12432     }
12433 
12434     if (matchregion == -1) {
12435         /* hit using the background region */
12436         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12437     } else {
12438         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12439         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12440         bool pxn = false;
12441 
12442         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
12443             pxn = extract32(env->pmsav8.rlar[secure][matchregion], 4, 1);
12444         }
12445 
12446         if (m_is_system_region(env, address)) {
12447             /* System space is always execute never */
12448             xn = 1;
12449         }
12450 
12451         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12452         if (*prot && !xn && !(pxn && !is_user)) {
12453             *prot |= PAGE_EXEC;
12454         }
12455         /* We don't need to look the attribute up in the MAIR0/MAIR1
12456          * registers because that only tells us about cacheability.
12457          */
12458         if (mregion) {
12459             *mregion = matchregion;
12460         }
12461     }
12462 
12463     fi->type = ARMFault_Permission;
12464     fi->level = 1;
12465     return !(*prot & (1 << access_type));
12466 }
12467 
12468 
12469 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12470                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12471                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12472                                  int *prot, target_ulong *page_size,
12473                                  ARMMMUFaultInfo *fi)
12474 {
12475     uint32_t secure = regime_is_secure(env, mmu_idx);
12476     V8M_SAttributes sattrs = {};
12477     bool ret;
12478     bool mpu_is_subpage;
12479 
12480     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12481         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12482         if (access_type == MMU_INST_FETCH) {
12483             /* Instruction fetches always use the MMU bank and the
12484              * transaction attribute determined by the fetch address,
12485              * regardless of CPU state. This is painful for QEMU
12486              * to handle, because it would mean we need to encode
12487              * into the mmu_idx not just the (user, negpri) information
12488              * for the current security state but also that for the
12489              * other security state, which would balloon the number
12490              * of mmu_idx values needed alarmingly.
12491              * Fortunately we can avoid this because it's not actually
12492              * possible to arbitrarily execute code from memory with
12493              * the wrong security attribute: it will always generate
12494              * an exception of some kind or another, apart from the
12495              * special case of an NS CPU executing an SG instruction
12496              * in S&NSC memory. So we always just fail the translation
12497              * here and sort things out in the exception handler
12498              * (including possibly emulating an SG instruction).
12499              */
12500             if (sattrs.ns != !secure) {
12501                 if (sattrs.nsc) {
12502                     fi->type = ARMFault_QEMU_NSCExec;
12503                 } else {
12504                     fi->type = ARMFault_QEMU_SFault;
12505                 }
12506                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12507                 *phys_ptr = address;
12508                 *prot = 0;
12509                 return true;
12510             }
12511         } else {
12512             /* For data accesses we always use the MMU bank indicated
12513              * by the current CPU state, but the security attributes
12514              * might downgrade a secure access to nonsecure.
12515              */
12516             if (sattrs.ns) {
12517                 txattrs->secure = false;
12518             } else if (!secure) {
12519                 /* NS access to S memory must fault.
12520                  * Architecturally we should first check whether the
12521                  * MPU information for this address indicates that we
12522                  * are doing an unaligned access to Device memory, which
12523                  * should generate a UsageFault instead. QEMU does not
12524                  * currently check for that kind of unaligned access though.
12525                  * If we added it we would need to do so as a special case
12526                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12527                  */
12528                 fi->type = ARMFault_QEMU_SFault;
12529                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12530                 *phys_ptr = address;
12531                 *prot = 0;
12532                 return true;
12533             }
12534         }
12535     }
12536 
12537     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12538                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12539     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12540     return ret;
12541 }
12542 
12543 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12544                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12545                                  hwaddr *phys_ptr, int *prot,
12546                                  ARMMMUFaultInfo *fi)
12547 {
12548     int n;
12549     uint32_t mask;
12550     uint32_t base;
12551     bool is_user = regime_is_user(env, mmu_idx);
12552 
12553     if (regime_translation_disabled(env, mmu_idx)) {
12554         /* MPU disabled.  */
12555         *phys_ptr = address;
12556         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12557         return false;
12558     }
12559 
12560     *phys_ptr = address;
12561     for (n = 7; n >= 0; n--) {
12562         base = env->cp15.c6_region[n];
12563         if ((base & 1) == 0) {
12564             continue;
12565         }
12566         mask = 1 << ((base >> 1) & 0x1f);
12567         /* Keep this shift separate from the above to avoid an
12568            (undefined) << 32.  */
12569         mask = (mask << 1) - 1;
12570         if (((base ^ address) & ~mask) == 0) {
12571             break;
12572         }
12573     }
12574     if (n < 0) {
12575         fi->type = ARMFault_Background;
12576         return true;
12577     }
12578 
12579     if (access_type == MMU_INST_FETCH) {
12580         mask = env->cp15.pmsav5_insn_ap;
12581     } else {
12582         mask = env->cp15.pmsav5_data_ap;
12583     }
12584     mask = (mask >> (n * 4)) & 0xf;
12585     switch (mask) {
12586     case 0:
12587         fi->type = ARMFault_Permission;
12588         fi->level = 1;
12589         return true;
12590     case 1:
12591         if (is_user) {
12592             fi->type = ARMFault_Permission;
12593             fi->level = 1;
12594             return true;
12595         }
12596         *prot = PAGE_READ | PAGE_WRITE;
12597         break;
12598     case 2:
12599         *prot = PAGE_READ;
12600         if (!is_user) {
12601             *prot |= PAGE_WRITE;
12602         }
12603         break;
12604     case 3:
12605         *prot = PAGE_READ | PAGE_WRITE;
12606         break;
12607     case 5:
12608         if (is_user) {
12609             fi->type = ARMFault_Permission;
12610             fi->level = 1;
12611             return true;
12612         }
12613         *prot = PAGE_READ;
12614         break;
12615     case 6:
12616         *prot = PAGE_READ;
12617         break;
12618     default:
12619         /* Bad permission.  */
12620         fi->type = ARMFault_Permission;
12621         fi->level = 1;
12622         return true;
12623     }
12624     *prot |= PAGE_EXEC;
12625     return false;
12626 }
12627 
12628 /* Combine either inner or outer cacheability attributes for normal
12629  * memory, according to table D4-42 and pseudocode procedure
12630  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12631  *
12632  * NB: only stage 1 includes allocation hints (RW bits), leading to
12633  * some asymmetry.
12634  */
12635 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12636 {
12637     if (s1 == 4 || s2 == 4) {
12638         /* non-cacheable has precedence */
12639         return 4;
12640     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12641         /* stage 1 write-through takes precedence */
12642         return s1;
12643     } else if (extract32(s2, 2, 2) == 2) {
12644         /* stage 2 write-through takes precedence, but the allocation hint
12645          * is still taken from stage 1
12646          */
12647         return (2 << 2) | extract32(s1, 0, 2);
12648     } else { /* write-back */
12649         return s1;
12650     }
12651 }
12652 
12653 /*
12654  * Combine the memory type and cacheability attributes of
12655  * s1 and s2 for the HCR_EL2.FWB == 0 case, returning the
12656  * combined attributes in MAIR_EL1 format.
12657  */
12658 static uint8_t combined_attrs_nofwb(CPUARMState *env,
12659                                     ARMCacheAttrs s1, ARMCacheAttrs s2)
12660 {
12661     uint8_t s1lo, s2lo, s1hi, s2hi, s2_mair_attrs, ret_attrs;
12662 
12663     s2_mair_attrs = convert_stage2_attrs(env, s2.attrs);
12664 
12665     s1lo = extract32(s1.attrs, 0, 4);
12666     s2lo = extract32(s2_mair_attrs, 0, 4);
12667     s1hi = extract32(s1.attrs, 4, 4);
12668     s2hi = extract32(s2_mair_attrs, 4, 4);
12669 
12670     /* Combine memory type and cacheability attributes */
12671     if (s1hi == 0 || s2hi == 0) {
12672         /* Device has precedence over normal */
12673         if (s1lo == 0 || s2lo == 0) {
12674             /* nGnRnE has precedence over anything */
12675             ret_attrs = 0;
12676         } else if (s1lo == 4 || s2lo == 4) {
12677             /* non-Reordering has precedence over Reordering */
12678             ret_attrs = 4;  /* nGnRE */
12679         } else if (s1lo == 8 || s2lo == 8) {
12680             /* non-Gathering has precedence over Gathering */
12681             ret_attrs = 8;  /* nGRE */
12682         } else {
12683             ret_attrs = 0xc; /* GRE */
12684         }
12685     } else { /* Normal memory */
12686         /* Outer/inner cacheability combine independently */
12687         ret_attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12688                   | combine_cacheattr_nibble(s1lo, s2lo);
12689     }
12690     return ret_attrs;
12691 }
12692 
12693 static uint8_t force_cacheattr_nibble_wb(uint8_t attr)
12694 {
12695     /*
12696      * Given the 4 bits specifying the outer or inner cacheability
12697      * in MAIR format, return a value specifying Normal Write-Back,
12698      * with the allocation and transient hints taken from the input
12699      * if the input specified some kind of cacheable attribute.
12700      */
12701     if (attr == 0 || attr == 4) {
12702         /*
12703          * 0 == an UNPREDICTABLE encoding
12704          * 4 == Non-cacheable
12705          * Either way, force Write-Back RW allocate non-transient
12706          */
12707         return 0xf;
12708     }
12709     /* Change WriteThrough to WriteBack, keep allocation and transient hints */
12710     return attr | 4;
12711 }
12712 
12713 /*
12714  * Combine the memory type and cacheability attributes of
12715  * s1 and s2 for the HCR_EL2.FWB == 1 case, returning the
12716  * combined attributes in MAIR_EL1 format.
12717  */
12718 static uint8_t combined_attrs_fwb(CPUARMState *env,
12719                                   ARMCacheAttrs s1, ARMCacheAttrs s2)
12720 {
12721     switch (s2.attrs) {
12722     case 7:
12723         /* Use stage 1 attributes */
12724         return s1.attrs;
12725     case 6:
12726         /*
12727          * Force Normal Write-Back. Note that if S1 is Normal cacheable
12728          * then we take the allocation hints from it; otherwise it is
12729          * RW allocate, non-transient.
12730          */
12731         if ((s1.attrs & 0xf0) == 0) {
12732             /* S1 is Device */
12733             return 0xff;
12734         }
12735         /* Need to check the Inner and Outer nibbles separately */
12736         return force_cacheattr_nibble_wb(s1.attrs & 0xf) |
12737             force_cacheattr_nibble_wb(s1.attrs >> 4) << 4;
12738     case 5:
12739         /* If S1 attrs are Device, use them; otherwise Normal Non-cacheable */
12740         if ((s1.attrs & 0xf0) == 0) {
12741             return s1.attrs;
12742         }
12743         return 0x44;
12744     case 0 ... 3:
12745         /* Force Device, of subtype specified by S2 */
12746         return s2.attrs << 2;
12747     default:
12748         /*
12749          * RESERVED values (including RES0 descriptor bit [5] being nonzero);
12750          * arbitrarily force Device.
12751          */
12752         return 0;
12753     }
12754 }
12755 
12756 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12757  * and CombineS1S2Desc()
12758  *
12759  * @env:     CPUARMState
12760  * @s1:      Attributes from stage 1 walk
12761  * @s2:      Attributes from stage 2 walk
12762  */
12763 static ARMCacheAttrs combine_cacheattrs(CPUARMState *env,
12764                                         ARMCacheAttrs s1, ARMCacheAttrs s2)
12765 {
12766     ARMCacheAttrs ret;
12767     bool tagged = false;
12768 
12769     assert(s2.is_s2_format && !s1.is_s2_format);
12770     ret.is_s2_format = false;
12771 
12772     if (s1.attrs == 0xf0) {
12773         tagged = true;
12774         s1.attrs = 0xff;
12775     }
12776 
12777     /* Combine shareability attributes (table D4-43) */
12778     if (s1.shareability == 2 || s2.shareability == 2) {
12779         /* if either are outer-shareable, the result is outer-shareable */
12780         ret.shareability = 2;
12781     } else if (s1.shareability == 3 || s2.shareability == 3) {
12782         /* if either are inner-shareable, the result is inner-shareable */
12783         ret.shareability = 3;
12784     } else {
12785         /* both non-shareable */
12786         ret.shareability = 0;
12787     }
12788 
12789     /* Combine memory type and cacheability attributes */
12790     if (arm_hcr_el2_eff(env) & HCR_FWB) {
12791         ret.attrs = combined_attrs_fwb(env, s1, s2);
12792     } else {
12793         ret.attrs = combined_attrs_nofwb(env, s1, s2);
12794     }
12795 
12796     /*
12797      * Any location for which the resultant memory type is any
12798      * type of Device memory is always treated as Outer Shareable.
12799      * Any location for which the resultant memory type is Normal
12800      * Inner Non-cacheable, Outer Non-cacheable is always treated
12801      * as Outer Shareable.
12802      * TODO: FEAT_XS adds another value (0x40) also meaning iNCoNC
12803      */
12804     if ((ret.attrs & 0xf0) == 0 || ret.attrs == 0x44) {
12805         ret.shareability = 2;
12806     }
12807 
12808     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12809     if (tagged && ret.attrs == 0xff) {
12810         ret.attrs = 0xf0;
12811     }
12812 
12813     return ret;
12814 }
12815 
12816 
12817 /* get_phys_addr - get the physical address for this virtual address
12818  *
12819  * Find the physical address corresponding to the given virtual address,
12820  * by doing a translation table walk on MMU based systems or using the
12821  * MPU state on MPU based systems.
12822  *
12823  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12824  * prot and page_size may not be filled in, and the populated fsr value provides
12825  * information on why the translation aborted, in the format of a
12826  * DFSR/IFSR fault register, with the following caveats:
12827  *  * we honour the short vs long DFSR format differences.
12828  *  * the WnR bit is never set (the caller must do this).
12829  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12830  *    value.
12831  *
12832  * @env: CPUARMState
12833  * @address: virtual address to get physical address for
12834  * @access_type: 0 for read, 1 for write, 2 for execute
12835  * @mmu_idx: MMU index indicating required translation regime
12836  * @phys_ptr: set to the physical address corresponding to the virtual address
12837  * @attrs: set to the memory transaction attributes to use
12838  * @prot: set to the permissions for the page containing phys_ptr
12839  * @page_size: set to the size of the page containing phys_ptr
12840  * @fi: set to fault info if the translation fails
12841  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12842  */
12843 bool get_phys_addr(CPUARMState *env, target_ulong address,
12844                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12845                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12846                    target_ulong *page_size,
12847                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12848 {
12849     ARMMMUIdx s1_mmu_idx = stage_1_mmu_idx(mmu_idx);
12850 
12851     if (mmu_idx != s1_mmu_idx) {
12852         /* Call ourselves recursively to do the stage 1 and then stage 2
12853          * translations if mmu_idx is a two-stage regime.
12854          */
12855         if (arm_feature(env, ARM_FEATURE_EL2)) {
12856             hwaddr ipa;
12857             int s2_prot;
12858             int ret;
12859             bool ipa_secure;
12860             ARMCacheAttrs cacheattrs2 = {};
12861             ARMMMUIdx s2_mmu_idx;
12862             bool is_el0;
12863 
12864             ret = get_phys_addr(env, address, access_type, s1_mmu_idx, &ipa,
12865                                 attrs, prot, page_size, fi, cacheattrs);
12866 
12867             /* If S1 fails or S2 is disabled, return early.  */
12868             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12869                 *phys_ptr = ipa;
12870                 return ret;
12871             }
12872 
12873             ipa_secure = attrs->secure;
12874             if (arm_is_secure_below_el3(env)) {
12875                 if (ipa_secure) {
12876                     attrs->secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
12877                 } else {
12878                     attrs->secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
12879                 }
12880             } else {
12881                 assert(!ipa_secure);
12882             }
12883 
12884             s2_mmu_idx = attrs->secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
12885             is_el0 = mmu_idx == ARMMMUIdx_E10_0 || mmu_idx == ARMMMUIdx_SE10_0;
12886 
12887             /* S1 is done. Now do S2 translation.  */
12888             ret = get_phys_addr_lpae(env, ipa, access_type, s2_mmu_idx, is_el0,
12889                                      phys_ptr, attrs, &s2_prot,
12890                                      page_size, fi, &cacheattrs2);
12891             fi->s2addr = ipa;
12892             /* Combine the S1 and S2 perms.  */
12893             *prot &= s2_prot;
12894 
12895             /* If S2 fails, return early.  */
12896             if (ret) {
12897                 return ret;
12898             }
12899 
12900             /* Combine the S1 and S2 cache attributes. */
12901             if (arm_hcr_el2_eff(env) & HCR_DC) {
12902                 /*
12903                  * HCR.DC forces the first stage attributes to
12904                  *  Normal Non-Shareable,
12905                  *  Inner Write-Back Read-Allocate Write-Allocate,
12906                  *  Outer Write-Back Read-Allocate Write-Allocate.
12907                  * Do not overwrite Tagged within attrs.
12908                  */
12909                 if (cacheattrs->attrs != 0xf0) {
12910                     cacheattrs->attrs = 0xff;
12911                 }
12912                 cacheattrs->shareability = 0;
12913             }
12914             *cacheattrs = combine_cacheattrs(env, *cacheattrs, cacheattrs2);
12915 
12916             /* Check if IPA translates to secure or non-secure PA space. */
12917             if (arm_is_secure_below_el3(env)) {
12918                 if (ipa_secure) {
12919                     attrs->secure =
12920                         !(env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW));
12921                 } else {
12922                     attrs->secure =
12923                         !((env->cp15.vtcr_el2.raw_tcr & (VTCR_NSA | VTCR_NSW))
12924                         || (env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW)));
12925                 }
12926             }
12927             return 0;
12928         } else {
12929             /*
12930              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12931              */
12932             mmu_idx = stage_1_mmu_idx(mmu_idx);
12933         }
12934     }
12935 
12936     /* The page table entries may downgrade secure to non-secure, but
12937      * cannot upgrade an non-secure translation regime's attributes
12938      * to secure.
12939      */
12940     attrs->secure = regime_is_secure(env, mmu_idx);
12941     attrs->user = regime_is_user(env, mmu_idx);
12942 
12943     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12944      * In v7 and earlier it affects all stage 1 translations.
12945      */
12946     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12947         && !arm_feature(env, ARM_FEATURE_V8)) {
12948         if (regime_el(env, mmu_idx) == 3) {
12949             address += env->cp15.fcseidr_s;
12950         } else {
12951             address += env->cp15.fcseidr_ns;
12952         }
12953     }
12954 
12955     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12956         bool ret;
12957         *page_size = TARGET_PAGE_SIZE;
12958 
12959         if (arm_feature(env, ARM_FEATURE_V8)) {
12960             /* PMSAv8 */
12961             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12962                                        phys_ptr, attrs, prot, page_size, fi);
12963         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12964             /* PMSAv7 */
12965             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12966                                        phys_ptr, prot, page_size, fi);
12967         } else {
12968             /* Pre-v7 MPU */
12969             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12970                                        phys_ptr, prot, fi);
12971         }
12972         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12973                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12974                       access_type == MMU_DATA_LOAD ? "reading" :
12975                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12976                       (uint32_t)address, mmu_idx,
12977                       ret ? "Miss" : "Hit",
12978                       *prot & PAGE_READ ? 'r' : '-',
12979                       *prot & PAGE_WRITE ? 'w' : '-',
12980                       *prot & PAGE_EXEC ? 'x' : '-');
12981 
12982         return ret;
12983     }
12984 
12985     /* Definitely a real MMU, not an MPU */
12986 
12987     if (regime_translation_disabled(env, mmu_idx)) {
12988         uint64_t hcr;
12989         uint8_t memattr;
12990 
12991         /*
12992          * MMU disabled.  S1 addresses within aa64 translation regimes are
12993          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12994          */
12995         if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
12996             int r_el = regime_el(env, mmu_idx);
12997             if (arm_el_is_aa64(env, r_el)) {
12998                 int pamax = arm_pamax(env_archcpu(env));
12999                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
13000                 int addrtop, tbi;
13001 
13002                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
13003                 if (access_type == MMU_INST_FETCH) {
13004                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
13005                 }
13006                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
13007                 addrtop = (tbi ? 55 : 63);
13008 
13009                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
13010                     fi->type = ARMFault_AddressSize;
13011                     fi->level = 0;
13012                     fi->stage2 = false;
13013                     return 1;
13014                 }
13015 
13016                 /*
13017                  * When TBI is disabled, we've just validated that all of the
13018                  * bits above PAMax are zero, so logically we only need to
13019                  * clear the top byte for TBI.  But it's clearer to follow
13020                  * the pseudocode set of addrdesc.paddress.
13021                  */
13022                 address = extract64(address, 0, 52);
13023             }
13024         }
13025         *phys_ptr = address;
13026         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
13027         *page_size = TARGET_PAGE_SIZE;
13028 
13029         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
13030         hcr = arm_hcr_el2_eff(env);
13031         cacheattrs->shareability = 0;
13032         cacheattrs->is_s2_format = false;
13033         if (hcr & HCR_DC) {
13034             if (hcr & HCR_DCT) {
13035                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
13036             } else {
13037                 memattr = 0xff;  /* Normal, WB, RWA */
13038             }
13039         } else if (access_type == MMU_INST_FETCH) {
13040             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
13041                 memattr = 0xee;  /* Normal, WT, RA, NT */
13042             } else {
13043                 memattr = 0x44;  /* Normal, NC, No */
13044             }
13045             cacheattrs->shareability = 2; /* outer sharable */
13046         } else {
13047             memattr = 0x00;      /* Device, nGnRnE */
13048         }
13049         cacheattrs->attrs = memattr;
13050         return 0;
13051     }
13052 
13053     if (regime_using_lpae_format(env, mmu_idx)) {
13054         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
13055                                   phys_ptr, attrs, prot, page_size,
13056                                   fi, cacheattrs);
13057     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
13058         return get_phys_addr_v6(env, address, access_type, mmu_idx,
13059                                 phys_ptr, attrs, prot, page_size, fi);
13060     } else {
13061         return get_phys_addr_v5(env, address, access_type, mmu_idx,
13062                                     phys_ptr, prot, page_size, fi);
13063     }
13064 }
13065 
13066 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
13067                                          MemTxAttrs *attrs)
13068 {
13069     ARMCPU *cpu = ARM_CPU(cs);
13070     CPUARMState *env = &cpu->env;
13071     hwaddr phys_addr;
13072     target_ulong page_size;
13073     int prot;
13074     bool ret;
13075     ARMMMUFaultInfo fi = {};
13076     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
13077     ARMCacheAttrs cacheattrs = {};
13078 
13079     *attrs = (MemTxAttrs) {};
13080 
13081     ret = get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &phys_addr,
13082                         attrs, &prot, &page_size, &fi, &cacheattrs);
13083 
13084     if (ret) {
13085         return -1;
13086     }
13087     return phys_addr;
13088 }
13089 
13090 #endif
13091 
13092 /* Note that signed overflow is undefined in C.  The following routines are
13093    careful to use unsigned types where modulo arithmetic is required.
13094    Failure to do so _will_ break on newer gcc.  */
13095 
13096 /* Signed saturating arithmetic.  */
13097 
13098 /* Perform 16-bit signed saturating addition.  */
13099 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
13100 {
13101     uint16_t res;
13102 
13103     res = a + b;
13104     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
13105         if (a & 0x8000)
13106             res = 0x8000;
13107         else
13108             res = 0x7fff;
13109     }
13110     return res;
13111 }
13112 
13113 /* Perform 8-bit signed saturating addition.  */
13114 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
13115 {
13116     uint8_t res;
13117 
13118     res = a + b;
13119     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
13120         if (a & 0x80)
13121             res = 0x80;
13122         else
13123             res = 0x7f;
13124     }
13125     return res;
13126 }
13127 
13128 /* Perform 16-bit signed saturating subtraction.  */
13129 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
13130 {
13131     uint16_t res;
13132 
13133     res = a - b;
13134     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
13135         if (a & 0x8000)
13136             res = 0x8000;
13137         else
13138             res = 0x7fff;
13139     }
13140     return res;
13141 }
13142 
13143 /* Perform 8-bit signed saturating subtraction.  */
13144 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
13145 {
13146     uint8_t res;
13147 
13148     res = a - b;
13149     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
13150         if (a & 0x80)
13151             res = 0x80;
13152         else
13153             res = 0x7f;
13154     }
13155     return res;
13156 }
13157 
13158 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
13159 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
13160 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
13161 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
13162 #define PFX q
13163 
13164 #include "op_addsub.h"
13165 
13166 /* Unsigned saturating arithmetic.  */
13167 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
13168 {
13169     uint16_t res;
13170     res = a + b;
13171     if (res < a)
13172         res = 0xffff;
13173     return res;
13174 }
13175 
13176 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
13177 {
13178     if (a > b)
13179         return a - b;
13180     else
13181         return 0;
13182 }
13183 
13184 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
13185 {
13186     uint8_t res;
13187     res = a + b;
13188     if (res < a)
13189         res = 0xff;
13190     return res;
13191 }
13192 
13193 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
13194 {
13195     if (a > b)
13196         return a - b;
13197     else
13198         return 0;
13199 }
13200 
13201 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
13202 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
13203 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
13204 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
13205 #define PFX uq
13206 
13207 #include "op_addsub.h"
13208 
13209 /* Signed modulo arithmetic.  */
13210 #define SARITH16(a, b, n, op) do { \
13211     int32_t sum; \
13212     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
13213     RESULT(sum, n, 16); \
13214     if (sum >= 0) \
13215         ge |= 3 << (n * 2); \
13216     } while(0)
13217 
13218 #define SARITH8(a, b, n, op) do { \
13219     int32_t sum; \
13220     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
13221     RESULT(sum, n, 8); \
13222     if (sum >= 0) \
13223         ge |= 1 << n; \
13224     } while(0)
13225 
13226 
13227 #define ADD16(a, b, n) SARITH16(a, b, n, +)
13228 #define SUB16(a, b, n) SARITH16(a, b, n, -)
13229 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
13230 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
13231 #define PFX s
13232 #define ARITH_GE
13233 
13234 #include "op_addsub.h"
13235 
13236 /* Unsigned modulo arithmetic.  */
13237 #define ADD16(a, b, n) do { \
13238     uint32_t sum; \
13239     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
13240     RESULT(sum, n, 16); \
13241     if ((sum >> 16) == 1) \
13242         ge |= 3 << (n * 2); \
13243     } while(0)
13244 
13245 #define ADD8(a, b, n) do { \
13246     uint32_t sum; \
13247     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
13248     RESULT(sum, n, 8); \
13249     if ((sum >> 8) == 1) \
13250         ge |= 1 << n; \
13251     } while(0)
13252 
13253 #define SUB16(a, b, n) do { \
13254     uint32_t sum; \
13255     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
13256     RESULT(sum, n, 16); \
13257     if ((sum >> 16) == 0) \
13258         ge |= 3 << (n * 2); \
13259     } while(0)
13260 
13261 #define SUB8(a, b, n) do { \
13262     uint32_t sum; \
13263     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
13264     RESULT(sum, n, 8); \
13265     if ((sum >> 8) == 0) \
13266         ge |= 1 << n; \
13267     } while(0)
13268 
13269 #define PFX u
13270 #define ARITH_GE
13271 
13272 #include "op_addsub.h"
13273 
13274 /* Halved signed arithmetic.  */
13275 #define ADD16(a, b, n) \
13276   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
13277 #define SUB16(a, b, n) \
13278   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
13279 #define ADD8(a, b, n) \
13280   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
13281 #define SUB8(a, b, n) \
13282   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
13283 #define PFX sh
13284 
13285 #include "op_addsub.h"
13286 
13287 /* Halved unsigned arithmetic.  */
13288 #define ADD16(a, b, n) \
13289   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13290 #define SUB16(a, b, n) \
13291   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13292 #define ADD8(a, b, n) \
13293   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13294 #define SUB8(a, b, n) \
13295   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13296 #define PFX uh
13297 
13298 #include "op_addsub.h"
13299 
13300 static inline uint8_t do_usad(uint8_t a, uint8_t b)
13301 {
13302     if (a > b)
13303         return a - b;
13304     else
13305         return b - a;
13306 }
13307 
13308 /* Unsigned sum of absolute byte differences.  */
13309 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
13310 {
13311     uint32_t sum;
13312     sum = do_usad(a, b);
13313     sum += do_usad(a >> 8, b >> 8);
13314     sum += do_usad(a >> 16, b >> 16);
13315     sum += do_usad(a >> 24, b >> 24);
13316     return sum;
13317 }
13318 
13319 /* For ARMv6 SEL instruction.  */
13320 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
13321 {
13322     uint32_t mask;
13323 
13324     mask = 0;
13325     if (flags & 1)
13326         mask |= 0xff;
13327     if (flags & 2)
13328         mask |= 0xff00;
13329     if (flags & 4)
13330         mask |= 0xff0000;
13331     if (flags & 8)
13332         mask |= 0xff000000;
13333     return (a & mask) | (b & ~mask);
13334 }
13335 
13336 /* CRC helpers.
13337  * The upper bytes of val (above the number specified by 'bytes') must have
13338  * been zeroed out by the caller.
13339  */
13340 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
13341 {
13342     uint8_t buf[4];
13343 
13344     stl_le_p(buf, val);
13345 
13346     /* zlib crc32 converts the accumulator and output to one's complement.  */
13347     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
13348 }
13349 
13350 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
13351 {
13352     uint8_t buf[4];
13353 
13354     stl_le_p(buf, val);
13355 
13356     /* Linux crc32c converts the output to one's complement.  */
13357     return crc32c(acc, buf, bytes) ^ 0xffffffff;
13358 }
13359 
13360 /* Return the exception level to which FP-disabled exceptions should
13361  * be taken, or 0 if FP is enabled.
13362  */
13363 int fp_exception_el(CPUARMState *env, int cur_el)
13364 {
13365 #ifndef CONFIG_USER_ONLY
13366     uint64_t hcr_el2;
13367 
13368     /* CPACR and the CPTR registers don't exist before v6, so FP is
13369      * always accessible
13370      */
13371     if (!arm_feature(env, ARM_FEATURE_V6)) {
13372         return 0;
13373     }
13374 
13375     if (arm_feature(env, ARM_FEATURE_M)) {
13376         /* CPACR can cause a NOCP UsageFault taken to current security state */
13377         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13378             return 1;
13379         }
13380 
13381         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13382             if (!extract32(env->v7m.nsacr, 10, 1)) {
13383                 /* FP insns cause a NOCP UsageFault taken to Secure */
13384                 return 3;
13385             }
13386         }
13387 
13388         return 0;
13389     }
13390 
13391     hcr_el2 = arm_hcr_el2_eff(env);
13392 
13393     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13394      * 0, 2 : trap EL0 and EL1/PL1 accesses
13395      * 1    : trap only EL0 accesses
13396      * 3    : trap no accesses
13397      * This register is ignored if E2H+TGE are both set.
13398      */
13399     if ((hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13400         int fpen = FIELD_EX64(env->cp15.cpacr_el1, CPACR_EL1, FPEN);
13401 
13402         switch (fpen) {
13403         case 0:
13404         case 2:
13405             if (cur_el == 0 || cur_el == 1) {
13406                 /* Trap to PL1, which might be EL1 or EL3 */
13407                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13408                     return 3;
13409                 }
13410                 return 1;
13411             }
13412             if (cur_el == 3 && !is_a64(env)) {
13413                 /* Secure PL1 running at EL3 */
13414                 return 3;
13415             }
13416             break;
13417         case 1:
13418             if (cur_el == 0) {
13419                 return 1;
13420             }
13421             break;
13422         case 3:
13423             break;
13424         }
13425     }
13426 
13427     /*
13428      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
13429      * to control non-secure access to the FPU. It doesn't have any
13430      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
13431      */
13432     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
13433          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
13434         if (!extract32(env->cp15.nsacr, 10, 1)) {
13435             /* FP insns act as UNDEF */
13436             return cur_el == 2 ? 2 : 1;
13437         }
13438     }
13439 
13440     /*
13441      * CPTR_EL2 is present in v7VE or v8, and changes format
13442      * with HCR_EL2.E2H (regardless of TGE).
13443      */
13444     if (cur_el <= 2) {
13445         if (hcr_el2 & HCR_E2H) {
13446             switch (FIELD_EX64(env->cp15.cptr_el[2], CPTR_EL2, FPEN)) {
13447             case 1:
13448                 if (cur_el != 0 || !(hcr_el2 & HCR_TGE)) {
13449                     break;
13450                 }
13451                 /* fall through */
13452             case 0:
13453             case 2:
13454                 return 2;
13455             }
13456         } else if (arm_is_el2_enabled(env)) {
13457             if (FIELD_EX64(env->cp15.cptr_el[2], CPTR_EL2, TFP)) {
13458                 return 2;
13459             }
13460         }
13461     }
13462 
13463     /* CPTR_EL3 : present in v8 */
13464     if (FIELD_EX64(env->cp15.cptr_el[3], CPTR_EL3, TFP)) {
13465         /* Trap all FP ops to EL3 */
13466         return 3;
13467     }
13468 #endif
13469     return 0;
13470 }
13471 
13472 /* Return the exception level we're running at if this is our mmu_idx */
13473 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
13474 {
13475     if (mmu_idx & ARM_MMU_IDX_M) {
13476         return mmu_idx & ARM_MMU_IDX_M_PRIV;
13477     }
13478 
13479     switch (mmu_idx) {
13480     case ARMMMUIdx_E10_0:
13481     case ARMMMUIdx_E20_0:
13482     case ARMMMUIdx_SE10_0:
13483     case ARMMMUIdx_SE20_0:
13484         return 0;
13485     case ARMMMUIdx_E10_1:
13486     case ARMMMUIdx_E10_1_PAN:
13487     case ARMMMUIdx_SE10_1:
13488     case ARMMMUIdx_SE10_1_PAN:
13489         return 1;
13490     case ARMMMUIdx_E2:
13491     case ARMMMUIdx_E20_2:
13492     case ARMMMUIdx_E20_2_PAN:
13493     case ARMMMUIdx_SE2:
13494     case ARMMMUIdx_SE20_2:
13495     case ARMMMUIdx_SE20_2_PAN:
13496         return 2;
13497     case ARMMMUIdx_SE3:
13498         return 3;
13499     default:
13500         g_assert_not_reached();
13501     }
13502 }
13503 
13504 #ifndef CONFIG_TCG
13505 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13506 {
13507     g_assert_not_reached();
13508 }
13509 #endif
13510 
13511 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
13512 {
13513     ARMMMUIdx idx;
13514     uint64_t hcr;
13515 
13516     if (arm_feature(env, ARM_FEATURE_M)) {
13517         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13518     }
13519 
13520     /* See ARM pseudo-function ELIsInHost.  */
13521     switch (el) {
13522     case 0:
13523         hcr = arm_hcr_el2_eff(env);
13524         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
13525             idx = ARMMMUIdx_E20_0;
13526         } else {
13527             idx = ARMMMUIdx_E10_0;
13528         }
13529         break;
13530     case 1:
13531         if (env->pstate & PSTATE_PAN) {
13532             idx = ARMMMUIdx_E10_1_PAN;
13533         } else {
13534             idx = ARMMMUIdx_E10_1;
13535         }
13536         break;
13537     case 2:
13538         /* Note that TGE does not apply at EL2.  */
13539         if (arm_hcr_el2_eff(env) & HCR_E2H) {
13540             if (env->pstate & PSTATE_PAN) {
13541                 idx = ARMMMUIdx_E20_2_PAN;
13542             } else {
13543                 idx = ARMMMUIdx_E20_2;
13544             }
13545         } else {
13546             idx = ARMMMUIdx_E2;
13547         }
13548         break;
13549     case 3:
13550         return ARMMMUIdx_SE3;
13551     default:
13552         g_assert_not_reached();
13553     }
13554 
13555     if (arm_is_secure_below_el3(env)) {
13556         idx &= ~ARM_MMU_IDX_A_NS;
13557     }
13558 
13559     return idx;
13560 }
13561 
13562 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13563 {
13564     return arm_mmu_idx_el(env, arm_current_el(env));
13565 }
13566 
13567 #ifndef CONFIG_USER_ONLY
13568 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13569 {
13570     return stage_1_mmu_idx(arm_mmu_idx(env));
13571 }
13572 #endif
13573 
13574 static CPUARMTBFlags rebuild_hflags_common(CPUARMState *env, int fp_el,
13575                                            ARMMMUIdx mmu_idx,
13576                                            CPUARMTBFlags flags)
13577 {
13578     DP_TBFLAG_ANY(flags, FPEXC_EL, fp_el);
13579     DP_TBFLAG_ANY(flags, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13580 
13581     if (arm_singlestep_active(env)) {
13582         DP_TBFLAG_ANY(flags, SS_ACTIVE, 1);
13583     }
13584     return flags;
13585 }
13586 
13587 static CPUARMTBFlags rebuild_hflags_common_32(CPUARMState *env, int fp_el,
13588                                               ARMMMUIdx mmu_idx,
13589                                               CPUARMTBFlags flags)
13590 {
13591     bool sctlr_b = arm_sctlr_b(env);
13592 
13593     if (sctlr_b) {
13594         DP_TBFLAG_A32(flags, SCTLR__B, 1);
13595     }
13596     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
13597         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13598     }
13599     DP_TBFLAG_A32(flags, NS, !access_secure_reg(env));
13600 
13601     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13602 }
13603 
13604 static CPUARMTBFlags rebuild_hflags_m32(CPUARMState *env, int fp_el,
13605                                         ARMMMUIdx mmu_idx)
13606 {
13607     CPUARMTBFlags flags = {};
13608     uint32_t ccr = env->v7m.ccr[env->v7m.secure];
13609 
13610     /* Without HaveMainExt, CCR.UNALIGN_TRP is RES1. */
13611     if (ccr & R_V7M_CCR_UNALIGN_TRP_MASK) {
13612         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13613     }
13614 
13615     if (arm_v7m_is_handler_mode(env)) {
13616         DP_TBFLAG_M32(flags, HANDLER, 1);
13617     }
13618 
13619     /*
13620      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
13621      * is suppressing them because the requested execution priority
13622      * is less than 0.
13623      */
13624     if (arm_feature(env, ARM_FEATURE_V8) &&
13625         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
13626           (ccr & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13627         DP_TBFLAG_M32(flags, STACKCHECK, 1);
13628     }
13629 
13630     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13631 }
13632 
13633 static CPUARMTBFlags rebuild_hflags_aprofile(CPUARMState *env)
13634 {
13635     CPUARMTBFlags flags = {};
13636 
13637     DP_TBFLAG_ANY(flags, DEBUG_TARGET_EL, arm_debug_target_el(env));
13638     return flags;
13639 }
13640 
13641 static CPUARMTBFlags rebuild_hflags_a32(CPUARMState *env, int fp_el,
13642                                         ARMMMUIdx mmu_idx)
13643 {
13644     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13645     int el = arm_current_el(env);
13646 
13647     if (arm_sctlr(env, el) & SCTLR_A) {
13648         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13649     }
13650 
13651     if (arm_el_is_aa64(env, 1)) {
13652         DP_TBFLAG_A32(flags, VFPEN, 1);
13653     }
13654 
13655     if (el < 2 && env->cp15.hstr_el2 &&
13656         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13657         DP_TBFLAG_A32(flags, HSTR_ACTIVE, 1);
13658     }
13659 
13660     if (env->uncached_cpsr & CPSR_IL) {
13661         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13662     }
13663 
13664     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13665 }
13666 
13667 static CPUARMTBFlags rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
13668                                         ARMMMUIdx mmu_idx)
13669 {
13670     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13671     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13672     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
13673     uint64_t sctlr;
13674     int tbii, tbid;
13675 
13676     DP_TBFLAG_ANY(flags, AARCH64_STATE, 1);
13677 
13678     /* Get control bits for tagged addresses.  */
13679     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
13680     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
13681 
13682     DP_TBFLAG_A64(flags, TBII, tbii);
13683     DP_TBFLAG_A64(flags, TBID, tbid);
13684 
13685     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
13686         int sve_el = sve_exception_el(env, el);
13687         uint32_t zcr_len;
13688 
13689         /*
13690          * If SVE is disabled, but FP is enabled,
13691          * then the effective len is 0.
13692          */
13693         if (sve_el != 0 && fp_el == 0) {
13694             zcr_len = 0;
13695         } else {
13696             zcr_len = sve_zcr_len_for_el(env, el);
13697         }
13698         DP_TBFLAG_A64(flags, SVEEXC_EL, sve_el);
13699         DP_TBFLAG_A64(flags, ZCR_LEN, zcr_len);
13700     }
13701 
13702     sctlr = regime_sctlr(env, stage1);
13703 
13704     if (sctlr & SCTLR_A) {
13705         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13706     }
13707 
13708     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
13709         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13710     }
13711 
13712     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
13713         /*
13714          * In order to save space in flags, we record only whether
13715          * pauth is "inactive", meaning all insns are implemented as
13716          * a nop, or "active" when some action must be performed.
13717          * The decision of which action to take is left to a helper.
13718          */
13719         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13720             DP_TBFLAG_A64(flags, PAUTH_ACTIVE, 1);
13721         }
13722     }
13723 
13724     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13725         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13726         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13727             DP_TBFLAG_A64(flags, BT, 1);
13728         }
13729     }
13730 
13731     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
13732     if (!(env->pstate & PSTATE_UAO)) {
13733         switch (mmu_idx) {
13734         case ARMMMUIdx_E10_1:
13735         case ARMMMUIdx_E10_1_PAN:
13736         case ARMMMUIdx_SE10_1:
13737         case ARMMMUIdx_SE10_1_PAN:
13738             /* TODO: ARMv8.3-NV */
13739             DP_TBFLAG_A64(flags, UNPRIV, 1);
13740             break;
13741         case ARMMMUIdx_E20_2:
13742         case ARMMMUIdx_E20_2_PAN:
13743         case ARMMMUIdx_SE20_2:
13744         case ARMMMUIdx_SE20_2_PAN:
13745             /*
13746              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
13747              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
13748              */
13749             if (env->cp15.hcr_el2 & HCR_TGE) {
13750                 DP_TBFLAG_A64(flags, UNPRIV, 1);
13751             }
13752             break;
13753         default:
13754             break;
13755         }
13756     }
13757 
13758     if (env->pstate & PSTATE_IL) {
13759         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13760     }
13761 
13762     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
13763         /*
13764          * Set MTE_ACTIVE if any access may be Checked, and leave clear
13765          * if all accesses must be Unchecked:
13766          * 1) If no TBI, then there are no tags in the address to check,
13767          * 2) If Tag Check Override, then all accesses are Unchecked,
13768          * 3) If Tag Check Fail == 0, then Checked access have no effect,
13769          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
13770          */
13771         if (allocation_tag_access_enabled(env, el, sctlr)) {
13772             DP_TBFLAG_A64(flags, ATA, 1);
13773             if (tbid
13774                 && !(env->pstate & PSTATE_TCO)
13775                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
13776                 DP_TBFLAG_A64(flags, MTE_ACTIVE, 1);
13777             }
13778         }
13779         /* And again for unprivileged accesses, if required.  */
13780         if (EX_TBFLAG_A64(flags, UNPRIV)
13781             && tbid
13782             && !(env->pstate & PSTATE_TCO)
13783             && (sctlr & SCTLR_TCF0)
13784             && allocation_tag_access_enabled(env, 0, sctlr)) {
13785             DP_TBFLAG_A64(flags, MTE0_ACTIVE, 1);
13786         }
13787         /* Cache TCMA as well as TBI. */
13788         DP_TBFLAG_A64(flags, TCMA, aa64_va_parameter_tcma(tcr, mmu_idx));
13789     }
13790 
13791     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13792 }
13793 
13794 static CPUARMTBFlags rebuild_hflags_internal(CPUARMState *env)
13795 {
13796     int el = arm_current_el(env);
13797     int fp_el = fp_exception_el(env, el);
13798     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13799 
13800     if (is_a64(env)) {
13801         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13802     } else if (arm_feature(env, ARM_FEATURE_M)) {
13803         return rebuild_hflags_m32(env, fp_el, mmu_idx);
13804     } else {
13805         return rebuild_hflags_a32(env, fp_el, mmu_idx);
13806     }
13807 }
13808 
13809 void arm_rebuild_hflags(CPUARMState *env)
13810 {
13811     env->hflags = rebuild_hflags_internal(env);
13812 }
13813 
13814 /*
13815  * If we have triggered a EL state change we can't rely on the
13816  * translator having passed it to us, we need to recompute.
13817  */
13818 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
13819 {
13820     int el = arm_current_el(env);
13821     int fp_el = fp_exception_el(env, el);
13822     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13823 
13824     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13825 }
13826 
13827 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
13828 {
13829     int fp_el = fp_exception_el(env, el);
13830     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13831 
13832     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13833 }
13834 
13835 /*
13836  * If we have triggered a EL state change we can't rely on the
13837  * translator having passed it to us, we need to recompute.
13838  */
13839 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
13840 {
13841     int el = arm_current_el(env);
13842     int fp_el = fp_exception_el(env, el);
13843     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13844     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13845 }
13846 
13847 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
13848 {
13849     int fp_el = fp_exception_el(env, el);
13850     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13851 
13852     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13853 }
13854 
13855 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
13856 {
13857     int fp_el = fp_exception_el(env, el);
13858     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13859 
13860     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13861 }
13862 
13863 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
13864 {
13865 #ifdef CONFIG_DEBUG_TCG
13866     CPUARMTBFlags c = env->hflags;
13867     CPUARMTBFlags r = rebuild_hflags_internal(env);
13868 
13869     if (unlikely(c.flags != r.flags || c.flags2 != r.flags2)) {
13870         fprintf(stderr, "TCG hflags mismatch "
13871                         "(current:(0x%08x,0x" TARGET_FMT_lx ")"
13872                         " rebuilt:(0x%08x,0x" TARGET_FMT_lx ")\n",
13873                 c.flags, c.flags2, r.flags, r.flags2);
13874         abort();
13875     }
13876 #endif
13877 }
13878 
13879 static bool mve_no_pred(CPUARMState *env)
13880 {
13881     /*
13882      * Return true if there is definitely no predication of MVE
13883      * instructions by VPR or LTPSIZE. (Returning false even if there
13884      * isn't any predication is OK; generated code will just be
13885      * a little worse.)
13886      * If the CPU does not implement MVE then this TB flag is always 0.
13887      *
13888      * NOTE: if you change this logic, the "recalculate s->mve_no_pred"
13889      * logic in gen_update_fp_context() needs to be updated to match.
13890      *
13891      * We do not include the effect of the ECI bits here -- they are
13892      * tracked in other TB flags. This simplifies the logic for
13893      * "when did we emit code that changes the MVE_NO_PRED TB flag
13894      * and thus need to end the TB?".
13895      */
13896     if (cpu_isar_feature(aa32_mve, env_archcpu(env))) {
13897         return false;
13898     }
13899     if (env->v7m.vpr) {
13900         return false;
13901     }
13902     if (env->v7m.ltpsize < 4) {
13903         return false;
13904     }
13905     return true;
13906 }
13907 
13908 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13909                           target_ulong *cs_base, uint32_t *pflags)
13910 {
13911     CPUARMTBFlags flags;
13912 
13913     assert_hflags_rebuild_correctly(env);
13914     flags = env->hflags;
13915 
13916     if (EX_TBFLAG_ANY(flags, AARCH64_STATE)) {
13917         *pc = env->pc;
13918         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13919             DP_TBFLAG_A64(flags, BTYPE, env->btype);
13920         }
13921     } else {
13922         *pc = env->regs[15];
13923 
13924         if (arm_feature(env, ARM_FEATURE_M)) {
13925             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13926                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13927                 != env->v7m.secure) {
13928                 DP_TBFLAG_M32(flags, FPCCR_S_WRONG, 1);
13929             }
13930 
13931             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13932                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13933                  (env->v7m.secure &&
13934                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13935                 /*
13936                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13937                  * active FP context; we must create a new FP context before
13938                  * executing any FP insn.
13939                  */
13940                 DP_TBFLAG_M32(flags, NEW_FP_CTXT_NEEDED, 1);
13941             }
13942 
13943             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13944             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13945                 DP_TBFLAG_M32(flags, LSPACT, 1);
13946             }
13947 
13948             if (mve_no_pred(env)) {
13949                 DP_TBFLAG_M32(flags, MVE_NO_PRED, 1);
13950             }
13951         } else {
13952             /*
13953              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13954              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13955              */
13956             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13957                 DP_TBFLAG_A32(flags, XSCALE_CPAR, env->cp15.c15_cpar);
13958             } else {
13959                 DP_TBFLAG_A32(flags, VECLEN, env->vfp.vec_len);
13960                 DP_TBFLAG_A32(flags, VECSTRIDE, env->vfp.vec_stride);
13961             }
13962             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13963                 DP_TBFLAG_A32(flags, VFPEN, 1);
13964             }
13965         }
13966 
13967         DP_TBFLAG_AM32(flags, THUMB, env->thumb);
13968         DP_TBFLAG_AM32(flags, CONDEXEC, env->condexec_bits);
13969     }
13970 
13971     /*
13972      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13973      * states defined in the ARM ARM for software singlestep:
13974      *  SS_ACTIVE   PSTATE.SS   State
13975      *     0            x       Inactive (the TB flag for SS is always 0)
13976      *     1            0       Active-pending
13977      *     1            1       Active-not-pending
13978      * SS_ACTIVE is set in hflags; PSTATE__SS is computed every TB.
13979      */
13980     if (EX_TBFLAG_ANY(flags, SS_ACTIVE) && (env->pstate & PSTATE_SS)) {
13981         DP_TBFLAG_ANY(flags, PSTATE__SS, 1);
13982     }
13983 
13984     *pflags = flags.flags;
13985     *cs_base = flags.flags2;
13986 }
13987 
13988 #ifdef TARGET_AARCH64
13989 /*
13990  * The manual says that when SVE is enabled and VQ is widened the
13991  * implementation is allowed to zero the previously inaccessible
13992  * portion of the registers.  The corollary to that is that when
13993  * SVE is enabled and VQ is narrowed we are also allowed to zero
13994  * the now inaccessible portion of the registers.
13995  *
13996  * The intent of this is that no predicate bit beyond VQ is ever set.
13997  * Which means that some operations on predicate registers themselves
13998  * may operate on full uint64_t or even unrolled across the maximum
13999  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
14000  * may well be cheaper than conditionals to restrict the operation
14001  * to the relevant portion of a uint16_t[16].
14002  */
14003 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
14004 {
14005     int i, j;
14006     uint64_t pmask;
14007 
14008     assert(vq >= 1 && vq <= ARM_MAX_VQ);
14009     assert(vq <= env_archcpu(env)->sve_max_vq);
14010 
14011     /* Zap the high bits of the zregs.  */
14012     for (i = 0; i < 32; i++) {
14013         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
14014     }
14015 
14016     /* Zap the high bits of the pregs and ffr.  */
14017     pmask = 0;
14018     if (vq & 3) {
14019         pmask = ~(-1ULL << (16 * (vq & 3)));
14020     }
14021     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
14022         for (i = 0; i < 17; ++i) {
14023             env->vfp.pregs[i].p[j] &= pmask;
14024         }
14025         pmask = 0;
14026     }
14027 }
14028 
14029 /*
14030  * Notice a change in SVE vector size when changing EL.
14031  */
14032 void aarch64_sve_change_el(CPUARMState *env, int old_el,
14033                            int new_el, bool el0_a64)
14034 {
14035     ARMCPU *cpu = env_archcpu(env);
14036     int old_len, new_len;
14037     bool old_a64, new_a64;
14038 
14039     /* Nothing to do if no SVE.  */
14040     if (!cpu_isar_feature(aa64_sve, cpu)) {
14041         return;
14042     }
14043 
14044     /* Nothing to do if FP is disabled in either EL.  */
14045     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
14046         return;
14047     }
14048 
14049     /*
14050      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
14051      * at ELx, or not available because the EL is in AArch32 state, then
14052      * for all purposes other than a direct read, the ZCR_ELx.LEN field
14053      * has an effective value of 0".
14054      *
14055      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
14056      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
14057      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
14058      * we already have the correct register contents when encountering the
14059      * vq0->vq0 transition between EL0->EL1.
14060      */
14061     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
14062     old_len = (old_a64 && !sve_exception_el(env, old_el)
14063                ? sve_zcr_len_for_el(env, old_el) : 0);
14064     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
14065     new_len = (new_a64 && !sve_exception_el(env, new_el)
14066                ? sve_zcr_len_for_el(env, new_el) : 0);
14067 
14068     /* When changing vector length, clear inaccessible state.  */
14069     if (new_len < old_len) {
14070         aarch64_sve_narrow_vq(env, new_len + 1);
14071     }
14072 }
14073 #endif
14074