xref: /openbmc/qemu/target/arm/helper.c (revision 033a4f15336646c5dbc07587a7924d71c12a9525)
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 #define PMCR_NUM_COUNTERS 4 /* QEMU IMPDEF choice */
43 
44 #ifndef CONFIG_USER_ONLY
45 
46 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
47                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
48                                bool s1_is_el0,
49                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
50                                target_ulong *page_size_ptr,
51                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
52     __attribute__((nonnull));
53 #endif
54 
55 static void switch_mode(CPUARMState *env, int mode);
56 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx);
57 
58 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
59 {
60     assert(ri->fieldoffset);
61     if (cpreg_field_is_64bit(ri)) {
62         return CPREG_FIELD64(env, ri);
63     } else {
64         return CPREG_FIELD32(env, ri);
65     }
66 }
67 
68 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
69                       uint64_t value)
70 {
71     assert(ri->fieldoffset);
72     if (cpreg_field_is_64bit(ri)) {
73         CPREG_FIELD64(env, ri) = value;
74     } else {
75         CPREG_FIELD32(env, ri) = value;
76     }
77 }
78 
79 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
80 {
81     return (char *)env + ri->fieldoffset;
82 }
83 
84 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
85 {
86     /* Raw read of a coprocessor register (as needed for migration, etc). */
87     if (ri->type & ARM_CP_CONST) {
88         return ri->resetvalue;
89     } else if (ri->raw_readfn) {
90         return ri->raw_readfn(env, ri);
91     } else if (ri->readfn) {
92         return ri->readfn(env, ri);
93     } else {
94         return raw_read(env, ri);
95     }
96 }
97 
98 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
99                              uint64_t v)
100 {
101     /* Raw write of a coprocessor register (as needed for migration, etc).
102      * Note that constant registers are treated as write-ignored; the
103      * caller should check for success by whether a readback gives the
104      * value written.
105      */
106     if (ri->type & ARM_CP_CONST) {
107         return;
108     } else if (ri->raw_writefn) {
109         ri->raw_writefn(env, ri, v);
110     } else if (ri->writefn) {
111         ri->writefn(env, ri, v);
112     } else {
113         raw_write(env, ri, v);
114     }
115 }
116 
117 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
118 {
119    /* Return true if the regdef would cause an assertion if you called
120     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
121     * program bug for it not to have the NO_RAW flag).
122     * NB that returning false here doesn't necessarily mean that calling
123     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
124     * read/write access functions which are safe for raw use" from "has
125     * read/write access functions which have side effects but has forgotten
126     * to provide raw access functions".
127     * The tests here line up with the conditions in read/write_raw_cp_reg()
128     * and assertions in raw_read()/raw_write().
129     */
130     if ((ri->type & ARM_CP_CONST) ||
131         ri->fieldoffset ||
132         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
133         return false;
134     }
135     return true;
136 }
137 
138 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
139 {
140     /* Write the coprocessor state from cpu->env to the (index,value) list. */
141     int i;
142     bool ok = true;
143 
144     for (i = 0; i < cpu->cpreg_array_len; i++) {
145         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
146         const ARMCPRegInfo *ri;
147         uint64_t newval;
148 
149         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
150         if (!ri) {
151             ok = false;
152             continue;
153         }
154         if (ri->type & ARM_CP_NO_RAW) {
155             continue;
156         }
157 
158         newval = read_raw_cp_reg(&cpu->env, ri);
159         if (kvm_sync) {
160             /*
161              * Only sync if the previous list->cpustate sync succeeded.
162              * Rather than tracking the success/failure state for every
163              * item in the list, we just recheck "does the raw write we must
164              * have made in write_list_to_cpustate() read back OK" here.
165              */
166             uint64_t oldval = cpu->cpreg_values[i];
167 
168             if (oldval == newval) {
169                 continue;
170             }
171 
172             write_raw_cp_reg(&cpu->env, ri, oldval);
173             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
174                 continue;
175             }
176 
177             write_raw_cp_reg(&cpu->env, ri, newval);
178         }
179         cpu->cpreg_values[i] = newval;
180     }
181     return ok;
182 }
183 
184 bool write_list_to_cpustate(ARMCPU *cpu)
185 {
186     int i;
187     bool ok = true;
188 
189     for (i = 0; i < cpu->cpreg_array_len; i++) {
190         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
191         uint64_t v = cpu->cpreg_values[i];
192         const ARMCPRegInfo *ri;
193 
194         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
195         if (!ri) {
196             ok = false;
197             continue;
198         }
199         if (ri->type & ARM_CP_NO_RAW) {
200             continue;
201         }
202         /* Write value and confirm it reads back as written
203          * (to catch read-only registers and partially read-only
204          * registers where the incoming migration value doesn't match)
205          */
206         write_raw_cp_reg(&cpu->env, ri, v);
207         if (read_raw_cp_reg(&cpu->env, ri) != v) {
208             ok = false;
209         }
210     }
211     return ok;
212 }
213 
214 static void add_cpreg_to_list(gpointer key, gpointer opaque)
215 {
216     ARMCPU *cpu = opaque;
217     uint32_t regidx = (uintptr_t)key;
218     const ARMCPRegInfo *ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
219 
220     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
221         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
222         /* The value array need not be initialized at this point */
223         cpu->cpreg_array_len++;
224     }
225 }
226 
227 static void count_cpreg(gpointer key, gpointer opaque)
228 {
229     ARMCPU *cpu = opaque;
230     const ARMCPRegInfo *ri;
231 
232     ri = g_hash_table_lookup(cpu->cp_regs, key);
233 
234     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
235         cpu->cpreg_array_len++;
236     }
237 }
238 
239 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
240 {
241     uint64_t aidx = cpreg_to_kvm_id((uintptr_t)a);
242     uint64_t bidx = cpreg_to_kvm_id((uintptr_t)b);
243 
244     if (aidx > bidx) {
245         return 1;
246     }
247     if (aidx < bidx) {
248         return -1;
249     }
250     return 0;
251 }
252 
253 void init_cpreg_list(ARMCPU *cpu)
254 {
255     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
256      * Note that we require cpreg_tuples[] to be sorted by key ID.
257      */
258     GList *keys;
259     int arraylen;
260 
261     keys = g_hash_table_get_keys(cpu->cp_regs);
262     keys = g_list_sort(keys, cpreg_key_compare);
263 
264     cpu->cpreg_array_len = 0;
265 
266     g_list_foreach(keys, count_cpreg, cpu);
267 
268     arraylen = cpu->cpreg_array_len;
269     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
270     cpu->cpreg_values = g_new(uint64_t, arraylen);
271     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
272     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
273     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
274     cpu->cpreg_array_len = 0;
275 
276     g_list_foreach(keys, add_cpreg_to_list, cpu);
277 
278     assert(cpu->cpreg_array_len == arraylen);
279 
280     g_list_free(keys);
281 }
282 
283 /*
284  * Some registers are not accessible from AArch32 EL3 if SCR.NS == 0.
285  */
286 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
287                                         const ARMCPRegInfo *ri,
288                                         bool isread)
289 {
290     if (!is_a64(env) && arm_current_el(env) == 3 &&
291         arm_is_secure_below_el3(env)) {
292         return CP_ACCESS_TRAP_UNCATEGORIZED;
293     }
294     return CP_ACCESS_OK;
295 }
296 
297 /* Some secure-only AArch32 registers trap to EL3 if used from
298  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
299  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
300  * We assume that the .access field is set to PL1_RW.
301  */
302 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
303                                             const ARMCPRegInfo *ri,
304                                             bool isread)
305 {
306     if (arm_current_el(env) == 3) {
307         return CP_ACCESS_OK;
308     }
309     if (arm_is_secure_below_el3(env)) {
310         if (env->cp15.scr_el3 & SCR_EEL2) {
311             return CP_ACCESS_TRAP_EL2;
312         }
313         return CP_ACCESS_TRAP_EL3;
314     }
315     /* This will be EL1 NS and EL2 NS, which just UNDEF */
316     return CP_ACCESS_TRAP_UNCATEGORIZED;
317 }
318 
319 static uint64_t arm_mdcr_el2_eff(CPUARMState *env)
320 {
321     return arm_is_el2_enabled(env) ? env->cp15.mdcr_el2 : 0;
322 }
323 
324 /* Check for traps to "powerdown debug" registers, which are controlled
325  * by MDCR.TDOSA
326  */
327 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
328                                    bool isread)
329 {
330     int el = arm_current_el(env);
331     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
332     bool mdcr_el2_tdosa = (mdcr_el2 & MDCR_TDOSA) || (mdcr_el2 & MDCR_TDE) ||
333         (arm_hcr_el2_eff(env) & HCR_TGE);
334 
335     if (el < 2 && mdcr_el2_tdosa) {
336         return CP_ACCESS_TRAP_EL2;
337     }
338     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
339         return CP_ACCESS_TRAP_EL3;
340     }
341     return CP_ACCESS_OK;
342 }
343 
344 /* Check for traps to "debug ROM" registers, which are controlled
345  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
346  */
347 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
348                                   bool isread)
349 {
350     int el = arm_current_el(env);
351     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
352     bool mdcr_el2_tdra = (mdcr_el2 & MDCR_TDRA) || (mdcr_el2 & MDCR_TDE) ||
353         (arm_hcr_el2_eff(env) & HCR_TGE);
354 
355     if (el < 2 && mdcr_el2_tdra) {
356         return CP_ACCESS_TRAP_EL2;
357     }
358     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
359         return CP_ACCESS_TRAP_EL3;
360     }
361     return CP_ACCESS_OK;
362 }
363 
364 /* Check for traps to general debug registers, which are controlled
365  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
366  */
367 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
368                                   bool isread)
369 {
370     int el = arm_current_el(env);
371     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
372     bool mdcr_el2_tda = (mdcr_el2 & MDCR_TDA) || (mdcr_el2 & MDCR_TDE) ||
373         (arm_hcr_el2_eff(env) & HCR_TGE);
374 
375     if (el < 2 && mdcr_el2_tda) {
376         return CP_ACCESS_TRAP_EL2;
377     }
378     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
379         return CP_ACCESS_TRAP_EL3;
380     }
381     return CP_ACCESS_OK;
382 }
383 
384 /* Check for traps to performance monitor registers, which are controlled
385  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
386  */
387 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
388                                  bool isread)
389 {
390     int el = arm_current_el(env);
391     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
392 
393     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
394         return CP_ACCESS_TRAP_EL2;
395     }
396     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
397         return CP_ACCESS_TRAP_EL3;
398     }
399     return CP_ACCESS_OK;
400 }
401 
402 /* Check for traps from EL1 due to HCR_EL2.TVM and HCR_EL2.TRVM.  */
403 static CPAccessResult access_tvm_trvm(CPUARMState *env, const ARMCPRegInfo *ri,
404                                       bool isread)
405 {
406     if (arm_current_el(env) == 1) {
407         uint64_t trap = isread ? HCR_TRVM : HCR_TVM;
408         if (arm_hcr_el2_eff(env) & trap) {
409             return CP_ACCESS_TRAP_EL2;
410         }
411     }
412     return CP_ACCESS_OK;
413 }
414 
415 /* Check for traps from EL1 due to HCR_EL2.TSW.  */
416 static CPAccessResult access_tsw(CPUARMState *env, const ARMCPRegInfo *ri,
417                                  bool isread)
418 {
419     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TSW)) {
420         return CP_ACCESS_TRAP_EL2;
421     }
422     return CP_ACCESS_OK;
423 }
424 
425 /* Check for traps from EL1 due to HCR_EL2.TACR.  */
426 static CPAccessResult access_tacr(CPUARMState *env, const ARMCPRegInfo *ri,
427                                   bool isread)
428 {
429     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TACR)) {
430         return CP_ACCESS_TRAP_EL2;
431     }
432     return CP_ACCESS_OK;
433 }
434 
435 /* Check for traps from EL1 due to HCR_EL2.TTLB. */
436 static CPAccessResult access_ttlb(CPUARMState *env, const ARMCPRegInfo *ri,
437                                   bool isread)
438 {
439     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TTLB)) {
440         return CP_ACCESS_TRAP_EL2;
441     }
442     return CP_ACCESS_OK;
443 }
444 
445 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
446 {
447     ARMCPU *cpu = env_archcpu(env);
448 
449     raw_write(env, ri, value);
450     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
451 }
452 
453 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
454 {
455     ARMCPU *cpu = env_archcpu(env);
456 
457     if (raw_read(env, ri) != value) {
458         /* Unlike real hardware the qemu TLB uses virtual addresses,
459          * not modified virtual addresses, so this causes a TLB flush.
460          */
461         tlb_flush(CPU(cpu));
462         raw_write(env, ri, value);
463     }
464 }
465 
466 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
467                              uint64_t value)
468 {
469     ARMCPU *cpu = env_archcpu(env);
470 
471     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
472         && !extended_addresses_enabled(env)) {
473         /* For VMSA (when not using the LPAE long descriptor page table
474          * format) this register includes the ASID, so do a TLB flush.
475          * For PMSA it is purely a process ID and no action is needed.
476          */
477         tlb_flush(CPU(cpu));
478     }
479     raw_write(env, ri, value);
480 }
481 
482 /* IS variants of TLB operations must affect all cores */
483 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
484                              uint64_t value)
485 {
486     CPUState *cs = env_cpu(env);
487 
488     tlb_flush_all_cpus_synced(cs);
489 }
490 
491 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
492                              uint64_t value)
493 {
494     CPUState *cs = env_cpu(env);
495 
496     tlb_flush_all_cpus_synced(cs);
497 }
498 
499 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
500                              uint64_t value)
501 {
502     CPUState *cs = env_cpu(env);
503 
504     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
505 }
506 
507 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
508                              uint64_t value)
509 {
510     CPUState *cs = env_cpu(env);
511 
512     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
513 }
514 
515 /*
516  * Non-IS variants of TLB operations are upgraded to
517  * IS versions if we are at EL1 and HCR_EL2.FB is effectively set to
518  * force broadcast of these operations.
519  */
520 static bool tlb_force_broadcast(CPUARMState *env)
521 {
522     return arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_FB);
523 }
524 
525 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
526                           uint64_t value)
527 {
528     /* Invalidate all (TLBIALL) */
529     CPUState *cs = env_cpu(env);
530 
531     if (tlb_force_broadcast(env)) {
532         tlb_flush_all_cpus_synced(cs);
533     } else {
534         tlb_flush(cs);
535     }
536 }
537 
538 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
539                           uint64_t value)
540 {
541     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
542     CPUState *cs = env_cpu(env);
543 
544     value &= TARGET_PAGE_MASK;
545     if (tlb_force_broadcast(env)) {
546         tlb_flush_page_all_cpus_synced(cs, value);
547     } else {
548         tlb_flush_page(cs, value);
549     }
550 }
551 
552 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
553                            uint64_t value)
554 {
555     /* Invalidate by ASID (TLBIASID) */
556     CPUState *cs = env_cpu(env);
557 
558     if (tlb_force_broadcast(env)) {
559         tlb_flush_all_cpus_synced(cs);
560     } else {
561         tlb_flush(cs);
562     }
563 }
564 
565 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
566                            uint64_t value)
567 {
568     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
569     CPUState *cs = env_cpu(env);
570 
571     value &= TARGET_PAGE_MASK;
572     if (tlb_force_broadcast(env)) {
573         tlb_flush_page_all_cpus_synced(cs, value);
574     } else {
575         tlb_flush_page(cs, value);
576     }
577 }
578 
579 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
580                                uint64_t value)
581 {
582     CPUState *cs = env_cpu(env);
583 
584     tlb_flush_by_mmuidx(cs,
585                         ARMMMUIdxBit_E10_1 |
586                         ARMMMUIdxBit_E10_1_PAN |
587                         ARMMMUIdxBit_E10_0);
588 }
589 
590 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
591                                   uint64_t value)
592 {
593     CPUState *cs = env_cpu(env);
594 
595     tlb_flush_by_mmuidx_all_cpus_synced(cs,
596                                         ARMMMUIdxBit_E10_1 |
597                                         ARMMMUIdxBit_E10_1_PAN |
598                                         ARMMMUIdxBit_E10_0);
599 }
600 
601 
602 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
603                               uint64_t value)
604 {
605     CPUState *cs = env_cpu(env);
606 
607     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_E2);
608 }
609 
610 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
611                                  uint64_t value)
612 {
613     CPUState *cs = env_cpu(env);
614 
615     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_E2);
616 }
617 
618 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
619                               uint64_t value)
620 {
621     CPUState *cs = env_cpu(env);
622     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
623 
624     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_E2);
625 }
626 
627 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
628                                  uint64_t value)
629 {
630     CPUState *cs = env_cpu(env);
631     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
632 
633     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
634                                              ARMMMUIdxBit_E2);
635 }
636 
637 static const ARMCPRegInfo cp_reginfo[] = {
638     /* Define the secure and non-secure FCSE identifier CP registers
639      * separately because there is no secure bank in V8 (no _EL3).  This allows
640      * the secure register to be properly reset and migrated. There is also no
641      * v8 EL1 version of the register so the non-secure instance stands alone.
642      */
643     { .name = "FCSEIDR",
644       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
645       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
646       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
647       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
648     { .name = "FCSEIDR_S",
649       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
650       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
651       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
652       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
653     /* Define the secure and non-secure context identifier CP registers
654      * separately because there is no secure bank in V8 (no _EL3).  This allows
655      * the secure register to be properly reset and migrated.  In the
656      * non-secure case, the 32-bit register will have reset and migration
657      * disabled during registration as it is handled by the 64-bit instance.
658      */
659     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
660       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
661       .access = PL1_RW, .accessfn = access_tvm_trvm,
662       .secure = ARM_CP_SECSTATE_NS,
663       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
664       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
665     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
666       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
667       .access = PL1_RW, .accessfn = access_tvm_trvm,
668       .secure = ARM_CP_SECSTATE_S,
669       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
670       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
671 };
672 
673 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
674     /* NB: Some of these registers exist in v8 but with more precise
675      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
676      */
677     /* MMU Domain access control / MPU write buffer control */
678     { .name = "DACR",
679       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
680       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
681       .writefn = dacr_write, .raw_writefn = raw_write,
682       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
683                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
684     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
685      * For v6 and v5, these mappings are overly broad.
686      */
687     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
688       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
689     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
690       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
691     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
692       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
693     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
694       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
695     /* Cache maintenance ops; some of this space may be overridden later. */
696     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
697       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
698       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
699 };
700 
701 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
702     /* Not all pre-v6 cores implemented this WFI, so this is slightly
703      * over-broad.
704      */
705     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
706       .access = PL1_W, .type = ARM_CP_WFI },
707 };
708 
709 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
710     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
711      * is UNPREDICTABLE; we choose to NOP as most implementations do).
712      */
713     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
714       .access = PL1_W, .type = ARM_CP_WFI },
715     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
716      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
717      * OMAPCP will override this space.
718      */
719     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
720       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
721       .resetvalue = 0 },
722     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
723       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
724       .resetvalue = 0 },
725     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
726     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
727       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
728       .resetvalue = 0 },
729     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
730      * implementing it as RAZ means the "debug architecture version" bits
731      * will read as a reserved value, which should cause Linux to not try
732      * to use the debug hardware.
733      */
734     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
735       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
736     /* MMU TLB control. Note that the wildcarding means we cover not just
737      * the unified TLB ops but also the dside/iside/inner-shareable variants.
738      */
739     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
740       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
741       .type = ARM_CP_NO_RAW },
742     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
743       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
744       .type = ARM_CP_NO_RAW },
745     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
746       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
747       .type = ARM_CP_NO_RAW },
748     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
749       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
750       .type = ARM_CP_NO_RAW },
751     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
752       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
753     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
754       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
755 };
756 
757 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
758                         uint64_t value)
759 {
760     uint32_t mask = 0;
761 
762     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
763     if (!arm_feature(env, ARM_FEATURE_V8)) {
764         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
765          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
766          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
767          */
768         if (cpu_isar_feature(aa32_vfp_simd, env_archcpu(env))) {
769             /* VFP coprocessor: cp10 & cp11 [23:20] */
770             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
771 
772             if (!arm_feature(env, ARM_FEATURE_NEON)) {
773                 /* ASEDIS [31] bit is RAO/WI */
774                 value |= (1 << 31);
775             }
776 
777             /* VFPv3 and upwards with NEON implement 32 double precision
778              * registers (D0-D31).
779              */
780             if (!cpu_isar_feature(aa32_simd_r32, env_archcpu(env))) {
781                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
782                 value |= (1 << 30);
783             }
784         }
785         value &= mask;
786     }
787 
788     /*
789      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
790      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
791      */
792     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
793         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
794         value &= ~(0xf << 20);
795         value |= env->cp15.cpacr_el1 & (0xf << 20);
796     }
797 
798     env->cp15.cpacr_el1 = value;
799 }
800 
801 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
802 {
803     /*
804      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
805      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
806      */
807     uint64_t value = env->cp15.cpacr_el1;
808 
809     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
810         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
811         value &= ~(0xf << 20);
812     }
813     return value;
814 }
815 
816 
817 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
818 {
819     /* Call cpacr_write() so that we reset with the correct RAO bits set
820      * for our CPU features.
821      */
822     cpacr_write(env, ri, 0);
823 }
824 
825 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
826                                    bool isread)
827 {
828     if (arm_feature(env, ARM_FEATURE_V8)) {
829         /* Check if CPACR accesses are to be trapped to EL2 */
830         if (arm_current_el(env) == 1 && arm_is_el2_enabled(env) &&
831             (env->cp15.cptr_el[2] & CPTR_TCPAC)) {
832             return CP_ACCESS_TRAP_EL2;
833         /* Check if CPACR accesses are to be trapped to EL3 */
834         } else if (arm_current_el(env) < 3 &&
835                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
836             return CP_ACCESS_TRAP_EL3;
837         }
838     }
839 
840     return CP_ACCESS_OK;
841 }
842 
843 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
844                                   bool isread)
845 {
846     /* Check if CPTR accesses are set to trap to EL3 */
847     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
848         return CP_ACCESS_TRAP_EL3;
849     }
850 
851     return CP_ACCESS_OK;
852 }
853 
854 static const ARMCPRegInfo v6_cp_reginfo[] = {
855     /* prefetch by MVA in v6, NOP in v7 */
856     { .name = "MVA_prefetch",
857       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
858       .access = PL1_W, .type = ARM_CP_NOP },
859     /* We need to break the TB after ISB to execute self-modifying code
860      * correctly and also to take any pending interrupts immediately.
861      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
862      */
863     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
864       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
865     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
866       .access = PL0_W, .type = ARM_CP_NOP },
867     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
868       .access = PL0_W, .type = ARM_CP_NOP },
869     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
870       .access = PL1_RW, .accessfn = access_tvm_trvm,
871       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
872                              offsetof(CPUARMState, cp15.ifar_ns) },
873       .resetvalue = 0, },
874     /* Watchpoint Fault Address Register : should actually only be present
875      * for 1136, 1176, 11MPCore.
876      */
877     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
878       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
879     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
880       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
881       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
882       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
883 };
884 
885 typedef struct pm_event {
886     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
887     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
888     bool (*supported)(CPUARMState *);
889     /*
890      * Retrieve the current count of the underlying event. The programmed
891      * counters hold a difference from the return value from this function
892      */
893     uint64_t (*get_count)(CPUARMState *);
894     /*
895      * Return how many nanoseconds it will take (at a minimum) for count events
896      * to occur. A negative value indicates the counter will never overflow, or
897      * that the counter has otherwise arranged for the overflow bit to be set
898      * and the PMU interrupt to be raised on overflow.
899      */
900     int64_t (*ns_per_count)(uint64_t);
901 } pm_event;
902 
903 static bool event_always_supported(CPUARMState *env)
904 {
905     return true;
906 }
907 
908 static uint64_t swinc_get_count(CPUARMState *env)
909 {
910     /*
911      * SW_INCR events are written directly to the pmevcntr's by writes to
912      * PMSWINC, so there is no underlying count maintained by the PMU itself
913      */
914     return 0;
915 }
916 
917 static int64_t swinc_ns_per(uint64_t ignored)
918 {
919     return -1;
920 }
921 
922 /*
923  * Return the underlying cycle count for the PMU cycle counters. If we're in
924  * usermode, simply return 0.
925  */
926 static uint64_t cycles_get_count(CPUARMState *env)
927 {
928 #ifndef CONFIG_USER_ONLY
929     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
930                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
931 #else
932     return cpu_get_host_ticks();
933 #endif
934 }
935 
936 #ifndef CONFIG_USER_ONLY
937 static int64_t cycles_ns_per(uint64_t cycles)
938 {
939     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
940 }
941 
942 static bool instructions_supported(CPUARMState *env)
943 {
944     return icount_enabled() == 1; /* Precise instruction counting */
945 }
946 
947 static uint64_t instructions_get_count(CPUARMState *env)
948 {
949     return (uint64_t)icount_get_raw();
950 }
951 
952 static int64_t instructions_ns_per(uint64_t icount)
953 {
954     return icount_to_ns((int64_t)icount);
955 }
956 #endif
957 
958 static bool pmu_8_1_events_supported(CPUARMState *env)
959 {
960     /* For events which are supported in any v8.1 PMU */
961     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
962 }
963 
964 static bool pmu_8_4_events_supported(CPUARMState *env)
965 {
966     /* For events which are supported in any v8.1 PMU */
967     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
968 }
969 
970 static uint64_t zero_event_get_count(CPUARMState *env)
971 {
972     /* For events which on QEMU never fire, so their count is always zero */
973     return 0;
974 }
975 
976 static int64_t zero_event_ns_per(uint64_t cycles)
977 {
978     /* An event which never fires can never overflow */
979     return -1;
980 }
981 
982 static const pm_event pm_events[] = {
983     { .number = 0x000, /* SW_INCR */
984       .supported = event_always_supported,
985       .get_count = swinc_get_count,
986       .ns_per_count = swinc_ns_per,
987     },
988 #ifndef CONFIG_USER_ONLY
989     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
990       .supported = instructions_supported,
991       .get_count = instructions_get_count,
992       .ns_per_count = instructions_ns_per,
993     },
994     { .number = 0x011, /* CPU_CYCLES, Cycle */
995       .supported = event_always_supported,
996       .get_count = cycles_get_count,
997       .ns_per_count = cycles_ns_per,
998     },
999 #endif
1000     { .number = 0x023, /* STALL_FRONTEND */
1001       .supported = pmu_8_1_events_supported,
1002       .get_count = zero_event_get_count,
1003       .ns_per_count = zero_event_ns_per,
1004     },
1005     { .number = 0x024, /* STALL_BACKEND */
1006       .supported = pmu_8_1_events_supported,
1007       .get_count = zero_event_get_count,
1008       .ns_per_count = zero_event_ns_per,
1009     },
1010     { .number = 0x03c, /* STALL */
1011       .supported = pmu_8_4_events_supported,
1012       .get_count = zero_event_get_count,
1013       .ns_per_count = zero_event_ns_per,
1014     },
1015 };
1016 
1017 /*
1018  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1019  * events (i.e. the statistical profiling extension), this implementation
1020  * should first be updated to something sparse instead of the current
1021  * supported_event_map[] array.
1022  */
1023 #define MAX_EVENT_ID 0x3c
1024 #define UNSUPPORTED_EVENT UINT16_MAX
1025 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1026 
1027 /*
1028  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1029  * of ARM event numbers to indices in our pm_events array.
1030  *
1031  * Note: Events in the 0x40XX range are not currently supported.
1032  */
1033 void pmu_init(ARMCPU *cpu)
1034 {
1035     unsigned int i;
1036 
1037     /*
1038      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1039      * events to them
1040      */
1041     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1042         supported_event_map[i] = UNSUPPORTED_EVENT;
1043     }
1044     cpu->pmceid0 = 0;
1045     cpu->pmceid1 = 0;
1046 
1047     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1048         const pm_event *cnt = &pm_events[i];
1049         assert(cnt->number <= MAX_EVENT_ID);
1050         /* We do not currently support events in the 0x40xx range */
1051         assert(cnt->number <= 0x3f);
1052 
1053         if (cnt->supported(&cpu->env)) {
1054             supported_event_map[cnt->number] = i;
1055             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1056             if (cnt->number & 0x20) {
1057                 cpu->pmceid1 |= event_mask;
1058             } else {
1059                 cpu->pmceid0 |= event_mask;
1060             }
1061         }
1062     }
1063 }
1064 
1065 /*
1066  * Check at runtime whether a PMU event is supported for the current machine
1067  */
1068 static bool event_supported(uint16_t number)
1069 {
1070     if (number > MAX_EVENT_ID) {
1071         return false;
1072     }
1073     return supported_event_map[number] != UNSUPPORTED_EVENT;
1074 }
1075 
1076 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1077                                    bool isread)
1078 {
1079     /* Performance monitor registers user accessibility is controlled
1080      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1081      * trapping to EL2 or EL3 for other accesses.
1082      */
1083     int el = arm_current_el(env);
1084     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1085 
1086     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1087         return CP_ACCESS_TRAP;
1088     }
1089     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
1090         return CP_ACCESS_TRAP_EL2;
1091     }
1092     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1093         return CP_ACCESS_TRAP_EL3;
1094     }
1095 
1096     return CP_ACCESS_OK;
1097 }
1098 
1099 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1100                                            const ARMCPRegInfo *ri,
1101                                            bool isread)
1102 {
1103     /* ER: event counter read trap control */
1104     if (arm_feature(env, ARM_FEATURE_V8)
1105         && arm_current_el(env) == 0
1106         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1107         && isread) {
1108         return CP_ACCESS_OK;
1109     }
1110 
1111     return pmreg_access(env, ri, isread);
1112 }
1113 
1114 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1115                                          const ARMCPRegInfo *ri,
1116                                          bool isread)
1117 {
1118     /* SW: software increment write trap control */
1119     if (arm_feature(env, ARM_FEATURE_V8)
1120         && arm_current_el(env) == 0
1121         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1122         && !isread) {
1123         return CP_ACCESS_OK;
1124     }
1125 
1126     return pmreg_access(env, ri, isread);
1127 }
1128 
1129 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1130                                         const ARMCPRegInfo *ri,
1131                                         bool isread)
1132 {
1133     /* ER: event counter read trap control */
1134     if (arm_feature(env, ARM_FEATURE_V8)
1135         && arm_current_el(env) == 0
1136         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1137         return CP_ACCESS_OK;
1138     }
1139 
1140     return pmreg_access(env, ri, isread);
1141 }
1142 
1143 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1144                                          const ARMCPRegInfo *ri,
1145                                          bool isread)
1146 {
1147     /* CR: cycle counter read trap control */
1148     if (arm_feature(env, ARM_FEATURE_V8)
1149         && arm_current_el(env) == 0
1150         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1151         && isread) {
1152         return CP_ACCESS_OK;
1153     }
1154 
1155     return pmreg_access(env, ri, isread);
1156 }
1157 
1158 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1159  * the current EL, security state, and register configuration.
1160  */
1161 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1162 {
1163     uint64_t filter;
1164     bool e, p, u, nsk, nsu, nsh, m;
1165     bool enabled, prohibited, filtered;
1166     bool secure = arm_is_secure(env);
1167     int el = arm_current_el(env);
1168     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1169     uint8_t hpmn = mdcr_el2 & MDCR_HPMN;
1170 
1171     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1172         return false;
1173     }
1174 
1175     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1176             (counter < hpmn || counter == 31)) {
1177         e = env->cp15.c9_pmcr & PMCRE;
1178     } else {
1179         e = mdcr_el2 & MDCR_HPME;
1180     }
1181     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1182 
1183     if (!secure) {
1184         if (el == 2 && (counter < hpmn || counter == 31)) {
1185             prohibited = mdcr_el2 & MDCR_HPMD;
1186         } else {
1187             prohibited = false;
1188         }
1189     } else {
1190         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1191            !(env->cp15.mdcr_el3 & MDCR_SPME);
1192     }
1193 
1194     if (prohibited && counter == 31) {
1195         prohibited = env->cp15.c9_pmcr & PMCRDP;
1196     }
1197 
1198     if (counter == 31) {
1199         filter = env->cp15.pmccfiltr_el0;
1200     } else {
1201         filter = env->cp15.c14_pmevtyper[counter];
1202     }
1203 
1204     p   = filter & PMXEVTYPER_P;
1205     u   = filter & PMXEVTYPER_U;
1206     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1207     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1208     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1209     m   = arm_el_is_aa64(env, 1) &&
1210               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1211 
1212     if (el == 0) {
1213         filtered = secure ? u : u != nsu;
1214     } else if (el == 1) {
1215         filtered = secure ? p : p != nsk;
1216     } else if (el == 2) {
1217         filtered = !nsh;
1218     } else { /* EL3 */
1219         filtered = m != p;
1220     }
1221 
1222     if (counter != 31) {
1223         /*
1224          * If not checking PMCCNTR, ensure the counter is setup to an event we
1225          * support
1226          */
1227         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1228         if (!event_supported(event)) {
1229             return false;
1230         }
1231     }
1232 
1233     return enabled && !prohibited && !filtered;
1234 }
1235 
1236 static void pmu_update_irq(CPUARMState *env)
1237 {
1238     ARMCPU *cpu = env_archcpu(env);
1239     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1240             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1241 }
1242 
1243 /*
1244  * Ensure c15_ccnt is the guest-visible count so that operations such as
1245  * enabling/disabling the counter or filtering, modifying the count itself,
1246  * etc. can be done logically. This is essentially a no-op if the counter is
1247  * not enabled at the time of the call.
1248  */
1249 static void pmccntr_op_start(CPUARMState *env)
1250 {
1251     uint64_t cycles = cycles_get_count(env);
1252 
1253     if (pmu_counter_enabled(env, 31)) {
1254         uint64_t eff_cycles = cycles;
1255         if (env->cp15.c9_pmcr & PMCRD) {
1256             /* Increment once every 64 processor clock cycles */
1257             eff_cycles /= 64;
1258         }
1259 
1260         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1261 
1262         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1263                                  1ull << 63 : 1ull << 31;
1264         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1265             env->cp15.c9_pmovsr |= (1 << 31);
1266             pmu_update_irq(env);
1267         }
1268 
1269         env->cp15.c15_ccnt = new_pmccntr;
1270     }
1271     env->cp15.c15_ccnt_delta = cycles;
1272 }
1273 
1274 /*
1275  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1276  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1277  * pmccntr_op_start.
1278  */
1279 static void pmccntr_op_finish(CPUARMState *env)
1280 {
1281     if (pmu_counter_enabled(env, 31)) {
1282 #ifndef CONFIG_USER_ONLY
1283         /* Calculate when the counter will next overflow */
1284         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1285         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1286             remaining_cycles = (uint32_t)remaining_cycles;
1287         }
1288         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1289 
1290         if (overflow_in > 0) {
1291             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1292                 overflow_in;
1293             ARMCPU *cpu = env_archcpu(env);
1294             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1295         }
1296 #endif
1297 
1298         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1299         if (env->cp15.c9_pmcr & PMCRD) {
1300             /* Increment once every 64 processor clock cycles */
1301             prev_cycles /= 64;
1302         }
1303         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1304     }
1305 }
1306 
1307 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1308 {
1309 
1310     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1311     uint64_t count = 0;
1312     if (event_supported(event)) {
1313         uint16_t event_idx = supported_event_map[event];
1314         count = pm_events[event_idx].get_count(env);
1315     }
1316 
1317     if (pmu_counter_enabled(env, counter)) {
1318         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1319 
1320         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1321             env->cp15.c9_pmovsr |= (1 << counter);
1322             pmu_update_irq(env);
1323         }
1324         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1325     }
1326     env->cp15.c14_pmevcntr_delta[counter] = count;
1327 }
1328 
1329 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1330 {
1331     if (pmu_counter_enabled(env, counter)) {
1332 #ifndef CONFIG_USER_ONLY
1333         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1334         uint16_t event_idx = supported_event_map[event];
1335         uint64_t delta = UINT32_MAX -
1336             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1337         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1338 
1339         if (overflow_in > 0) {
1340             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1341                 overflow_in;
1342             ARMCPU *cpu = env_archcpu(env);
1343             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1344         }
1345 #endif
1346 
1347         env->cp15.c14_pmevcntr_delta[counter] -=
1348             env->cp15.c14_pmevcntr[counter];
1349     }
1350 }
1351 
1352 void pmu_op_start(CPUARMState *env)
1353 {
1354     unsigned int i;
1355     pmccntr_op_start(env);
1356     for (i = 0; i < pmu_num_counters(env); i++) {
1357         pmevcntr_op_start(env, i);
1358     }
1359 }
1360 
1361 void pmu_op_finish(CPUARMState *env)
1362 {
1363     unsigned int i;
1364     pmccntr_op_finish(env);
1365     for (i = 0; i < pmu_num_counters(env); i++) {
1366         pmevcntr_op_finish(env, i);
1367     }
1368 }
1369 
1370 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1371 {
1372     pmu_op_start(&cpu->env);
1373 }
1374 
1375 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1376 {
1377     pmu_op_finish(&cpu->env);
1378 }
1379 
1380 void arm_pmu_timer_cb(void *opaque)
1381 {
1382     ARMCPU *cpu = opaque;
1383 
1384     /*
1385      * Update all the counter values based on the current underlying counts,
1386      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1387      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1388      * counter may expire.
1389      */
1390     pmu_op_start(&cpu->env);
1391     pmu_op_finish(&cpu->env);
1392 }
1393 
1394 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1395                        uint64_t value)
1396 {
1397     pmu_op_start(env);
1398 
1399     if (value & PMCRC) {
1400         /* The counter has been reset */
1401         env->cp15.c15_ccnt = 0;
1402     }
1403 
1404     if (value & PMCRP) {
1405         unsigned int i;
1406         for (i = 0; i < pmu_num_counters(env); i++) {
1407             env->cp15.c14_pmevcntr[i] = 0;
1408         }
1409     }
1410 
1411     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1412     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1413 
1414     pmu_op_finish(env);
1415 }
1416 
1417 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1418                           uint64_t value)
1419 {
1420     unsigned int i;
1421     for (i = 0; i < pmu_num_counters(env); i++) {
1422         /* Increment a counter's count iff: */
1423         if ((value & (1 << i)) && /* counter's bit is set */
1424                 /* counter is enabled and not filtered */
1425                 pmu_counter_enabled(env, i) &&
1426                 /* counter is SW_INCR */
1427                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1428             pmevcntr_op_start(env, i);
1429 
1430             /*
1431              * Detect if this write causes an overflow since we can't predict
1432              * PMSWINC overflows like we can for other events
1433              */
1434             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1435 
1436             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1437                 env->cp15.c9_pmovsr |= (1 << i);
1438                 pmu_update_irq(env);
1439             }
1440 
1441             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1442 
1443             pmevcntr_op_finish(env, i);
1444         }
1445     }
1446 }
1447 
1448 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1449 {
1450     uint64_t ret;
1451     pmccntr_op_start(env);
1452     ret = env->cp15.c15_ccnt;
1453     pmccntr_op_finish(env);
1454     return ret;
1455 }
1456 
1457 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1458                          uint64_t value)
1459 {
1460     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1461      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1462      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1463      * accessed.
1464      */
1465     env->cp15.c9_pmselr = value & 0x1f;
1466 }
1467 
1468 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1469                         uint64_t value)
1470 {
1471     pmccntr_op_start(env);
1472     env->cp15.c15_ccnt = value;
1473     pmccntr_op_finish(env);
1474 }
1475 
1476 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1477                             uint64_t value)
1478 {
1479     uint64_t cur_val = pmccntr_read(env, NULL);
1480 
1481     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1482 }
1483 
1484 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1485                             uint64_t value)
1486 {
1487     pmccntr_op_start(env);
1488     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1489     pmccntr_op_finish(env);
1490 }
1491 
1492 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1493                             uint64_t value)
1494 {
1495     pmccntr_op_start(env);
1496     /* M is not accessible from AArch32 */
1497     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1498         (value & PMCCFILTR);
1499     pmccntr_op_finish(env);
1500 }
1501 
1502 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1503 {
1504     /* M is not visible in AArch32 */
1505     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1506 }
1507 
1508 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1509                             uint64_t value)
1510 {
1511     value &= pmu_counter_mask(env);
1512     env->cp15.c9_pmcnten |= value;
1513 }
1514 
1515 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1516                              uint64_t value)
1517 {
1518     value &= pmu_counter_mask(env);
1519     env->cp15.c9_pmcnten &= ~value;
1520 }
1521 
1522 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1523                          uint64_t value)
1524 {
1525     value &= pmu_counter_mask(env);
1526     env->cp15.c9_pmovsr &= ~value;
1527     pmu_update_irq(env);
1528 }
1529 
1530 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1531                          uint64_t value)
1532 {
1533     value &= pmu_counter_mask(env);
1534     env->cp15.c9_pmovsr |= value;
1535     pmu_update_irq(env);
1536 }
1537 
1538 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1539                              uint64_t value, const uint8_t counter)
1540 {
1541     if (counter == 31) {
1542         pmccfiltr_write(env, ri, value);
1543     } else if (counter < pmu_num_counters(env)) {
1544         pmevcntr_op_start(env, counter);
1545 
1546         /*
1547          * If this counter's event type is changing, store the current
1548          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1549          * pmevcntr_op_finish has the correct baseline when it converts back to
1550          * a delta.
1551          */
1552         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1553             PMXEVTYPER_EVTCOUNT;
1554         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1555         if (old_event != new_event) {
1556             uint64_t count = 0;
1557             if (event_supported(new_event)) {
1558                 uint16_t event_idx = supported_event_map[new_event];
1559                 count = pm_events[event_idx].get_count(env);
1560             }
1561             env->cp15.c14_pmevcntr_delta[counter] = count;
1562         }
1563 
1564         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1565         pmevcntr_op_finish(env, counter);
1566     }
1567     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1568      * PMSELR value is equal to or greater than the number of implemented
1569      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1570      */
1571 }
1572 
1573 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1574                                const uint8_t counter)
1575 {
1576     if (counter == 31) {
1577         return env->cp15.pmccfiltr_el0;
1578     } else if (counter < pmu_num_counters(env)) {
1579         return env->cp15.c14_pmevtyper[counter];
1580     } else {
1581       /*
1582        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1583        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1584        */
1585         return 0;
1586     }
1587 }
1588 
1589 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1590                               uint64_t value)
1591 {
1592     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1593     pmevtyper_write(env, ri, value, counter);
1594 }
1595 
1596 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1597                                uint64_t value)
1598 {
1599     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1600     env->cp15.c14_pmevtyper[counter] = value;
1601 
1602     /*
1603      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1604      * pmu_op_finish calls when loading saved state for a migration. Because
1605      * we're potentially updating the type of event here, the value written to
1606      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1607      * different counter type. Therefore, we need to set this value to the
1608      * current count for the counter type we're writing so that pmu_op_finish
1609      * has the correct count for its calculation.
1610      */
1611     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1612     if (event_supported(event)) {
1613         uint16_t event_idx = supported_event_map[event];
1614         env->cp15.c14_pmevcntr_delta[counter] =
1615             pm_events[event_idx].get_count(env);
1616     }
1617 }
1618 
1619 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1620 {
1621     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1622     return pmevtyper_read(env, ri, counter);
1623 }
1624 
1625 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1626                              uint64_t value)
1627 {
1628     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1629 }
1630 
1631 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1632 {
1633     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1634 }
1635 
1636 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1637                              uint64_t value, uint8_t counter)
1638 {
1639     if (counter < pmu_num_counters(env)) {
1640         pmevcntr_op_start(env, counter);
1641         env->cp15.c14_pmevcntr[counter] = value;
1642         pmevcntr_op_finish(env, counter);
1643     }
1644     /*
1645      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1646      * are CONSTRAINED UNPREDICTABLE.
1647      */
1648 }
1649 
1650 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1651                               uint8_t counter)
1652 {
1653     if (counter < pmu_num_counters(env)) {
1654         uint64_t ret;
1655         pmevcntr_op_start(env, counter);
1656         ret = env->cp15.c14_pmevcntr[counter];
1657         pmevcntr_op_finish(env, counter);
1658         return ret;
1659     } else {
1660       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1661        * are CONSTRAINED UNPREDICTABLE. */
1662         return 0;
1663     }
1664 }
1665 
1666 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1667                              uint64_t value)
1668 {
1669     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1670     pmevcntr_write(env, ri, value, counter);
1671 }
1672 
1673 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1674 {
1675     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1676     return pmevcntr_read(env, ri, counter);
1677 }
1678 
1679 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1680                              uint64_t value)
1681 {
1682     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1683     assert(counter < pmu_num_counters(env));
1684     env->cp15.c14_pmevcntr[counter] = value;
1685     pmevcntr_write(env, ri, value, counter);
1686 }
1687 
1688 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1689 {
1690     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1691     assert(counter < pmu_num_counters(env));
1692     return env->cp15.c14_pmevcntr[counter];
1693 }
1694 
1695 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1696                              uint64_t value)
1697 {
1698     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1699 }
1700 
1701 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1702 {
1703     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1704 }
1705 
1706 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1707                             uint64_t value)
1708 {
1709     if (arm_feature(env, ARM_FEATURE_V8)) {
1710         env->cp15.c9_pmuserenr = value & 0xf;
1711     } else {
1712         env->cp15.c9_pmuserenr = value & 1;
1713     }
1714 }
1715 
1716 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1717                              uint64_t value)
1718 {
1719     /* We have no event counters so only the C bit can be changed */
1720     value &= pmu_counter_mask(env);
1721     env->cp15.c9_pminten |= value;
1722     pmu_update_irq(env);
1723 }
1724 
1725 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1726                              uint64_t value)
1727 {
1728     value &= pmu_counter_mask(env);
1729     env->cp15.c9_pminten &= ~value;
1730     pmu_update_irq(env);
1731 }
1732 
1733 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1734                        uint64_t value)
1735 {
1736     /* Note that even though the AArch64 view of this register has bits
1737      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1738      * architectural requirements for bits which are RES0 only in some
1739      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1740      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1741      */
1742     raw_write(env, ri, value & ~0x1FULL);
1743 }
1744 
1745 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1746 {
1747     /* Begin with base v8.0 state.  */
1748     uint32_t valid_mask = 0x3fff;
1749     ARMCPU *cpu = env_archcpu(env);
1750 
1751     if (ri->state == ARM_CP_STATE_AA64) {
1752         if (arm_feature(env, ARM_FEATURE_AARCH64) &&
1753             !cpu_isar_feature(aa64_aa32_el1, cpu)) {
1754                 value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1755         }
1756         valid_mask &= ~SCR_NET;
1757 
1758         if (cpu_isar_feature(aa64_lor, cpu)) {
1759             valid_mask |= SCR_TLOR;
1760         }
1761         if (cpu_isar_feature(aa64_pauth, cpu)) {
1762             valid_mask |= SCR_API | SCR_APK;
1763         }
1764         if (cpu_isar_feature(aa64_sel2, cpu)) {
1765             valid_mask |= SCR_EEL2;
1766         }
1767         if (cpu_isar_feature(aa64_mte, cpu)) {
1768             valid_mask |= SCR_ATA;
1769         }
1770     } else {
1771         valid_mask &= ~(SCR_RW | SCR_ST);
1772     }
1773 
1774     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1775         valid_mask &= ~SCR_HCE;
1776 
1777         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1778          * supported if EL2 exists. The bit is UNK/SBZP when
1779          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1780          * when EL2 is unavailable.
1781          * On ARMv8, this bit is always available.
1782          */
1783         if (arm_feature(env, ARM_FEATURE_V7) &&
1784             !arm_feature(env, ARM_FEATURE_V8)) {
1785             valid_mask &= ~SCR_SMD;
1786         }
1787     }
1788 
1789     /* Clear all-context RES0 bits.  */
1790     value &= valid_mask;
1791     raw_write(env, ri, value);
1792 }
1793 
1794 static void scr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1795 {
1796     /*
1797      * scr_write will set the RES1 bits on an AArch64-only CPU.
1798      * The reset value will be 0x30 on an AArch64-only CPU and 0 otherwise.
1799      */
1800     scr_write(env, ri, 0);
1801 }
1802 
1803 static CPAccessResult access_aa64_tid2(CPUARMState *env,
1804                                        const ARMCPRegInfo *ri,
1805                                        bool isread)
1806 {
1807     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
1808         return CP_ACCESS_TRAP_EL2;
1809     }
1810 
1811     return CP_ACCESS_OK;
1812 }
1813 
1814 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1815 {
1816     ARMCPU *cpu = env_archcpu(env);
1817 
1818     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1819      * bank
1820      */
1821     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1822                                         ri->secure & ARM_CP_SECSTATE_S);
1823 
1824     return cpu->ccsidr[index];
1825 }
1826 
1827 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1828                          uint64_t value)
1829 {
1830     raw_write(env, ri, value & 0xf);
1831 }
1832 
1833 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1834 {
1835     CPUState *cs = env_cpu(env);
1836     bool el1 = arm_current_el(env) == 1;
1837     uint64_t hcr_el2 = el1 ? arm_hcr_el2_eff(env) : 0;
1838     uint64_t ret = 0;
1839 
1840     if (hcr_el2 & HCR_IMO) {
1841         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1842             ret |= CPSR_I;
1843         }
1844     } else {
1845         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1846             ret |= CPSR_I;
1847         }
1848     }
1849 
1850     if (hcr_el2 & HCR_FMO) {
1851         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1852             ret |= CPSR_F;
1853         }
1854     } else {
1855         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1856             ret |= CPSR_F;
1857         }
1858     }
1859 
1860     /* External aborts are not possible in QEMU so A bit is always clear */
1861     return ret;
1862 }
1863 
1864 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1865                                        bool isread)
1866 {
1867     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
1868         return CP_ACCESS_TRAP_EL2;
1869     }
1870 
1871     return CP_ACCESS_OK;
1872 }
1873 
1874 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1875                                        bool isread)
1876 {
1877     if (arm_feature(env, ARM_FEATURE_V8)) {
1878         return access_aa64_tid1(env, ri, isread);
1879     }
1880 
1881     return CP_ACCESS_OK;
1882 }
1883 
1884 static const ARMCPRegInfo v7_cp_reginfo[] = {
1885     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1886     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1887       .access = PL1_W, .type = ARM_CP_NOP },
1888     /* Performance monitors are implementation defined in v7,
1889      * but with an ARM recommended set of registers, which we
1890      * follow.
1891      *
1892      * Performance registers fall into three categories:
1893      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1894      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1895      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1896      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1897      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1898      */
1899     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1900       .access = PL0_RW, .type = ARM_CP_ALIAS,
1901       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1902       .writefn = pmcntenset_write,
1903       .accessfn = pmreg_access,
1904       .raw_writefn = raw_write },
1905     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1906       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1907       .access = PL0_RW, .accessfn = pmreg_access,
1908       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1909       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1910     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1911       .access = PL0_RW,
1912       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1913       .accessfn = pmreg_access,
1914       .writefn = pmcntenclr_write,
1915       .type = ARM_CP_ALIAS },
1916     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1917       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1918       .access = PL0_RW, .accessfn = pmreg_access,
1919       .type = ARM_CP_ALIAS,
1920       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1921       .writefn = pmcntenclr_write },
1922     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1923       .access = PL0_RW, .type = ARM_CP_IO,
1924       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1925       .accessfn = pmreg_access,
1926       .writefn = pmovsr_write,
1927       .raw_writefn = raw_write },
1928     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1929       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1930       .access = PL0_RW, .accessfn = pmreg_access,
1931       .type = ARM_CP_ALIAS | ARM_CP_IO,
1932       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1933       .writefn = pmovsr_write,
1934       .raw_writefn = raw_write },
1935     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1936       .access = PL0_W, .accessfn = pmreg_access_swinc,
1937       .type = ARM_CP_NO_RAW | ARM_CP_IO,
1938       .writefn = pmswinc_write },
1939     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
1940       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
1941       .access = PL0_W, .accessfn = pmreg_access_swinc,
1942       .type = ARM_CP_NO_RAW | ARM_CP_IO,
1943       .writefn = pmswinc_write },
1944     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1945       .access = PL0_RW, .type = ARM_CP_ALIAS,
1946       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1947       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1948       .raw_writefn = raw_write},
1949     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1950       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1951       .access = PL0_RW, .accessfn = pmreg_access_selr,
1952       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1953       .writefn = pmselr_write, .raw_writefn = raw_write, },
1954     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1955       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
1956       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1957       .accessfn = pmreg_access_ccntr },
1958     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1959       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1960       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1961       .type = ARM_CP_IO,
1962       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
1963       .readfn = pmccntr_read, .writefn = pmccntr_write,
1964       .raw_readfn = raw_read, .raw_writefn = raw_write, },
1965     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
1966       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
1967       .access = PL0_RW, .accessfn = pmreg_access,
1968       .type = ARM_CP_ALIAS | ARM_CP_IO,
1969       .resetvalue = 0, },
1970     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1971       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1972       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
1973       .access = PL0_RW, .accessfn = pmreg_access,
1974       .type = ARM_CP_IO,
1975       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1976       .resetvalue = 0, },
1977     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1978       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1979       .accessfn = pmreg_access,
1980       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1981     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1982       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1983       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1984       .accessfn = pmreg_access,
1985       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1986     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
1987       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1988       .accessfn = pmreg_access_xevcntr,
1989       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
1990     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
1991       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
1992       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1993       .accessfn = pmreg_access_xevcntr,
1994       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
1995     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
1996       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
1997       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
1998       .resetvalue = 0,
1999       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2000     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2001       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2002       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2003       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2004       .resetvalue = 0,
2005       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2006     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2007       .access = PL1_RW, .accessfn = access_tpm,
2008       .type = ARM_CP_ALIAS | ARM_CP_IO,
2009       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2010       .resetvalue = 0,
2011       .writefn = pmintenset_write, .raw_writefn = raw_write },
2012     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2013       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2014       .access = PL1_RW, .accessfn = access_tpm,
2015       .type = ARM_CP_IO,
2016       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2017       .writefn = pmintenset_write, .raw_writefn = raw_write,
2018       .resetvalue = 0x0 },
2019     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2020       .access = PL1_RW, .accessfn = access_tpm,
2021       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2022       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2023       .writefn = pmintenclr_write, },
2024     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2025       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2026       .access = PL1_RW, .accessfn = access_tpm,
2027       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2028       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2029       .writefn = pmintenclr_write },
2030     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2031       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2032       .access = PL1_R,
2033       .accessfn = access_aa64_tid2,
2034       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2035     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2036       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2037       .access = PL1_RW,
2038       .accessfn = access_aa64_tid2,
2039       .writefn = csselr_write, .resetvalue = 0,
2040       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2041                              offsetof(CPUARMState, cp15.csselr_ns) } },
2042     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2043      * just RAZ for all cores:
2044      */
2045     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2046       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2047       .access = PL1_R, .type = ARM_CP_CONST,
2048       .accessfn = access_aa64_tid1,
2049       .resetvalue = 0 },
2050     /* Auxiliary fault status registers: these also are IMPDEF, and we
2051      * choose to RAZ/WI for all cores.
2052      */
2053     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2054       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2055       .access = PL1_RW, .accessfn = access_tvm_trvm,
2056       .type = ARM_CP_CONST, .resetvalue = 0 },
2057     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2058       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2059       .access = PL1_RW, .accessfn = access_tvm_trvm,
2060       .type = ARM_CP_CONST, .resetvalue = 0 },
2061     /* MAIR can just read-as-written because we don't implement caches
2062      * and so don't need to care about memory attributes.
2063      */
2064     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2065       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2066       .access = PL1_RW, .accessfn = access_tvm_trvm,
2067       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2068       .resetvalue = 0 },
2069     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2070       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2071       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2072       .resetvalue = 0 },
2073     /* For non-long-descriptor page tables these are PRRR and NMRR;
2074      * regardless they still act as reads-as-written for QEMU.
2075      */
2076      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2077       * allows them to assign the correct fieldoffset based on the endianness
2078       * handled in the field definitions.
2079       */
2080     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2081       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2082       .access = PL1_RW, .accessfn = access_tvm_trvm,
2083       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2084                              offsetof(CPUARMState, cp15.mair0_ns) },
2085       .resetfn = arm_cp_reset_ignore },
2086     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2087       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2088       .access = PL1_RW, .accessfn = access_tvm_trvm,
2089       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2090                              offsetof(CPUARMState, cp15.mair1_ns) },
2091       .resetfn = arm_cp_reset_ignore },
2092     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2093       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2094       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2095     /* 32 bit ITLB invalidates */
2096     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2097       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2098       .writefn = tlbiall_write },
2099     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2100       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2101       .writefn = tlbimva_write },
2102     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2103       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2104       .writefn = tlbiasid_write },
2105     /* 32 bit DTLB invalidates */
2106     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2107       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2108       .writefn = tlbiall_write },
2109     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2110       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2111       .writefn = tlbimva_write },
2112     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2113       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2114       .writefn = tlbiasid_write },
2115     /* 32 bit TLB invalidates */
2116     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2117       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2118       .writefn = tlbiall_write },
2119     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2120       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2121       .writefn = tlbimva_write },
2122     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2123       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2124       .writefn = tlbiasid_write },
2125     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2126       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2127       .writefn = tlbimvaa_write },
2128 };
2129 
2130 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2131     /* 32 bit TLB invalidates, Inner Shareable */
2132     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2133       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2134       .writefn = tlbiall_is_write },
2135     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2136       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2137       .writefn = tlbimva_is_write },
2138     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2139       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2140       .writefn = tlbiasid_is_write },
2141     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2142       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2143       .writefn = tlbimvaa_is_write },
2144 };
2145 
2146 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2147     /* PMOVSSET is not implemented in v7 before v7ve */
2148     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2149       .access = PL0_RW, .accessfn = pmreg_access,
2150       .type = ARM_CP_ALIAS | ARM_CP_IO,
2151       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2152       .writefn = pmovsset_write,
2153       .raw_writefn = raw_write },
2154     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2155       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2156       .access = PL0_RW, .accessfn = pmreg_access,
2157       .type = ARM_CP_ALIAS | ARM_CP_IO,
2158       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2159       .writefn = pmovsset_write,
2160       .raw_writefn = raw_write },
2161 };
2162 
2163 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2164                         uint64_t value)
2165 {
2166     value &= 1;
2167     env->teecr = value;
2168 }
2169 
2170 static CPAccessResult teecr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2171                                    bool isread)
2172 {
2173     /*
2174      * HSTR.TTEE only exists in v7A, not v8A, but v8A doesn't have T2EE
2175      * at all, so we don't need to check whether we're v8A.
2176      */
2177     if (arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
2178         (env->cp15.hstr_el2 & HSTR_TTEE)) {
2179         return CP_ACCESS_TRAP_EL2;
2180     }
2181     return CP_ACCESS_OK;
2182 }
2183 
2184 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2185                                     bool isread)
2186 {
2187     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2188         return CP_ACCESS_TRAP;
2189     }
2190     return teecr_access(env, ri, isread);
2191 }
2192 
2193 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2194     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2195       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2196       .resetvalue = 0,
2197       .writefn = teecr_write, .accessfn = teecr_access },
2198     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2199       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2200       .accessfn = teehbr_access, .resetvalue = 0 },
2201 };
2202 
2203 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2204     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2205       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2206       .access = PL0_RW,
2207       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2208     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2209       .access = PL0_RW,
2210       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2211                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2212       .resetfn = arm_cp_reset_ignore },
2213     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2214       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2215       .access = PL0_R|PL1_W,
2216       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2217       .resetvalue = 0},
2218     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2219       .access = PL0_R|PL1_W,
2220       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2221                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2222       .resetfn = arm_cp_reset_ignore },
2223     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2224       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2225       .access = PL1_RW,
2226       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2227     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2228       .access = PL1_RW,
2229       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2230                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2231       .resetvalue = 0 },
2232 };
2233 
2234 #ifndef CONFIG_USER_ONLY
2235 
2236 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2237                                        bool isread)
2238 {
2239     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2240      * Writable only at the highest implemented exception level.
2241      */
2242     int el = arm_current_el(env);
2243     uint64_t hcr;
2244     uint32_t cntkctl;
2245 
2246     switch (el) {
2247     case 0:
2248         hcr = arm_hcr_el2_eff(env);
2249         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2250             cntkctl = env->cp15.cnthctl_el2;
2251         } else {
2252             cntkctl = env->cp15.c14_cntkctl;
2253         }
2254         if (!extract32(cntkctl, 0, 2)) {
2255             return CP_ACCESS_TRAP;
2256         }
2257         break;
2258     case 1:
2259         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2260             arm_is_secure_below_el3(env)) {
2261             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2262             return CP_ACCESS_TRAP_UNCATEGORIZED;
2263         }
2264         break;
2265     case 2:
2266     case 3:
2267         break;
2268     }
2269 
2270     if (!isread && el < arm_highest_el(env)) {
2271         return CP_ACCESS_TRAP_UNCATEGORIZED;
2272     }
2273 
2274     return CP_ACCESS_OK;
2275 }
2276 
2277 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2278                                         bool isread)
2279 {
2280     unsigned int cur_el = arm_current_el(env);
2281     bool has_el2 = arm_is_el2_enabled(env);
2282     uint64_t hcr = arm_hcr_el2_eff(env);
2283 
2284     switch (cur_el) {
2285     case 0:
2286         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2287         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2288             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2289                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2290         }
2291 
2292         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2293         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2294             return CP_ACCESS_TRAP;
2295         }
2296 
2297         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2298         if (hcr & HCR_E2H) {
2299             if (timeridx == GTIMER_PHYS &&
2300                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2301                 return CP_ACCESS_TRAP_EL2;
2302             }
2303         } else {
2304             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2305             if (has_el2 && timeridx == GTIMER_PHYS &&
2306                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2307                 return CP_ACCESS_TRAP_EL2;
2308             }
2309         }
2310         break;
2311 
2312     case 1:
2313         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2314         if (has_el2 && timeridx == GTIMER_PHYS &&
2315             (hcr & HCR_E2H
2316              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2317              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2318             return CP_ACCESS_TRAP_EL2;
2319         }
2320         break;
2321     }
2322     return CP_ACCESS_OK;
2323 }
2324 
2325 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2326                                       bool isread)
2327 {
2328     unsigned int cur_el = arm_current_el(env);
2329     bool has_el2 = arm_is_el2_enabled(env);
2330     uint64_t hcr = arm_hcr_el2_eff(env);
2331 
2332     switch (cur_el) {
2333     case 0:
2334         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2335             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2336             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2337                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2338         }
2339 
2340         /*
2341          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2342          * EL0 if EL0[PV]TEN is zero.
2343          */
2344         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2345             return CP_ACCESS_TRAP;
2346         }
2347         /* fall through */
2348 
2349     case 1:
2350         if (has_el2 && timeridx == GTIMER_PHYS) {
2351             if (hcr & HCR_E2H) {
2352                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2353                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2354                     return CP_ACCESS_TRAP_EL2;
2355                 }
2356             } else {
2357                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2358                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2359                     return CP_ACCESS_TRAP_EL2;
2360                 }
2361             }
2362         }
2363         break;
2364     }
2365     return CP_ACCESS_OK;
2366 }
2367 
2368 static CPAccessResult gt_pct_access(CPUARMState *env,
2369                                     const ARMCPRegInfo *ri,
2370                                     bool isread)
2371 {
2372     return gt_counter_access(env, GTIMER_PHYS, isread);
2373 }
2374 
2375 static CPAccessResult gt_vct_access(CPUARMState *env,
2376                                     const ARMCPRegInfo *ri,
2377                                     bool isread)
2378 {
2379     return gt_counter_access(env, GTIMER_VIRT, isread);
2380 }
2381 
2382 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2383                                        bool isread)
2384 {
2385     return gt_timer_access(env, GTIMER_PHYS, isread);
2386 }
2387 
2388 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2389                                        bool isread)
2390 {
2391     return gt_timer_access(env, GTIMER_VIRT, isread);
2392 }
2393 
2394 static CPAccessResult gt_stimer_access(CPUARMState *env,
2395                                        const ARMCPRegInfo *ri,
2396                                        bool isread)
2397 {
2398     /* The AArch64 register view of the secure physical timer is
2399      * always accessible from EL3, and configurably accessible from
2400      * Secure EL1.
2401      */
2402     switch (arm_current_el(env)) {
2403     case 1:
2404         if (!arm_is_secure(env)) {
2405             return CP_ACCESS_TRAP;
2406         }
2407         if (!(env->cp15.scr_el3 & SCR_ST)) {
2408             return CP_ACCESS_TRAP_EL3;
2409         }
2410         return CP_ACCESS_OK;
2411     case 0:
2412     case 2:
2413         return CP_ACCESS_TRAP;
2414     case 3:
2415         return CP_ACCESS_OK;
2416     default:
2417         g_assert_not_reached();
2418     }
2419 }
2420 
2421 static uint64_t gt_get_countervalue(CPUARMState *env)
2422 {
2423     ARMCPU *cpu = env_archcpu(env);
2424 
2425     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2426 }
2427 
2428 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2429 {
2430     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2431 
2432     if (gt->ctl & 1) {
2433         /* Timer enabled: calculate and set current ISTATUS, irq, and
2434          * reset timer to when ISTATUS next has to change
2435          */
2436         uint64_t offset = timeridx == GTIMER_VIRT ?
2437                                       cpu->env.cp15.cntvoff_el2 : 0;
2438         uint64_t count = gt_get_countervalue(&cpu->env);
2439         /* Note that this must be unsigned 64 bit arithmetic: */
2440         int istatus = count - offset >= gt->cval;
2441         uint64_t nexttick;
2442         int irqstate;
2443 
2444         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2445 
2446         irqstate = (istatus && !(gt->ctl & 2));
2447         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2448 
2449         if (istatus) {
2450             /* Next transition is when count rolls back over to zero */
2451             nexttick = UINT64_MAX;
2452         } else {
2453             /* Next transition is when we hit cval */
2454             nexttick = gt->cval + offset;
2455         }
2456         /* Note that the desired next expiry time might be beyond the
2457          * signed-64-bit range of a QEMUTimer -- in this case we just
2458          * set the timer for as far in the future as possible. When the
2459          * timer expires we will reset the timer for any remaining period.
2460          */
2461         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2462             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2463         } else {
2464             timer_mod(cpu->gt_timer[timeridx], nexttick);
2465         }
2466         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2467     } else {
2468         /* Timer disabled: ISTATUS and timer output always clear */
2469         gt->ctl &= ~4;
2470         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2471         timer_del(cpu->gt_timer[timeridx]);
2472         trace_arm_gt_recalc_disabled(timeridx);
2473     }
2474 }
2475 
2476 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2477                            int timeridx)
2478 {
2479     ARMCPU *cpu = env_archcpu(env);
2480 
2481     timer_del(cpu->gt_timer[timeridx]);
2482 }
2483 
2484 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2485 {
2486     return gt_get_countervalue(env);
2487 }
2488 
2489 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2490 {
2491     uint64_t hcr;
2492 
2493     switch (arm_current_el(env)) {
2494     case 2:
2495         hcr = arm_hcr_el2_eff(env);
2496         if (hcr & HCR_E2H) {
2497             return 0;
2498         }
2499         break;
2500     case 0:
2501         hcr = arm_hcr_el2_eff(env);
2502         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2503             return 0;
2504         }
2505         break;
2506     }
2507 
2508     return env->cp15.cntvoff_el2;
2509 }
2510 
2511 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2512 {
2513     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2514 }
2515 
2516 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2517                           int timeridx,
2518                           uint64_t value)
2519 {
2520     trace_arm_gt_cval_write(timeridx, value);
2521     env->cp15.c14_timer[timeridx].cval = value;
2522     gt_recalc_timer(env_archcpu(env), timeridx);
2523 }
2524 
2525 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2526                              int timeridx)
2527 {
2528     uint64_t offset = 0;
2529 
2530     switch (timeridx) {
2531     case GTIMER_VIRT:
2532     case GTIMER_HYPVIRT:
2533         offset = gt_virt_cnt_offset(env);
2534         break;
2535     }
2536 
2537     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2538                       (gt_get_countervalue(env) - offset));
2539 }
2540 
2541 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2542                           int timeridx,
2543                           uint64_t value)
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     trace_arm_gt_tval_write(timeridx, value);
2555     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2556                                          sextract64(value, 0, 32);
2557     gt_recalc_timer(env_archcpu(env), timeridx);
2558 }
2559 
2560 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2561                          int timeridx,
2562                          uint64_t value)
2563 {
2564     ARMCPU *cpu = env_archcpu(env);
2565     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2566 
2567     trace_arm_gt_ctl_write(timeridx, value);
2568     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2569     if ((oldval ^ value) & 1) {
2570         /* Enable toggled */
2571         gt_recalc_timer(cpu, timeridx);
2572     } else if ((oldval ^ value) & 2) {
2573         /* IMASK toggled: don't need to recalculate,
2574          * just set the interrupt line based on ISTATUS
2575          */
2576         int irqstate = (oldval & 4) && !(value & 2);
2577 
2578         trace_arm_gt_imask_toggle(timeridx, irqstate);
2579         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2580     }
2581 }
2582 
2583 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2584 {
2585     gt_timer_reset(env, ri, GTIMER_PHYS);
2586 }
2587 
2588 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2589                                uint64_t value)
2590 {
2591     gt_cval_write(env, ri, GTIMER_PHYS, value);
2592 }
2593 
2594 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2595 {
2596     return gt_tval_read(env, ri, GTIMER_PHYS);
2597 }
2598 
2599 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2600                                uint64_t value)
2601 {
2602     gt_tval_write(env, ri, GTIMER_PHYS, value);
2603 }
2604 
2605 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2606                               uint64_t value)
2607 {
2608     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2609 }
2610 
2611 static int gt_phys_redir_timeridx(CPUARMState *env)
2612 {
2613     switch (arm_mmu_idx(env)) {
2614     case ARMMMUIdx_E20_0:
2615     case ARMMMUIdx_E20_2:
2616     case ARMMMUIdx_E20_2_PAN:
2617     case ARMMMUIdx_SE20_0:
2618     case ARMMMUIdx_SE20_2:
2619     case ARMMMUIdx_SE20_2_PAN:
2620         return GTIMER_HYP;
2621     default:
2622         return GTIMER_PHYS;
2623     }
2624 }
2625 
2626 static int gt_virt_redir_timeridx(CPUARMState *env)
2627 {
2628     switch (arm_mmu_idx(env)) {
2629     case ARMMMUIdx_E20_0:
2630     case ARMMMUIdx_E20_2:
2631     case ARMMMUIdx_E20_2_PAN:
2632     case ARMMMUIdx_SE20_0:
2633     case ARMMMUIdx_SE20_2:
2634     case ARMMMUIdx_SE20_2_PAN:
2635         return GTIMER_HYPVIRT;
2636     default:
2637         return GTIMER_VIRT;
2638     }
2639 }
2640 
2641 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2642                                         const ARMCPRegInfo *ri)
2643 {
2644     int timeridx = gt_phys_redir_timeridx(env);
2645     return env->cp15.c14_timer[timeridx].cval;
2646 }
2647 
2648 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2649                                      uint64_t value)
2650 {
2651     int timeridx = gt_phys_redir_timeridx(env);
2652     gt_cval_write(env, ri, timeridx, value);
2653 }
2654 
2655 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2656                                         const ARMCPRegInfo *ri)
2657 {
2658     int timeridx = gt_phys_redir_timeridx(env);
2659     return gt_tval_read(env, ri, timeridx);
2660 }
2661 
2662 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2663                                      uint64_t value)
2664 {
2665     int timeridx = gt_phys_redir_timeridx(env);
2666     gt_tval_write(env, ri, timeridx, value);
2667 }
2668 
2669 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2670                                        const ARMCPRegInfo *ri)
2671 {
2672     int timeridx = gt_phys_redir_timeridx(env);
2673     return env->cp15.c14_timer[timeridx].ctl;
2674 }
2675 
2676 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2677                                     uint64_t value)
2678 {
2679     int timeridx = gt_phys_redir_timeridx(env);
2680     gt_ctl_write(env, ri, timeridx, value);
2681 }
2682 
2683 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2684 {
2685     gt_timer_reset(env, ri, GTIMER_VIRT);
2686 }
2687 
2688 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2689                                uint64_t value)
2690 {
2691     gt_cval_write(env, ri, GTIMER_VIRT, value);
2692 }
2693 
2694 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2695 {
2696     return gt_tval_read(env, ri, GTIMER_VIRT);
2697 }
2698 
2699 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2700                                uint64_t value)
2701 {
2702     gt_tval_write(env, ri, GTIMER_VIRT, value);
2703 }
2704 
2705 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2706                               uint64_t value)
2707 {
2708     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2709 }
2710 
2711 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2712                               uint64_t value)
2713 {
2714     ARMCPU *cpu = env_archcpu(env);
2715 
2716     trace_arm_gt_cntvoff_write(value);
2717     raw_write(env, ri, value);
2718     gt_recalc_timer(cpu, GTIMER_VIRT);
2719 }
2720 
2721 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2722                                         const ARMCPRegInfo *ri)
2723 {
2724     int timeridx = gt_virt_redir_timeridx(env);
2725     return env->cp15.c14_timer[timeridx].cval;
2726 }
2727 
2728 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2729                                      uint64_t value)
2730 {
2731     int timeridx = gt_virt_redir_timeridx(env);
2732     gt_cval_write(env, ri, timeridx, value);
2733 }
2734 
2735 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
2736                                         const ARMCPRegInfo *ri)
2737 {
2738     int timeridx = gt_virt_redir_timeridx(env);
2739     return gt_tval_read(env, ri, timeridx);
2740 }
2741 
2742 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2743                                      uint64_t value)
2744 {
2745     int timeridx = gt_virt_redir_timeridx(env);
2746     gt_tval_write(env, ri, timeridx, value);
2747 }
2748 
2749 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
2750                                        const ARMCPRegInfo *ri)
2751 {
2752     int timeridx = gt_virt_redir_timeridx(env);
2753     return env->cp15.c14_timer[timeridx].ctl;
2754 }
2755 
2756 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2757                                     uint64_t value)
2758 {
2759     int timeridx = gt_virt_redir_timeridx(env);
2760     gt_ctl_write(env, ri, timeridx, value);
2761 }
2762 
2763 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2764 {
2765     gt_timer_reset(env, ri, GTIMER_HYP);
2766 }
2767 
2768 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2769                               uint64_t value)
2770 {
2771     gt_cval_write(env, ri, GTIMER_HYP, value);
2772 }
2773 
2774 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2775 {
2776     return gt_tval_read(env, ri, GTIMER_HYP);
2777 }
2778 
2779 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2780                               uint64_t value)
2781 {
2782     gt_tval_write(env, ri, GTIMER_HYP, value);
2783 }
2784 
2785 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2786                               uint64_t value)
2787 {
2788     gt_ctl_write(env, ri, GTIMER_HYP, value);
2789 }
2790 
2791 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2792 {
2793     gt_timer_reset(env, ri, GTIMER_SEC);
2794 }
2795 
2796 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2797                               uint64_t value)
2798 {
2799     gt_cval_write(env, ri, GTIMER_SEC, value);
2800 }
2801 
2802 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2803 {
2804     return gt_tval_read(env, ri, GTIMER_SEC);
2805 }
2806 
2807 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2808                               uint64_t value)
2809 {
2810     gt_tval_write(env, ri, GTIMER_SEC, value);
2811 }
2812 
2813 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2814                               uint64_t value)
2815 {
2816     gt_ctl_write(env, ri, GTIMER_SEC, value);
2817 }
2818 
2819 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2820 {
2821     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
2822 }
2823 
2824 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2825                              uint64_t value)
2826 {
2827     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
2828 }
2829 
2830 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2831 {
2832     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
2833 }
2834 
2835 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2836                              uint64_t value)
2837 {
2838     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
2839 }
2840 
2841 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2842                             uint64_t value)
2843 {
2844     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
2845 }
2846 
2847 void arm_gt_ptimer_cb(void *opaque)
2848 {
2849     ARMCPU *cpu = opaque;
2850 
2851     gt_recalc_timer(cpu, GTIMER_PHYS);
2852 }
2853 
2854 void arm_gt_vtimer_cb(void *opaque)
2855 {
2856     ARMCPU *cpu = opaque;
2857 
2858     gt_recalc_timer(cpu, GTIMER_VIRT);
2859 }
2860 
2861 void arm_gt_htimer_cb(void *opaque)
2862 {
2863     ARMCPU *cpu = opaque;
2864 
2865     gt_recalc_timer(cpu, GTIMER_HYP);
2866 }
2867 
2868 void arm_gt_stimer_cb(void *opaque)
2869 {
2870     ARMCPU *cpu = opaque;
2871 
2872     gt_recalc_timer(cpu, GTIMER_SEC);
2873 }
2874 
2875 void arm_gt_hvtimer_cb(void *opaque)
2876 {
2877     ARMCPU *cpu = opaque;
2878 
2879     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
2880 }
2881 
2882 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
2883 {
2884     ARMCPU *cpu = env_archcpu(env);
2885 
2886     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
2887 }
2888 
2889 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2890     /* Note that CNTFRQ is purely reads-as-written for the benefit
2891      * of software; writing it doesn't actually change the timer frequency.
2892      * Our reset value matches the fixed frequency we implement the timer at.
2893      */
2894     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2895       .type = ARM_CP_ALIAS,
2896       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2897       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2898     },
2899     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2900       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2901       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2902       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2903       .resetfn = arm_gt_cntfrq_reset,
2904     },
2905     /* overall control: mostly access permissions */
2906     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2907       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2908       .access = PL1_RW,
2909       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2910       .resetvalue = 0,
2911     },
2912     /* per-timer control */
2913     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2914       .secure = ARM_CP_SECSTATE_NS,
2915       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2916       .accessfn = gt_ptimer_access,
2917       .fieldoffset = offsetoflow32(CPUARMState,
2918                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2919       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
2920       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
2921     },
2922     { .name = "CNTP_CTL_S",
2923       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2924       .secure = ARM_CP_SECSTATE_S,
2925       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2926       .accessfn = gt_ptimer_access,
2927       .fieldoffset = offsetoflow32(CPUARMState,
2928                                    cp15.c14_timer[GTIMER_SEC].ctl),
2929       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2930     },
2931     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2932       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2933       .type = ARM_CP_IO, .access = PL0_RW,
2934       .accessfn = gt_ptimer_access,
2935       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2936       .resetvalue = 0,
2937       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
2938       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
2939     },
2940     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2941       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2942       .accessfn = gt_vtimer_access,
2943       .fieldoffset = offsetoflow32(CPUARMState,
2944                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2945       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
2946       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
2947     },
2948     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2949       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2950       .type = ARM_CP_IO, .access = PL0_RW,
2951       .accessfn = gt_vtimer_access,
2952       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2953       .resetvalue = 0,
2954       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
2955       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
2956     },
2957     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2958     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2959       .secure = ARM_CP_SECSTATE_NS,
2960       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2961       .accessfn = gt_ptimer_access,
2962       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
2963     },
2964     { .name = "CNTP_TVAL_S",
2965       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2966       .secure = ARM_CP_SECSTATE_S,
2967       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2968       .accessfn = gt_ptimer_access,
2969       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2970     },
2971     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2972       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2973       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2974       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2975       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
2976     },
2977     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2978       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2979       .accessfn = gt_vtimer_access,
2980       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
2981     },
2982     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2983       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2984       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2985       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2986       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
2987     },
2988     /* The counter itself */
2989     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2990       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2991       .accessfn = gt_pct_access,
2992       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2993     },
2994     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2995       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2996       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2997       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2998     },
2999     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3000       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3001       .accessfn = gt_vct_access,
3002       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3003     },
3004     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3005       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3006       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3007       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3008     },
3009     /* Comparison value, indicating when the timer goes off */
3010     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3011       .secure = ARM_CP_SECSTATE_NS,
3012       .access = PL0_RW,
3013       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3014       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3015       .accessfn = gt_ptimer_access,
3016       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3017       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3018     },
3019     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3020       .secure = ARM_CP_SECSTATE_S,
3021       .access = PL0_RW,
3022       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3023       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3024       .accessfn = gt_ptimer_access,
3025       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3026     },
3027     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3028       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3029       .access = PL0_RW,
3030       .type = ARM_CP_IO,
3031       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3032       .resetvalue = 0, .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 = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3037       .access = PL0_RW,
3038       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3039       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3040       .accessfn = gt_vtimer_access,
3041       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3042       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3043     },
3044     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3045       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3046       .access = PL0_RW,
3047       .type = ARM_CP_IO,
3048       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3049       .resetvalue = 0, .accessfn = gt_vtimer_access,
3050       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3051       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3052     },
3053     /* Secure timer -- this is actually restricted to only EL3
3054      * and configurably Secure-EL1 via the accessfn.
3055      */
3056     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3057       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3058       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3059       .accessfn = gt_stimer_access,
3060       .readfn = gt_sec_tval_read,
3061       .writefn = gt_sec_tval_write,
3062       .resetfn = gt_sec_timer_reset,
3063     },
3064     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3065       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3066       .type = ARM_CP_IO, .access = PL1_RW,
3067       .accessfn = gt_stimer_access,
3068       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3069       .resetvalue = 0,
3070       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3071     },
3072     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3073       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3074       .type = ARM_CP_IO, .access = PL1_RW,
3075       .accessfn = gt_stimer_access,
3076       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3077       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3078     },
3079 };
3080 
3081 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3082                                  bool isread)
3083 {
3084     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3085         return CP_ACCESS_TRAP;
3086     }
3087     return CP_ACCESS_OK;
3088 }
3089 
3090 #else
3091 
3092 /* In user-mode most of the generic timer registers are inaccessible
3093  * however modern kernels (4.12+) allow access to cntvct_el0
3094  */
3095 
3096 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3097 {
3098     ARMCPU *cpu = env_archcpu(env);
3099 
3100     /* Currently we have no support for QEMUTimer in linux-user so we
3101      * can't call gt_get_countervalue(env), instead we directly
3102      * call the lower level functions.
3103      */
3104     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3105 }
3106 
3107 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3108     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3109       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3110       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3111       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3112       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3113     },
3114     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3115       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3116       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3117       .readfn = gt_virt_cnt_read,
3118     },
3119 };
3120 
3121 #endif
3122 
3123 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3124 {
3125     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3126         raw_write(env, ri, value);
3127     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3128         raw_write(env, ri, value & 0xfffff6ff);
3129     } else {
3130         raw_write(env, ri, value & 0xfffff1ff);
3131     }
3132 }
3133 
3134 #ifndef CONFIG_USER_ONLY
3135 /* get_phys_addr() isn't present for user-mode-only targets */
3136 
3137 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3138                                  bool isread)
3139 {
3140     if (ri->opc2 & 4) {
3141         /* The ATS12NSO* operations must trap to EL3 or EL2 if executed in
3142          * Secure EL1 (which can only happen if EL3 is AArch64).
3143          * They are simply UNDEF if executed from NS EL1.
3144          * They function normally from EL2 or EL3.
3145          */
3146         if (arm_current_el(env) == 1) {
3147             if (arm_is_secure_below_el3(env)) {
3148                 if (env->cp15.scr_el3 & SCR_EEL2) {
3149                     return CP_ACCESS_TRAP_UNCATEGORIZED_EL2;
3150                 }
3151                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3152             }
3153             return CP_ACCESS_TRAP_UNCATEGORIZED;
3154         }
3155     }
3156     return CP_ACCESS_OK;
3157 }
3158 
3159 #ifdef CONFIG_TCG
3160 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3161                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3162 {
3163     hwaddr phys_addr;
3164     target_ulong page_size;
3165     int prot;
3166     bool ret;
3167     uint64_t par64;
3168     bool format64 = false;
3169     MemTxAttrs attrs = {};
3170     ARMMMUFaultInfo fi = {};
3171     ARMCacheAttrs cacheattrs = {};
3172 
3173     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3174                         &prot, &page_size, &fi, &cacheattrs);
3175 
3176     if (ret) {
3177         /*
3178          * Some kinds of translation fault must cause exceptions rather
3179          * than being reported in the PAR.
3180          */
3181         int current_el = arm_current_el(env);
3182         int target_el;
3183         uint32_t syn, fsr, fsc;
3184         bool take_exc = false;
3185 
3186         if (fi.s1ptw && current_el == 1
3187             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3188             /*
3189              * Synchronous stage 2 fault on an access made as part of the
3190              * translation table walk for AT S1E0* or AT S1E1* insn
3191              * executed from NS EL1. If this is a synchronous external abort
3192              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3193              * to EL3. Otherwise the fault is taken as an exception to EL2,
3194              * and HPFAR_EL2 holds the faulting IPA.
3195              */
3196             if (fi.type == ARMFault_SyncExternalOnWalk &&
3197                 (env->cp15.scr_el3 & SCR_EA)) {
3198                 target_el = 3;
3199             } else {
3200                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3201                 if (arm_is_secure_below_el3(env) && fi.s1ns) {
3202                     env->cp15.hpfar_el2 |= HPFAR_NS;
3203                 }
3204                 target_el = 2;
3205             }
3206             take_exc = true;
3207         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3208             /*
3209              * Synchronous external aborts during a translation table walk
3210              * are taken as Data Abort exceptions.
3211              */
3212             if (fi.stage2) {
3213                 if (current_el == 3) {
3214                     target_el = 3;
3215                 } else {
3216                     target_el = 2;
3217                 }
3218             } else {
3219                 target_el = exception_target_el(env);
3220             }
3221             take_exc = true;
3222         }
3223 
3224         if (take_exc) {
3225             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3226             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3227                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3228                 fsr = arm_fi_to_lfsc(&fi);
3229                 fsc = extract32(fsr, 0, 6);
3230             } else {
3231                 fsr = arm_fi_to_sfsc(&fi);
3232                 fsc = 0x3f;
3233             }
3234             /*
3235              * Report exception with ESR indicating a fault due to a
3236              * translation table walk for a cache maintenance instruction.
3237              */
3238             syn = syn_data_abort_no_iss(current_el == target_el, 0,
3239                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3240             env->exception.vaddress = value;
3241             env->exception.fsr = fsr;
3242             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3243         }
3244     }
3245 
3246     if (is_a64(env)) {
3247         format64 = true;
3248     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3249         /*
3250          * ATS1Cxx:
3251          * * TTBCR.EAE determines whether the result is returned using the
3252          *   32-bit or the 64-bit PAR format
3253          * * Instructions executed in Hyp mode always use the 64bit format
3254          *
3255          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3256          * * The Non-secure TTBCR.EAE bit is set to 1
3257          * * The implementation includes EL2, and the value of HCR.VM is 1
3258          *
3259          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3260          *
3261          * ATS1Hx always uses the 64bit format.
3262          */
3263         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3264 
3265         if (arm_feature(env, ARM_FEATURE_EL2)) {
3266             if (mmu_idx == ARMMMUIdx_E10_0 ||
3267                 mmu_idx == ARMMMUIdx_E10_1 ||
3268                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3269                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3270             } else {
3271                 format64 |= arm_current_el(env) == 2;
3272             }
3273         }
3274     }
3275 
3276     if (format64) {
3277         /* Create a 64-bit PAR */
3278         par64 = (1 << 11); /* LPAE bit always set */
3279         if (!ret) {
3280             par64 |= phys_addr & ~0xfffULL;
3281             if (!attrs.secure) {
3282                 par64 |= (1 << 9); /* NS */
3283             }
3284             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3285             par64 |= cacheattrs.shareability << 7; /* SH */
3286         } else {
3287             uint32_t fsr = arm_fi_to_lfsc(&fi);
3288 
3289             par64 |= 1; /* F */
3290             par64 |= (fsr & 0x3f) << 1; /* FS */
3291             if (fi.stage2) {
3292                 par64 |= (1 << 9); /* S */
3293             }
3294             if (fi.s1ptw) {
3295                 par64 |= (1 << 8); /* PTW */
3296             }
3297         }
3298     } else {
3299         /* fsr is a DFSR/IFSR value for the short descriptor
3300          * translation table format (with WnR always clear).
3301          * Convert it to a 32-bit PAR.
3302          */
3303         if (!ret) {
3304             /* We do not set any attribute bits in the PAR */
3305             if (page_size == (1 << 24)
3306                 && arm_feature(env, ARM_FEATURE_V7)) {
3307                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3308             } else {
3309                 par64 = phys_addr & 0xfffff000;
3310             }
3311             if (!attrs.secure) {
3312                 par64 |= (1 << 9); /* NS */
3313             }
3314         } else {
3315             uint32_t fsr = arm_fi_to_sfsc(&fi);
3316 
3317             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3318                     ((fsr & 0xf) << 1) | 1;
3319         }
3320     }
3321     return par64;
3322 }
3323 #endif /* CONFIG_TCG */
3324 
3325 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3326 {
3327 #ifdef CONFIG_TCG
3328     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3329     uint64_t par64;
3330     ARMMMUIdx mmu_idx;
3331     int el = arm_current_el(env);
3332     bool secure = arm_is_secure_below_el3(env);
3333 
3334     switch (ri->opc2 & 6) {
3335     case 0:
3336         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3337         switch (el) {
3338         case 3:
3339             mmu_idx = ARMMMUIdx_SE3;
3340             break;
3341         case 2:
3342             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3343             /* fall through */
3344         case 1:
3345             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3346                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3347                            : ARMMMUIdx_Stage1_E1_PAN);
3348             } else {
3349                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3350             }
3351             break;
3352         default:
3353             g_assert_not_reached();
3354         }
3355         break;
3356     case 2:
3357         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3358         switch (el) {
3359         case 3:
3360             mmu_idx = ARMMMUIdx_SE10_0;
3361             break;
3362         case 2:
3363             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3364             mmu_idx = ARMMMUIdx_Stage1_E0;
3365             break;
3366         case 1:
3367             mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3368             break;
3369         default:
3370             g_assert_not_reached();
3371         }
3372         break;
3373     case 4:
3374         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3375         mmu_idx = ARMMMUIdx_E10_1;
3376         break;
3377     case 6:
3378         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3379         mmu_idx = ARMMMUIdx_E10_0;
3380         break;
3381     default:
3382         g_assert_not_reached();
3383     }
3384 
3385     par64 = do_ats_write(env, value, access_type, mmu_idx);
3386 
3387     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3388 #else
3389     /* Handled by hardware accelerator. */
3390     g_assert_not_reached();
3391 #endif /* CONFIG_TCG */
3392 }
3393 
3394 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3395                         uint64_t value)
3396 {
3397 #ifdef CONFIG_TCG
3398     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3399     uint64_t par64;
3400 
3401     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3402 
3403     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3404 #else
3405     /* Handled by hardware accelerator. */
3406     g_assert_not_reached();
3407 #endif /* CONFIG_TCG */
3408 }
3409 
3410 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3411                                      bool isread)
3412 {
3413     if (arm_current_el(env) == 3 &&
3414         !(env->cp15.scr_el3 & (SCR_NS | SCR_EEL2))) {
3415         return CP_ACCESS_TRAP;
3416     }
3417     return CP_ACCESS_OK;
3418 }
3419 
3420 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3421                         uint64_t value)
3422 {
3423 #ifdef CONFIG_TCG
3424     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3425     ARMMMUIdx mmu_idx;
3426     int secure = arm_is_secure_below_el3(env);
3427 
3428     switch (ri->opc2 & 6) {
3429     case 0:
3430         switch (ri->opc1) {
3431         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3432             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3433                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3434                            : ARMMMUIdx_Stage1_E1_PAN);
3435             } else {
3436                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3437             }
3438             break;
3439         case 4: /* AT S1E2R, AT S1E2W */
3440             mmu_idx = secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2;
3441             break;
3442         case 6: /* AT S1E3R, AT S1E3W */
3443             mmu_idx = ARMMMUIdx_SE3;
3444             break;
3445         default:
3446             g_assert_not_reached();
3447         }
3448         break;
3449     case 2: /* AT S1E0R, AT S1E0W */
3450         mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3451         break;
3452     case 4: /* AT S12E1R, AT S12E1W */
3453         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3454         break;
3455     case 6: /* AT S12E0R, AT S12E0W */
3456         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3457         break;
3458     default:
3459         g_assert_not_reached();
3460     }
3461 
3462     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3463 #else
3464     /* Handled by hardware accelerator. */
3465     g_assert_not_reached();
3466 #endif /* CONFIG_TCG */
3467 }
3468 #endif
3469 
3470 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3471     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3472       .access = PL1_RW, .resetvalue = 0,
3473       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3474                              offsetoflow32(CPUARMState, cp15.par_ns) },
3475       .writefn = par_write },
3476 #ifndef CONFIG_USER_ONLY
3477     /* This underdecoding is safe because the reginfo is NO_RAW. */
3478     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3479       .access = PL1_W, .accessfn = ats_access,
3480       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3481 #endif
3482 };
3483 
3484 /* Return basic MPU access permission bits.  */
3485 static uint32_t simple_mpu_ap_bits(uint32_t val)
3486 {
3487     uint32_t ret;
3488     uint32_t mask;
3489     int i;
3490     ret = 0;
3491     mask = 3;
3492     for (i = 0; i < 16; i += 2) {
3493         ret |= (val >> i) & mask;
3494         mask <<= 2;
3495     }
3496     return ret;
3497 }
3498 
3499 /* Pad basic MPU access permission bits to extended format.  */
3500 static uint32_t extended_mpu_ap_bits(uint32_t val)
3501 {
3502     uint32_t ret;
3503     uint32_t mask;
3504     int i;
3505     ret = 0;
3506     mask = 3;
3507     for (i = 0; i < 16; i += 2) {
3508         ret |= (val & mask) << i;
3509         mask <<= 2;
3510     }
3511     return ret;
3512 }
3513 
3514 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3515                                  uint64_t value)
3516 {
3517     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3518 }
3519 
3520 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3521 {
3522     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3523 }
3524 
3525 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3526                                  uint64_t value)
3527 {
3528     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3529 }
3530 
3531 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3532 {
3533     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3534 }
3535 
3536 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3537 {
3538     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3539 
3540     if (!u32p) {
3541         return 0;
3542     }
3543 
3544     u32p += env->pmsav7.rnr[M_REG_NS];
3545     return *u32p;
3546 }
3547 
3548 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3549                          uint64_t value)
3550 {
3551     ARMCPU *cpu = env_archcpu(env);
3552     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3553 
3554     if (!u32p) {
3555         return;
3556     }
3557 
3558     u32p += env->pmsav7.rnr[M_REG_NS];
3559     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3560     *u32p = value;
3561 }
3562 
3563 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3564                               uint64_t value)
3565 {
3566     ARMCPU *cpu = env_archcpu(env);
3567     uint32_t nrgs = cpu->pmsav7_dregion;
3568 
3569     if (value >= nrgs) {
3570         qemu_log_mask(LOG_GUEST_ERROR,
3571                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3572                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3573         return;
3574     }
3575 
3576     raw_write(env, ri, value);
3577 }
3578 
3579 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3580     /* Reset for all these registers is handled in arm_cpu_reset(),
3581      * because the PMSAv7 is also used by M-profile CPUs, which do
3582      * not register cpregs but still need the state to be reset.
3583      */
3584     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3585       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3586       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3587       .readfn = pmsav7_read, .writefn = pmsav7_write,
3588       .resetfn = arm_cp_reset_ignore },
3589     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3590       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3591       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3592       .readfn = pmsav7_read, .writefn = pmsav7_write,
3593       .resetfn = arm_cp_reset_ignore },
3594     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3595       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3596       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3597       .readfn = pmsav7_read, .writefn = pmsav7_write,
3598       .resetfn = arm_cp_reset_ignore },
3599     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3600       .access = PL1_RW,
3601       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3602       .writefn = pmsav7_rgnr_write,
3603       .resetfn = arm_cp_reset_ignore },
3604 };
3605 
3606 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3607     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3608       .access = PL1_RW, .type = ARM_CP_ALIAS,
3609       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3610       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3611     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3612       .access = PL1_RW, .type = ARM_CP_ALIAS,
3613       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3614       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3615     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3616       .access = PL1_RW,
3617       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3618       .resetvalue = 0, },
3619     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3620       .access = PL1_RW,
3621       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3622       .resetvalue = 0, },
3623     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3624       .access = PL1_RW,
3625       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3626     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3627       .access = PL1_RW,
3628       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3629     /* Protection region base and size registers */
3630     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3631       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3632       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3633     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3634       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3635       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3636     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3637       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3638       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3639     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3640       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3641       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3642     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3643       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3644       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3645     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3646       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3647       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3648     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3649       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3650       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3651     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3652       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3653       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3654 };
3655 
3656 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3657                                  uint64_t value)
3658 {
3659     TCR *tcr = raw_ptr(env, ri);
3660     int maskshift = extract32(value, 0, 3);
3661 
3662     if (!arm_feature(env, ARM_FEATURE_V8)) {
3663         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3664             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3665              * using Long-desciptor translation table format */
3666             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3667         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3668             /* In an implementation that includes the Security Extensions
3669              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3670              * Short-descriptor translation table format.
3671              */
3672             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3673         } else {
3674             value &= TTBCR_N;
3675         }
3676     }
3677 
3678     /* Update the masks corresponding to the TCR bank being written
3679      * Note that we always calculate mask and base_mask, but
3680      * they are only used for short-descriptor tables (ie if EAE is 0);
3681      * for long-descriptor tables the TCR fields are used differently
3682      * and the mask and base_mask values are meaningless.
3683      */
3684     tcr->raw_tcr = value;
3685     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3686     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3687 }
3688 
3689 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3690                              uint64_t value)
3691 {
3692     ARMCPU *cpu = env_archcpu(env);
3693     TCR *tcr = raw_ptr(env, ri);
3694 
3695     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3696         /* With LPAE the TTBCR could result in a change of ASID
3697          * via the TTBCR.A1 bit, so do a TLB flush.
3698          */
3699         tlb_flush(CPU(cpu));
3700     }
3701     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3702     value = deposit64(tcr->raw_tcr, 0, 32, value);
3703     vmsa_ttbcr_raw_write(env, ri, value);
3704 }
3705 
3706 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3707 {
3708     TCR *tcr = raw_ptr(env, ri);
3709 
3710     /* Reset both the TCR as well as the masks corresponding to the bank of
3711      * the TCR being reset.
3712      */
3713     tcr->raw_tcr = 0;
3714     tcr->mask = 0;
3715     tcr->base_mask = 0xffffc000u;
3716 }
3717 
3718 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3719                                uint64_t value)
3720 {
3721     ARMCPU *cpu = env_archcpu(env);
3722     TCR *tcr = raw_ptr(env, ri);
3723 
3724     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3725     tlb_flush(CPU(cpu));
3726     tcr->raw_tcr = value;
3727 }
3728 
3729 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3730                             uint64_t value)
3731 {
3732     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3733     if (cpreg_field_is_64bit(ri) &&
3734         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3735         ARMCPU *cpu = env_archcpu(env);
3736         tlb_flush(CPU(cpu));
3737     }
3738     raw_write(env, ri, value);
3739 }
3740 
3741 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3742                                     uint64_t value)
3743 {
3744     /*
3745      * If we are running with E2&0 regime, then an ASID is active.
3746      * Flush if that might be changing.  Note we're not checking
3747      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
3748      * holds the active ASID, only checking the field that might.
3749      */
3750     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
3751         (arm_hcr_el2_eff(env) & HCR_E2H)) {
3752         uint16_t mask = ARMMMUIdxBit_E20_2 |
3753                         ARMMMUIdxBit_E20_2_PAN |
3754                         ARMMMUIdxBit_E20_0;
3755 
3756         if (arm_is_secure_below_el3(env)) {
3757             mask >>= ARM_MMU_IDX_A_NS;
3758         }
3759 
3760         tlb_flush_by_mmuidx(env_cpu(env), mask);
3761     }
3762     raw_write(env, ri, value);
3763 }
3764 
3765 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3766                         uint64_t value)
3767 {
3768     ARMCPU *cpu = env_archcpu(env);
3769     CPUState *cs = CPU(cpu);
3770 
3771     /*
3772      * A change in VMID to the stage2 page table (Stage2) invalidates
3773      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
3774      */
3775     if (raw_read(env, ri) != value) {
3776         uint16_t mask = ARMMMUIdxBit_E10_1 |
3777                         ARMMMUIdxBit_E10_1_PAN |
3778                         ARMMMUIdxBit_E10_0;
3779 
3780         if (arm_is_secure_below_el3(env)) {
3781             mask >>= ARM_MMU_IDX_A_NS;
3782         }
3783 
3784         tlb_flush_by_mmuidx(cs, mask);
3785         raw_write(env, ri, value);
3786     }
3787 }
3788 
3789 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3790     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3791       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
3792       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3793                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3794     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3795       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3796       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3797                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3798     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3799       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3800       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3801                              offsetof(CPUARMState, cp15.dfar_ns) } },
3802     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3803       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3804       .access = PL1_RW, .accessfn = access_tvm_trvm,
3805       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3806       .resetvalue = 0, },
3807 };
3808 
3809 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3810     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3811       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3812       .access = PL1_RW, .accessfn = access_tvm_trvm,
3813       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3814     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3815       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3816       .access = PL1_RW, .accessfn = access_tvm_trvm,
3817       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3818       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3819                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3820     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3821       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3822       .access = PL1_RW, .accessfn = access_tvm_trvm,
3823       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3824       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3825                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3826     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3827       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3828       .access = PL1_RW, .accessfn = access_tvm_trvm,
3829       .writefn = vmsa_tcr_el12_write,
3830       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3831       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3832     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3833       .access = PL1_RW, .accessfn = access_tvm_trvm,
3834       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3835       .raw_writefn = vmsa_ttbcr_raw_write,
3836       /* No offsetoflow32 -- pass the entire TCR to writefn/raw_writefn. */
3837       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.tcr_el[3]),
3838                              offsetof(CPUARMState, cp15.tcr_el[1])} },
3839 };
3840 
3841 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3842  * qemu tlbs nor adjusting cached masks.
3843  */
3844 static const ARMCPRegInfo ttbcr2_reginfo = {
3845     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3846     .access = PL1_RW, .accessfn = access_tvm_trvm,
3847     .type = ARM_CP_ALIAS,
3848     .bank_fieldoffsets = {
3849         offsetofhigh32(CPUARMState, cp15.tcr_el[3].raw_tcr),
3850         offsetofhigh32(CPUARMState, cp15.tcr_el[1].raw_tcr),
3851     },
3852 };
3853 
3854 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3855                                 uint64_t value)
3856 {
3857     env->cp15.c15_ticonfig = value & 0xe7;
3858     /* The OS_TYPE bit in this register changes the reported CPUID! */
3859     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3860         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3861 }
3862 
3863 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3864                                 uint64_t value)
3865 {
3866     env->cp15.c15_threadid = value & 0xffff;
3867 }
3868 
3869 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3870                            uint64_t value)
3871 {
3872     /* Wait-for-interrupt (deprecated) */
3873     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
3874 }
3875 
3876 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3877                                   uint64_t value)
3878 {
3879     /* On OMAP there are registers indicating the max/min index of dcache lines
3880      * containing a dirty line; cache flush operations have to reset these.
3881      */
3882     env->cp15.c15_i_max = 0x000;
3883     env->cp15.c15_i_min = 0xff0;
3884 }
3885 
3886 static const ARMCPRegInfo omap_cp_reginfo[] = {
3887     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3888       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3889       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3890       .resetvalue = 0, },
3891     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3892       .access = PL1_RW, .type = ARM_CP_NOP },
3893     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3894       .access = PL1_RW,
3895       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3896       .writefn = omap_ticonfig_write },
3897     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3898       .access = PL1_RW,
3899       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3900     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3901       .access = PL1_RW, .resetvalue = 0xff0,
3902       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3903     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3904       .access = PL1_RW,
3905       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3906       .writefn = omap_threadid_write },
3907     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3908       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3909       .type = ARM_CP_NO_RAW,
3910       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3911     /* TODO: Peripheral port remap register:
3912      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3913      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3914      * when MMU is off.
3915      */
3916     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3917       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3918       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3919       .writefn = omap_cachemaint_write },
3920     { .name = "C9", .cp = 15, .crn = 9,
3921       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3922       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3923 };
3924 
3925 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3926                               uint64_t value)
3927 {
3928     env->cp15.c15_cpar = value & 0x3fff;
3929 }
3930 
3931 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3932     { .name = "XSCALE_CPAR",
3933       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3934       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3935       .writefn = xscale_cpar_write, },
3936     { .name = "XSCALE_AUXCR",
3937       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3938       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3939       .resetvalue = 0, },
3940     /* XScale specific cache-lockdown: since we have no cache we NOP these
3941      * and hope the guest does not really rely on cache behaviour.
3942      */
3943     { .name = "XSCALE_LOCK_ICACHE_LINE",
3944       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3945       .access = PL1_W, .type = ARM_CP_NOP },
3946     { .name = "XSCALE_UNLOCK_ICACHE",
3947       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3948       .access = PL1_W, .type = ARM_CP_NOP },
3949     { .name = "XSCALE_DCACHE_LOCK",
3950       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3951       .access = PL1_RW, .type = ARM_CP_NOP },
3952     { .name = "XSCALE_UNLOCK_DCACHE",
3953       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3954       .access = PL1_W, .type = ARM_CP_NOP },
3955 };
3956 
3957 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3958     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3959      * implementation of this implementation-defined space.
3960      * Ideally this should eventually disappear in favour of actually
3961      * implementing the correct behaviour for all cores.
3962      */
3963     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3964       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3965       .access = PL1_RW,
3966       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3967       .resetvalue = 0 },
3968 };
3969 
3970 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3971     /* Cache status: RAZ because we have no cache so it's always clean */
3972     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3973       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3974       .resetvalue = 0 },
3975 };
3976 
3977 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
3978     /* We never have a a block transfer operation in progress */
3979     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
3980       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3981       .resetvalue = 0 },
3982     /* The cache ops themselves: these all NOP for QEMU */
3983     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
3984       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3985     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
3986       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3987     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
3988       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3989     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
3990       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3991     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
3992       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3993     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
3994       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3995 };
3996 
3997 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
3998     /* The cache test-and-clean instructions always return (1 << 30)
3999      * to indicate that there are no dirty cache lines.
4000      */
4001     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4002       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4003       .resetvalue = (1 << 30) },
4004     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4005       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4006       .resetvalue = (1 << 30) },
4007 };
4008 
4009 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4010     /* Ignore ReadBuffer accesses */
4011     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4012       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4013       .access = PL1_RW, .resetvalue = 0,
4014       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4015 };
4016 
4017 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4018 {
4019     unsigned int cur_el = arm_current_el(env);
4020 
4021     if (arm_is_el2_enabled(env) && cur_el == 1) {
4022         return env->cp15.vpidr_el2;
4023     }
4024     return raw_read(env, ri);
4025 }
4026 
4027 static uint64_t mpidr_read_val(CPUARMState *env)
4028 {
4029     ARMCPU *cpu = env_archcpu(env);
4030     uint64_t mpidr = cpu->mp_affinity;
4031 
4032     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4033         mpidr |= (1U << 31);
4034         /* Cores which are uniprocessor (non-coherent)
4035          * but still implement the MP extensions set
4036          * bit 30. (For instance, Cortex-R5).
4037          */
4038         if (cpu->mp_is_up) {
4039             mpidr |= (1u << 30);
4040         }
4041     }
4042     return mpidr;
4043 }
4044 
4045 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4046 {
4047     unsigned int cur_el = arm_current_el(env);
4048 
4049     if (arm_is_el2_enabled(env) && cur_el == 1) {
4050         return env->cp15.vmpidr_el2;
4051     }
4052     return mpidr_read_val(env);
4053 }
4054 
4055 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4056     /* NOP AMAIR0/1 */
4057     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4058       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4059       .access = PL1_RW, .accessfn = access_tvm_trvm,
4060       .type = ARM_CP_CONST, .resetvalue = 0 },
4061     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4062     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4063       .access = PL1_RW, .accessfn = access_tvm_trvm,
4064       .type = ARM_CP_CONST, .resetvalue = 0 },
4065     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4066       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4067       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4068                              offsetof(CPUARMState, cp15.par_ns)} },
4069     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4070       .access = PL1_RW, .accessfn = access_tvm_trvm,
4071       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4072       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4073                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4074       .writefn = vmsa_ttbr_write, },
4075     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4076       .access = PL1_RW, .accessfn = access_tvm_trvm,
4077       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4078       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4079                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4080       .writefn = vmsa_ttbr_write, },
4081 };
4082 
4083 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4084 {
4085     return vfp_get_fpcr(env);
4086 }
4087 
4088 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4089                             uint64_t value)
4090 {
4091     vfp_set_fpcr(env, value);
4092 }
4093 
4094 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4095 {
4096     return vfp_get_fpsr(env);
4097 }
4098 
4099 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4100                             uint64_t value)
4101 {
4102     vfp_set_fpsr(env, value);
4103 }
4104 
4105 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4106                                        bool isread)
4107 {
4108     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4109         return CP_ACCESS_TRAP;
4110     }
4111     return CP_ACCESS_OK;
4112 }
4113 
4114 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4115                             uint64_t value)
4116 {
4117     env->daif = value & PSTATE_DAIF;
4118 }
4119 
4120 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4121 {
4122     return env->pstate & PSTATE_PAN;
4123 }
4124 
4125 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4126                            uint64_t value)
4127 {
4128     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4129 }
4130 
4131 static const ARMCPRegInfo pan_reginfo = {
4132     .name = "PAN", .state = ARM_CP_STATE_AA64,
4133     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4134     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4135     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4136 };
4137 
4138 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4139 {
4140     return env->pstate & PSTATE_UAO;
4141 }
4142 
4143 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4144                            uint64_t value)
4145 {
4146     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4147 }
4148 
4149 static const ARMCPRegInfo uao_reginfo = {
4150     .name = "UAO", .state = ARM_CP_STATE_AA64,
4151     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4152     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4153     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4154 };
4155 
4156 static uint64_t aa64_dit_read(CPUARMState *env, const ARMCPRegInfo *ri)
4157 {
4158     return env->pstate & PSTATE_DIT;
4159 }
4160 
4161 static void aa64_dit_write(CPUARMState *env, const ARMCPRegInfo *ri,
4162                            uint64_t value)
4163 {
4164     env->pstate = (env->pstate & ~PSTATE_DIT) | (value & PSTATE_DIT);
4165 }
4166 
4167 static const ARMCPRegInfo dit_reginfo = {
4168     .name = "DIT", .state = ARM_CP_STATE_AA64,
4169     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 5,
4170     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4171     .readfn = aa64_dit_read, .writefn = aa64_dit_write
4172 };
4173 
4174 static uint64_t aa64_ssbs_read(CPUARMState *env, const ARMCPRegInfo *ri)
4175 {
4176     return env->pstate & PSTATE_SSBS;
4177 }
4178 
4179 static void aa64_ssbs_write(CPUARMState *env, const ARMCPRegInfo *ri,
4180                            uint64_t value)
4181 {
4182     env->pstate = (env->pstate & ~PSTATE_SSBS) | (value & PSTATE_SSBS);
4183 }
4184 
4185 static const ARMCPRegInfo ssbs_reginfo = {
4186     .name = "SSBS", .state = ARM_CP_STATE_AA64,
4187     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 6,
4188     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4189     .readfn = aa64_ssbs_read, .writefn = aa64_ssbs_write
4190 };
4191 
4192 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4193                                               const ARMCPRegInfo *ri,
4194                                               bool isread)
4195 {
4196     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4197     switch (arm_current_el(env)) {
4198     case 0:
4199         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4200         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4201             return CP_ACCESS_TRAP;
4202         }
4203         /* fall through */
4204     case 1:
4205         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4206         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4207             return CP_ACCESS_TRAP_EL2;
4208         }
4209         break;
4210     }
4211     return CP_ACCESS_OK;
4212 }
4213 
4214 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4215                                               const ARMCPRegInfo *ri,
4216                                               bool isread)
4217 {
4218     /* Cache invalidate/clean to Point of Unification... */
4219     switch (arm_current_el(env)) {
4220     case 0:
4221         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4222         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4223             return CP_ACCESS_TRAP;
4224         }
4225         /* fall through */
4226     case 1:
4227         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4228         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4229             return CP_ACCESS_TRAP_EL2;
4230         }
4231         break;
4232     }
4233     return CP_ACCESS_OK;
4234 }
4235 
4236 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4237  * Page D4-1736 (DDI0487A.b)
4238  */
4239 
4240 static int vae1_tlbmask(CPUARMState *env)
4241 {
4242     uint64_t hcr = arm_hcr_el2_eff(env);
4243     uint16_t mask;
4244 
4245     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4246         mask = ARMMMUIdxBit_E20_2 |
4247                ARMMMUIdxBit_E20_2_PAN |
4248                ARMMMUIdxBit_E20_0;
4249     } else {
4250         mask = ARMMMUIdxBit_E10_1 |
4251                ARMMMUIdxBit_E10_1_PAN |
4252                ARMMMUIdxBit_E10_0;
4253     }
4254 
4255     if (arm_is_secure_below_el3(env)) {
4256         mask >>= ARM_MMU_IDX_A_NS;
4257     }
4258 
4259     return mask;
4260 }
4261 
4262 /* Return 56 if TBI is enabled, 64 otherwise. */
4263 static int tlbbits_for_regime(CPUARMState *env, ARMMMUIdx mmu_idx,
4264                               uint64_t addr)
4265 {
4266     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
4267     int tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
4268     int select = extract64(addr, 55, 1);
4269 
4270     return (tbi >> select) & 1 ? 56 : 64;
4271 }
4272 
4273 static int vae1_tlbbits(CPUARMState *env, uint64_t addr)
4274 {
4275     uint64_t hcr = arm_hcr_el2_eff(env);
4276     ARMMMUIdx mmu_idx;
4277 
4278     /* Only the regime of the mmu_idx below is significant. */
4279     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4280         mmu_idx = ARMMMUIdx_E20_0;
4281     } else {
4282         mmu_idx = ARMMMUIdx_E10_0;
4283     }
4284 
4285     if (arm_is_secure_below_el3(env)) {
4286         mmu_idx &= ~ARM_MMU_IDX_A_NS;
4287     }
4288 
4289     return tlbbits_for_regime(env, mmu_idx, addr);
4290 }
4291 
4292 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4293                                       uint64_t value)
4294 {
4295     CPUState *cs = env_cpu(env);
4296     int mask = vae1_tlbmask(env);
4297 
4298     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4299 }
4300 
4301 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4302                                     uint64_t value)
4303 {
4304     CPUState *cs = env_cpu(env);
4305     int mask = vae1_tlbmask(env);
4306 
4307     if (tlb_force_broadcast(env)) {
4308         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4309     } else {
4310         tlb_flush_by_mmuidx(cs, mask);
4311     }
4312 }
4313 
4314 static int alle1_tlbmask(CPUARMState *env)
4315 {
4316     /*
4317      * Note that the 'ALL' scope must invalidate both stage 1 and
4318      * stage 2 translations, whereas most other scopes only invalidate
4319      * stage 1 translations.
4320      */
4321     if (arm_is_secure_below_el3(env)) {
4322         return ARMMMUIdxBit_SE10_1 |
4323                ARMMMUIdxBit_SE10_1_PAN |
4324                ARMMMUIdxBit_SE10_0;
4325     } else {
4326         return ARMMMUIdxBit_E10_1 |
4327                ARMMMUIdxBit_E10_1_PAN |
4328                ARMMMUIdxBit_E10_0;
4329     }
4330 }
4331 
4332 static int e2_tlbmask(CPUARMState *env)
4333 {
4334     if (arm_is_secure_below_el3(env)) {
4335         return ARMMMUIdxBit_SE20_0 |
4336                ARMMMUIdxBit_SE20_2 |
4337                ARMMMUIdxBit_SE20_2_PAN |
4338                ARMMMUIdxBit_SE2;
4339     } else {
4340         return ARMMMUIdxBit_E20_0 |
4341                ARMMMUIdxBit_E20_2 |
4342                ARMMMUIdxBit_E20_2_PAN |
4343                ARMMMUIdxBit_E2;
4344     }
4345 }
4346 
4347 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4348                                   uint64_t value)
4349 {
4350     CPUState *cs = env_cpu(env);
4351     int mask = alle1_tlbmask(env);
4352 
4353     tlb_flush_by_mmuidx(cs, mask);
4354 }
4355 
4356 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4357                                   uint64_t value)
4358 {
4359     CPUState *cs = env_cpu(env);
4360     int mask = e2_tlbmask(env);
4361 
4362     tlb_flush_by_mmuidx(cs, mask);
4363 }
4364 
4365 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4366                                   uint64_t value)
4367 {
4368     ARMCPU *cpu = env_archcpu(env);
4369     CPUState *cs = CPU(cpu);
4370 
4371     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4372 }
4373 
4374 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4375                                     uint64_t value)
4376 {
4377     CPUState *cs = env_cpu(env);
4378     int mask = alle1_tlbmask(env);
4379 
4380     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4381 }
4382 
4383 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4384                                     uint64_t value)
4385 {
4386     CPUState *cs = env_cpu(env);
4387     int mask = e2_tlbmask(env);
4388 
4389     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4390 }
4391 
4392 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4393                                     uint64_t value)
4394 {
4395     CPUState *cs = env_cpu(env);
4396 
4397     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4398 }
4399 
4400 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4401                                  uint64_t value)
4402 {
4403     /* Invalidate by VA, EL2
4404      * Currently handles both VAE2 and VALE2, since we don't support
4405      * flush-last-level-only.
4406      */
4407     CPUState *cs = env_cpu(env);
4408     int mask = e2_tlbmask(env);
4409     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4410 
4411     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4412 }
4413 
4414 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4415                                  uint64_t value)
4416 {
4417     /* Invalidate by VA, EL3
4418      * Currently handles both VAE3 and VALE3, since we don't support
4419      * flush-last-level-only.
4420      */
4421     ARMCPU *cpu = env_archcpu(env);
4422     CPUState *cs = CPU(cpu);
4423     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4424 
4425     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4426 }
4427 
4428 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4429                                    uint64_t value)
4430 {
4431     CPUState *cs = env_cpu(env);
4432     int mask = vae1_tlbmask(env);
4433     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4434     int bits = vae1_tlbbits(env, pageaddr);
4435 
4436     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4437 }
4438 
4439 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4440                                  uint64_t value)
4441 {
4442     /* Invalidate by VA, EL1&0 (AArch64 version).
4443      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4444      * since we don't support flush-for-specific-ASID-only or
4445      * flush-last-level-only.
4446      */
4447     CPUState *cs = env_cpu(env);
4448     int mask = vae1_tlbmask(env);
4449     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4450     int bits = vae1_tlbbits(env, pageaddr);
4451 
4452     if (tlb_force_broadcast(env)) {
4453         tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4454     } else {
4455         tlb_flush_page_bits_by_mmuidx(cs, pageaddr, mask, bits);
4456     }
4457 }
4458 
4459 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4460                                    uint64_t value)
4461 {
4462     CPUState *cs = env_cpu(env);
4463     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4464     bool secure = arm_is_secure_below_el3(env);
4465     int mask = secure ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2;
4466     int bits = tlbbits_for_regime(env, secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2,
4467                                   pageaddr);
4468 
4469     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4470 }
4471 
4472 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4473                                    uint64_t value)
4474 {
4475     CPUState *cs = env_cpu(env);
4476     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4477     int bits = tlbbits_for_regime(env, ARMMMUIdx_SE3, pageaddr);
4478 
4479     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr,
4480                                                   ARMMMUIdxBit_SE3, bits);
4481 }
4482 
4483 #ifdef TARGET_AARCH64
4484 typedef struct {
4485     uint64_t base;
4486     uint64_t length;
4487 } TLBIRange;
4488 
4489 static TLBIRange tlbi_aa64_get_range(CPUARMState *env, ARMMMUIdx mmuidx,
4490                                      uint64_t value)
4491 {
4492     unsigned int page_size_granule, page_shift, num, scale, exponent;
4493     /* Extract one bit to represent the va selector in use. */
4494     uint64_t select = sextract64(value, 36, 1);
4495     ARMVAParameters param = aa64_va_parameters(env, select, mmuidx, true);
4496     TLBIRange ret = { };
4497 
4498     page_size_granule = extract64(value, 46, 2);
4499 
4500     /* The granule encoded in value must match the granule in use. */
4501     if (page_size_granule != (param.using64k ? 3 : param.using16k ? 2 : 1)) {
4502         qemu_log_mask(LOG_GUEST_ERROR, "Invalid tlbi page size granule %d\n",
4503                       page_size_granule);
4504         return ret;
4505     }
4506 
4507     page_shift = (page_size_granule - 1) * 2 + 12;
4508     num = extract64(value, 39, 5);
4509     scale = extract64(value, 44, 2);
4510     exponent = (5 * scale) + 1;
4511 
4512     ret.length = (num + 1) << (exponent + page_shift);
4513 
4514     if (param.select) {
4515         ret.base = sextract64(value, 0, 37);
4516     } else {
4517         ret.base = extract64(value, 0, 37);
4518     }
4519     if (param.ds) {
4520         /*
4521          * With DS=1, BaseADDR is always shifted 16 so that it is able
4522          * to address all 52 va bits.  The input address is perforce
4523          * aligned on a 64k boundary regardless of translation granule.
4524          */
4525         page_shift = 16;
4526     }
4527     ret.base <<= page_shift;
4528 
4529     return ret;
4530 }
4531 
4532 static void do_rvae_write(CPUARMState *env, uint64_t value,
4533                           int idxmap, bool synced)
4534 {
4535     ARMMMUIdx one_idx = ARM_MMU_IDX_A | ctz32(idxmap);
4536     TLBIRange range;
4537     int bits;
4538 
4539     range = tlbi_aa64_get_range(env, one_idx, value);
4540     bits = tlbbits_for_regime(env, one_idx, range.base);
4541 
4542     if (synced) {
4543         tlb_flush_range_by_mmuidx_all_cpus_synced(env_cpu(env),
4544                                                   range.base,
4545                                                   range.length,
4546                                                   idxmap,
4547                                                   bits);
4548     } else {
4549         tlb_flush_range_by_mmuidx(env_cpu(env), range.base,
4550                                   range.length, idxmap, bits);
4551     }
4552 }
4553 
4554 static void tlbi_aa64_rvae1_write(CPUARMState *env,
4555                                   const ARMCPRegInfo *ri,
4556                                   uint64_t value)
4557 {
4558     /*
4559      * Invalidate by VA range, EL1&0.
4560      * Currently handles all of RVAE1, RVAAE1, RVAALE1 and RVALE1,
4561      * since we don't support flush-for-specific-ASID-only or
4562      * flush-last-level-only.
4563      */
4564 
4565     do_rvae_write(env, value, vae1_tlbmask(env),
4566                   tlb_force_broadcast(env));
4567 }
4568 
4569 static void tlbi_aa64_rvae1is_write(CPUARMState *env,
4570                                     const ARMCPRegInfo *ri,
4571                                     uint64_t value)
4572 {
4573     /*
4574      * Invalidate by VA range, Inner/Outer Shareable EL1&0.
4575      * Currently handles all of RVAE1IS, RVAE1OS, RVAAE1IS, RVAAE1OS,
4576      * RVAALE1IS, RVAALE1OS, RVALE1IS and RVALE1OS, since we don't support
4577      * flush-for-specific-ASID-only, flush-last-level-only or inner/outer
4578      * shareable specific flushes.
4579      */
4580 
4581     do_rvae_write(env, value, vae1_tlbmask(env), true);
4582 }
4583 
4584 static int vae2_tlbmask(CPUARMState *env)
4585 {
4586     return (arm_is_secure_below_el3(env)
4587             ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2);
4588 }
4589 
4590 static void tlbi_aa64_rvae2_write(CPUARMState *env,
4591                                   const ARMCPRegInfo *ri,
4592                                   uint64_t value)
4593 {
4594     /*
4595      * Invalidate by VA range, EL2.
4596      * Currently handles all of RVAE2 and RVALE2,
4597      * since we don't support flush-for-specific-ASID-only or
4598      * flush-last-level-only.
4599      */
4600 
4601     do_rvae_write(env, value, vae2_tlbmask(env),
4602                   tlb_force_broadcast(env));
4603 
4604 
4605 }
4606 
4607 static void tlbi_aa64_rvae2is_write(CPUARMState *env,
4608                                     const ARMCPRegInfo *ri,
4609                                     uint64_t value)
4610 {
4611     /*
4612      * Invalidate by VA range, Inner/Outer Shareable, EL2.
4613      * Currently handles all of RVAE2IS, RVAE2OS, RVALE2IS and RVALE2OS,
4614      * since we don't support flush-for-specific-ASID-only,
4615      * flush-last-level-only or inner/outer shareable specific flushes.
4616      */
4617 
4618     do_rvae_write(env, value, vae2_tlbmask(env), true);
4619 
4620 }
4621 
4622 static void tlbi_aa64_rvae3_write(CPUARMState *env,
4623                                   const ARMCPRegInfo *ri,
4624                                   uint64_t value)
4625 {
4626     /*
4627      * Invalidate by VA range, EL3.
4628      * Currently handles all of RVAE3 and RVALE3,
4629      * since we don't support flush-for-specific-ASID-only or
4630      * flush-last-level-only.
4631      */
4632 
4633     do_rvae_write(env, value, ARMMMUIdxBit_SE3,
4634                   tlb_force_broadcast(env));
4635 }
4636 
4637 static void tlbi_aa64_rvae3is_write(CPUARMState *env,
4638                                     const ARMCPRegInfo *ri,
4639                                     uint64_t value)
4640 {
4641     /*
4642      * Invalidate by VA range, EL3, Inner/Outer Shareable.
4643      * Currently handles all of RVAE3IS, RVAE3OS, RVALE3IS and RVALE3OS,
4644      * since we don't support flush-for-specific-ASID-only,
4645      * flush-last-level-only or inner/outer specific flushes.
4646      */
4647 
4648     do_rvae_write(env, value, ARMMMUIdxBit_SE3, true);
4649 }
4650 #endif
4651 
4652 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4653                                       bool isread)
4654 {
4655     int cur_el = arm_current_el(env);
4656 
4657     if (cur_el < 2) {
4658         uint64_t hcr = arm_hcr_el2_eff(env);
4659 
4660         if (cur_el == 0) {
4661             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4662                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4663                     return CP_ACCESS_TRAP_EL2;
4664                 }
4665             } else {
4666                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4667                     return CP_ACCESS_TRAP;
4668                 }
4669                 if (hcr & HCR_TDZ) {
4670                     return CP_ACCESS_TRAP_EL2;
4671                 }
4672             }
4673         } else if (hcr & HCR_TDZ) {
4674             return CP_ACCESS_TRAP_EL2;
4675         }
4676     }
4677     return CP_ACCESS_OK;
4678 }
4679 
4680 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4681 {
4682     ARMCPU *cpu = env_archcpu(env);
4683     int dzp_bit = 1 << 4;
4684 
4685     /* DZP indicates whether DC ZVA access is allowed */
4686     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4687         dzp_bit = 0;
4688     }
4689     return cpu->dcz_blocksize | dzp_bit;
4690 }
4691 
4692 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4693                                     bool isread)
4694 {
4695     if (!(env->pstate & PSTATE_SP)) {
4696         /* Access to SP_EL0 is undefined if it's being used as
4697          * the stack pointer.
4698          */
4699         return CP_ACCESS_TRAP_UNCATEGORIZED;
4700     }
4701     return CP_ACCESS_OK;
4702 }
4703 
4704 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4705 {
4706     return env->pstate & PSTATE_SP;
4707 }
4708 
4709 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4710 {
4711     update_spsel(env, val);
4712 }
4713 
4714 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4715                         uint64_t value)
4716 {
4717     ARMCPU *cpu = env_archcpu(env);
4718 
4719     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4720         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4721         value &= ~SCTLR_M;
4722     }
4723 
4724     /* ??? Lots of these bits are not implemented.  */
4725 
4726     if (ri->state == ARM_CP_STATE_AA64 && !cpu_isar_feature(aa64_mte, cpu)) {
4727         if (ri->opc1 == 6) { /* SCTLR_EL3 */
4728             value &= ~(SCTLR_ITFSB | SCTLR_TCF | SCTLR_ATA);
4729         } else {
4730             value &= ~(SCTLR_ITFSB | SCTLR_TCF0 | SCTLR_TCF |
4731                        SCTLR_ATA0 | SCTLR_ATA);
4732         }
4733     }
4734 
4735     if (raw_read(env, ri) == value) {
4736         /* Skip the TLB flush if nothing actually changed; Linux likes
4737          * to do a lot of pointless SCTLR writes.
4738          */
4739         return;
4740     }
4741 
4742     raw_write(env, ri, value);
4743 
4744     /* This may enable/disable the MMU, so do a TLB flush.  */
4745     tlb_flush(CPU(cpu));
4746 
4747     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4748         /*
4749          * Normally we would always end the TB on an SCTLR write; see the
4750          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4751          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4752          * of hflags from the translator, so do it here.
4753          */
4754         arm_rebuild_hflags(env);
4755     }
4756 }
4757 
4758 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4759                        uint64_t value)
4760 {
4761     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4762 }
4763 
4764 static const ARMCPRegInfo v8_cp_reginfo[] = {
4765     /* Minimal set of EL0-visible registers. This will need to be expanded
4766      * significantly for system emulation of AArch64 CPUs.
4767      */
4768     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4769       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4770       .access = PL0_RW, .type = ARM_CP_NZCV },
4771     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4772       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4773       .type = ARM_CP_NO_RAW,
4774       .access = PL0_RW, .accessfn = aa64_daif_access,
4775       .fieldoffset = offsetof(CPUARMState, daif),
4776       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4777     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4778       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4779       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4780       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4781     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4782       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4783       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4784       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4785     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4786       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4787       .access = PL0_R, .type = ARM_CP_NO_RAW,
4788       .readfn = aa64_dczid_read },
4789     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4790       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4791       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4792 #ifndef CONFIG_USER_ONLY
4793       /* Avoid overhead of an access check that always passes in user-mode */
4794       .accessfn = aa64_zva_access,
4795 #endif
4796     },
4797     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4798       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4799       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4800     /* Cache ops: all NOPs since we don't emulate caches */
4801     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4802       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4803       .access = PL1_W, .type = ARM_CP_NOP,
4804       .accessfn = aa64_cacheop_pou_access },
4805     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4806       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4807       .access = PL1_W, .type = ARM_CP_NOP,
4808       .accessfn = aa64_cacheop_pou_access },
4809     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4810       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4811       .access = PL0_W, .type = ARM_CP_NOP,
4812       .accessfn = aa64_cacheop_pou_access },
4813     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4814       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4815       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4816       .type = ARM_CP_NOP },
4817     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4818       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4819       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4820     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4821       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4822       .access = PL0_W, .type = ARM_CP_NOP,
4823       .accessfn = aa64_cacheop_poc_access },
4824     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4825       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4826       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4827     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4828       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4829       .access = PL0_W, .type = ARM_CP_NOP,
4830       .accessfn = aa64_cacheop_pou_access },
4831     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4832       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4833       .access = PL0_W, .type = ARM_CP_NOP,
4834       .accessfn = aa64_cacheop_poc_access },
4835     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4836       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4837       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4838     /* TLBI operations */
4839     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4840       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4841       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4842       .writefn = tlbi_aa64_vmalle1is_write },
4843     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4844       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4845       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4846       .writefn = tlbi_aa64_vae1is_write },
4847     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4848       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4849       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4850       .writefn = tlbi_aa64_vmalle1is_write },
4851     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4852       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4853       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4854       .writefn = tlbi_aa64_vae1is_write },
4855     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4856       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4857       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4858       .writefn = tlbi_aa64_vae1is_write },
4859     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4860       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4861       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4862       .writefn = tlbi_aa64_vae1is_write },
4863     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4864       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4865       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4866       .writefn = tlbi_aa64_vmalle1_write },
4867     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4868       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4869       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4870       .writefn = tlbi_aa64_vae1_write },
4871     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4872       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4873       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4874       .writefn = tlbi_aa64_vmalle1_write },
4875     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4876       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4877       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4878       .writefn = tlbi_aa64_vae1_write },
4879     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4880       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4881       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4882       .writefn = tlbi_aa64_vae1_write },
4883     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4884       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4885       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4886       .writefn = tlbi_aa64_vae1_write },
4887     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4888       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4889       .access = PL2_W, .type = ARM_CP_NOP },
4890     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4891       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4892       .access = PL2_W, .type = ARM_CP_NOP },
4893     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4894       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4895       .access = PL2_W, .type = ARM_CP_NO_RAW,
4896       .writefn = tlbi_aa64_alle1is_write },
4897     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4898       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4899       .access = PL2_W, .type = ARM_CP_NO_RAW,
4900       .writefn = tlbi_aa64_alle1is_write },
4901     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4902       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4903       .access = PL2_W, .type = ARM_CP_NOP },
4904     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4905       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4906       .access = PL2_W, .type = ARM_CP_NOP },
4907     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4908       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4909       .access = PL2_W, .type = ARM_CP_NO_RAW,
4910       .writefn = tlbi_aa64_alle1_write },
4911     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4912       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4913       .access = PL2_W, .type = ARM_CP_NO_RAW,
4914       .writefn = tlbi_aa64_alle1is_write },
4915 #ifndef CONFIG_USER_ONLY
4916     /* 64 bit address translation operations */
4917     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4918       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4919       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4920       .writefn = ats_write64 },
4921     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4922       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4923       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4924       .writefn = ats_write64 },
4925     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4926       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4927       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4928       .writefn = ats_write64 },
4929     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4930       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4931       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4932       .writefn = ats_write64 },
4933     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4934       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4935       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4936       .writefn = ats_write64 },
4937     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4938       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4939       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4940       .writefn = ats_write64 },
4941     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4942       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4943       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4944       .writefn = ats_write64 },
4945     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4946       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4947       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4948       .writefn = ats_write64 },
4949     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4950     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4951       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4952       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4953       .writefn = ats_write64 },
4954     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4955       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4956       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4957       .writefn = ats_write64 },
4958     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4959       .type = ARM_CP_ALIAS,
4960       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4961       .access = PL1_RW, .resetvalue = 0,
4962       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4963       .writefn = par_write },
4964 #endif
4965     /* TLB invalidate last level of translation table walk */
4966     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4967       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4968       .writefn = tlbimva_is_write },
4969     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4970       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4971       .writefn = tlbimvaa_is_write },
4972     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4973       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4974       .writefn = tlbimva_write },
4975     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4976       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4977       .writefn = tlbimvaa_write },
4978     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4979       .type = ARM_CP_NO_RAW, .access = PL2_W,
4980       .writefn = tlbimva_hyp_write },
4981     { .name = "TLBIMVALHIS",
4982       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4983       .type = ARM_CP_NO_RAW, .access = PL2_W,
4984       .writefn = tlbimva_hyp_is_write },
4985     { .name = "TLBIIPAS2",
4986       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4987       .type = ARM_CP_NOP, .access = PL2_W },
4988     { .name = "TLBIIPAS2IS",
4989       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4990       .type = ARM_CP_NOP, .access = PL2_W },
4991     { .name = "TLBIIPAS2L",
4992       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4993       .type = ARM_CP_NOP, .access = PL2_W },
4994     { .name = "TLBIIPAS2LIS",
4995       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4996       .type = ARM_CP_NOP, .access = PL2_W },
4997     /* 32 bit cache operations */
4998     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4999       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5000     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5001       .type = ARM_CP_NOP, .access = PL1_W },
5002     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5003       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5004     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5005       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5006     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5007       .type = ARM_CP_NOP, .access = PL1_W },
5008     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5009       .type = ARM_CP_NOP, .access = PL1_W },
5010     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5011       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5012     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5013       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5014     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5015       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5016     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5017       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5018     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5019       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5020     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5021       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5022     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5023       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5024     /* MMU Domain access control / MPU write buffer control */
5025     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5026       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5027       .writefn = dacr_write, .raw_writefn = raw_write,
5028       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5029                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5030     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5031       .type = ARM_CP_ALIAS,
5032       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5033       .access = PL1_RW,
5034       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5035     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5036       .type = ARM_CP_ALIAS,
5037       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5038       .access = PL1_RW,
5039       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5040     /* We rely on the access checks not allowing the guest to write to the
5041      * state field when SPSel indicates that it's being used as the stack
5042      * pointer.
5043      */
5044     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5045       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5046       .access = PL1_RW, .accessfn = sp_el0_access,
5047       .type = ARM_CP_ALIAS,
5048       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5049     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5050       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5051       .access = PL2_RW, .type = ARM_CP_ALIAS,
5052       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5053     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5054       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5055       .type = ARM_CP_NO_RAW,
5056       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5057     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5058       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5059       .access = PL2_RW,
5060       .type = ARM_CP_ALIAS | ARM_CP_FPU | ARM_CP_EL3_NO_EL2_KEEP,
5061       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]) },
5062     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5063       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5064       .access = PL2_RW, .resetvalue = 0, .type = ARM_CP_EL3_NO_EL2_KEEP,
5065       .writefn = dacr_write, .raw_writefn = raw_write,
5066       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5067     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5068       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5069       .access = PL2_RW, .resetvalue = 0, .type = ARM_CP_EL3_NO_EL2_KEEP,
5070       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5071     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5072       .type = ARM_CP_ALIAS,
5073       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5074       .access = PL2_RW,
5075       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5076     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5077       .type = ARM_CP_ALIAS,
5078       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5079       .access = PL2_RW,
5080       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5081     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5082       .type = ARM_CP_ALIAS,
5083       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5084       .access = PL2_RW,
5085       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5086     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5087       .type = ARM_CP_ALIAS,
5088       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5089       .access = PL2_RW,
5090       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5091     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5092       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5093       .resetvalue = 0,
5094       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5095     { .name = "SDCR", .type = ARM_CP_ALIAS,
5096       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5097       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5098       .writefn = sdcr_write,
5099       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5100 };
5101 
5102 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5103 {
5104     ARMCPU *cpu = env_archcpu(env);
5105 
5106     if (arm_feature(env, ARM_FEATURE_V8)) {
5107         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5108     } else {
5109         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5110     }
5111 
5112     if (arm_feature(env, ARM_FEATURE_EL3)) {
5113         valid_mask &= ~HCR_HCD;
5114     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5115         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5116          * However, if we're using the SMC PSCI conduit then QEMU is
5117          * effectively acting like EL3 firmware and so the guest at
5118          * EL2 should retain the ability to prevent EL1 from being
5119          * able to make SMC calls into the ersatz firmware, so in
5120          * that case HCR.TSC should be read/write.
5121          */
5122         valid_mask &= ~HCR_TSC;
5123     }
5124 
5125     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5126         if (cpu_isar_feature(aa64_vh, cpu)) {
5127             valid_mask |= HCR_E2H;
5128         }
5129         if (cpu_isar_feature(aa64_lor, cpu)) {
5130             valid_mask |= HCR_TLOR;
5131         }
5132         if (cpu_isar_feature(aa64_pauth, cpu)) {
5133             valid_mask |= HCR_API | HCR_APK;
5134         }
5135         if (cpu_isar_feature(aa64_mte, cpu)) {
5136             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5137         }
5138     }
5139 
5140     /* Clear RES0 bits.  */
5141     value &= valid_mask;
5142 
5143     /*
5144      * These bits change the MMU setup:
5145      * HCR_VM enables stage 2 translation
5146      * HCR_PTW forbids certain page-table setups
5147      * HCR_DC disables stage1 and enables stage2 translation
5148      * HCR_DCT enables tagging on (disabled) stage1 translation
5149      */
5150     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT)) {
5151         tlb_flush(CPU(cpu));
5152     }
5153     env->cp15.hcr_el2 = value;
5154 
5155     /*
5156      * Updates to VI and VF require us to update the status of
5157      * virtual interrupts, which are the logical OR of these bits
5158      * and the state of the input lines from the GIC. (This requires
5159      * that we have the iothread lock, which is done by marking the
5160      * reginfo structs as ARM_CP_IO.)
5161      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5162      * possible for it to be taken immediately, because VIRQ and
5163      * VFIQ are masked unless running at EL0 or EL1, and HCR
5164      * can only be written at EL2.
5165      */
5166     g_assert(qemu_mutex_iothread_locked());
5167     arm_cpu_update_virq(cpu);
5168     arm_cpu_update_vfiq(cpu);
5169 }
5170 
5171 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5172 {
5173     do_hcr_write(env, value, 0);
5174 }
5175 
5176 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5177                           uint64_t value)
5178 {
5179     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5180     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5181     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5182 }
5183 
5184 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5185                          uint64_t value)
5186 {
5187     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5188     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5189     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5190 }
5191 
5192 /*
5193  * Return the effective value of HCR_EL2.
5194  * Bits that are not included here:
5195  * RW       (read from SCR_EL3.RW as needed)
5196  */
5197 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5198 {
5199     uint64_t ret = env->cp15.hcr_el2;
5200 
5201     if (!arm_is_el2_enabled(env)) {
5202         /*
5203          * "This register has no effect if EL2 is not enabled in the
5204          * current Security state".  This is ARMv8.4-SecEL2 speak for
5205          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5206          *
5207          * Prior to that, the language was "In an implementation that
5208          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5209          * as if this field is 0 for all purposes other than a direct
5210          * read or write access of HCR_EL2".  With lots of enumeration
5211          * on a per-field basis.  In current QEMU, this is condition
5212          * is arm_is_secure_below_el3.
5213          *
5214          * Since the v8.4 language applies to the entire register, and
5215          * appears to be backward compatible, use that.
5216          */
5217         return 0;
5218     }
5219 
5220     /*
5221      * For a cpu that supports both aarch64 and aarch32, we can set bits
5222      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5223      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5224      */
5225     if (!arm_el_is_aa64(env, 2)) {
5226         uint64_t aa32_valid;
5227 
5228         /*
5229          * These bits are up-to-date as of ARMv8.6.
5230          * For HCR, it's easiest to list just the 2 bits that are invalid.
5231          * For HCR2, list those that are valid.
5232          */
5233         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5234         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5235                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5236         ret &= aa32_valid;
5237     }
5238 
5239     if (ret & HCR_TGE) {
5240         /* These bits are up-to-date as of ARMv8.6.  */
5241         if (ret & HCR_E2H) {
5242             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5243                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5244                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5245                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5246                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5247                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5248         } else {
5249             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5250         }
5251         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5252                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5253                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5254                  HCR_TLOR);
5255     }
5256 
5257     return ret;
5258 }
5259 
5260 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5261                            uint64_t value)
5262 {
5263     /*
5264      * For A-profile AArch32 EL3, if NSACR.CP10
5265      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5266      */
5267     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5268         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5269         value &= ~(0x3 << 10);
5270         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5271     }
5272     env->cp15.cptr_el[2] = value;
5273 }
5274 
5275 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5276 {
5277     /*
5278      * For A-profile AArch32 EL3, if NSACR.CP10
5279      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5280      */
5281     uint64_t value = env->cp15.cptr_el[2];
5282 
5283     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5284         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5285         value |= 0x3 << 10;
5286     }
5287     return value;
5288 }
5289 
5290 static const ARMCPRegInfo el2_cp_reginfo[] = {
5291     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5292       .type = ARM_CP_IO,
5293       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5294       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5295       .writefn = hcr_write },
5296     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5297       .type = ARM_CP_ALIAS | ARM_CP_IO,
5298       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5299       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5300       .writefn = hcr_writelow },
5301     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5302       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5303       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5304     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5305       .type = ARM_CP_ALIAS,
5306       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5307       .access = PL2_RW,
5308       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5309     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5310       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5311       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5312     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5313       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5314       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5315     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5316       .type = ARM_CP_ALIAS,
5317       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5318       .access = PL2_RW,
5319       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5320     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5321       .type = ARM_CP_ALIAS,
5322       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5323       .access = PL2_RW,
5324       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5325     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5326       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5327       .access = PL2_RW, .writefn = vbar_write,
5328       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5329       .resetvalue = 0 },
5330     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5331       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5332       .access = PL3_RW, .type = ARM_CP_ALIAS,
5333       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5334     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5335       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5336       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5337       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5338       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5339     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5340       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5341       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5342       .resetvalue = 0 },
5343     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5344       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5345       .access = PL2_RW, .type = ARM_CP_ALIAS,
5346       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5347     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5348       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5349       .access = PL2_RW, .type = ARM_CP_CONST,
5350       .resetvalue = 0 },
5351     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5352     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5353       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5354       .access = PL2_RW, .type = ARM_CP_CONST,
5355       .resetvalue = 0 },
5356     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5357       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5358       .access = PL2_RW, .type = ARM_CP_CONST,
5359       .resetvalue = 0 },
5360     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5361       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5362       .access = PL2_RW, .type = ARM_CP_CONST,
5363       .resetvalue = 0 },
5364     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5365       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5366       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5367       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5368       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5369     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5370       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5371       .type = ARM_CP_ALIAS,
5372       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5373       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5374     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5375       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5376       .access = PL2_RW,
5377       /* no .writefn needed as this can't cause an ASID change;
5378        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5379        */
5380       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5381     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5382       .cp = 15, .opc1 = 6, .crm = 2,
5383       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5384       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5385       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5386       .writefn = vttbr_write },
5387     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5388       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5389       .access = PL2_RW, .writefn = vttbr_write,
5390       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5391     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5392       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5393       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5394       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5395     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5396       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5397       .access = PL2_RW, .resetvalue = 0,
5398       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5399     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5400       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5401       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5402       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5403     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5404       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5405       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5406     { .name = "TLBIALLNSNH",
5407       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5408       .type = ARM_CP_NO_RAW, .access = PL2_W,
5409       .writefn = tlbiall_nsnh_write },
5410     { .name = "TLBIALLNSNHIS",
5411       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5412       .type = ARM_CP_NO_RAW, .access = PL2_W,
5413       .writefn = tlbiall_nsnh_is_write },
5414     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5415       .type = ARM_CP_NO_RAW, .access = PL2_W,
5416       .writefn = tlbiall_hyp_write },
5417     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5418       .type = ARM_CP_NO_RAW, .access = PL2_W,
5419       .writefn = tlbiall_hyp_is_write },
5420     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5421       .type = ARM_CP_NO_RAW, .access = PL2_W,
5422       .writefn = tlbimva_hyp_write },
5423     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5424       .type = ARM_CP_NO_RAW, .access = PL2_W,
5425       .writefn = tlbimva_hyp_is_write },
5426     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5427       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5428       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5429       .writefn = tlbi_aa64_alle2_write },
5430     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5431       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5432       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5433       .writefn = tlbi_aa64_vae2_write },
5434     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5435       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5436       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5437       .writefn = tlbi_aa64_vae2_write },
5438     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5439       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5440       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5441       .writefn = tlbi_aa64_alle2is_write },
5442     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5443       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5444       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5445       .writefn = tlbi_aa64_vae2is_write },
5446     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5447       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5448       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5449       .writefn = tlbi_aa64_vae2is_write },
5450 #ifndef CONFIG_USER_ONLY
5451     /* Unlike the other EL2-related AT operations, these must
5452      * UNDEF from EL3 if EL2 is not implemented, which is why we
5453      * define them here rather than with the rest of the AT ops.
5454      */
5455     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5456       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5457       .access = PL2_W, .accessfn = at_s1e2_access,
5458       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC | ARM_CP_EL3_NO_EL2_UNDEF,
5459       .writefn = ats_write64 },
5460     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5461       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5462       .access = PL2_W, .accessfn = at_s1e2_access,
5463       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC | ARM_CP_EL3_NO_EL2_UNDEF,
5464       .writefn = ats_write64 },
5465     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5466      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5467      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5468      * to behave as if SCR.NS was 1.
5469      */
5470     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5471       .access = PL2_W,
5472       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5473     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5474       .access = PL2_W,
5475       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5476     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5477       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5478       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5479        * reset values as IMPDEF. We choose to reset to 3 to comply with
5480        * both ARMv7 and ARMv8.
5481        */
5482       .access = PL2_RW, .resetvalue = 3,
5483       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5484     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5485       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5486       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5487       .writefn = gt_cntvoff_write,
5488       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5489     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5490       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5491       .writefn = gt_cntvoff_write,
5492       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5493     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5494       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5495       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5496       .type = ARM_CP_IO, .access = PL2_RW,
5497       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5498     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5499       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5500       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5501       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5502     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5503       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5504       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5505       .resetfn = gt_hyp_timer_reset,
5506       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5507     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5508       .type = ARM_CP_IO,
5509       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5510       .access = PL2_RW,
5511       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5512       .resetvalue = 0,
5513       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5514 #endif
5515     /* The only field of MDCR_EL2 that has a defined architectural reset value
5516      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N.
5517      */
5518     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5519       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5520       .access = PL2_RW, .resetvalue = PMCR_NUM_COUNTERS,
5521       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5522     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5523       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5524       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5525       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5526     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5527       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5528       .access = PL2_RW,
5529       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5530     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5531       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5532       .access = PL2_RW,
5533       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5534 };
5535 
5536 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5537     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5538       .type = ARM_CP_ALIAS | ARM_CP_IO,
5539       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5540       .access = PL2_RW,
5541       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5542       .writefn = hcr_writehigh },
5543 };
5544 
5545 static CPAccessResult sel2_access(CPUARMState *env, const ARMCPRegInfo *ri,
5546                                   bool isread)
5547 {
5548     if (arm_current_el(env) == 3 || arm_is_secure_below_el3(env)) {
5549         return CP_ACCESS_OK;
5550     }
5551     return CP_ACCESS_TRAP_UNCATEGORIZED;
5552 }
5553 
5554 static const ARMCPRegInfo el2_sec_cp_reginfo[] = {
5555     { .name = "VSTTBR_EL2", .state = ARM_CP_STATE_AA64,
5556       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 0,
5557       .access = PL2_RW, .accessfn = sel2_access,
5558       .fieldoffset = offsetof(CPUARMState, cp15.vsttbr_el2) },
5559     { .name = "VSTCR_EL2", .state = ARM_CP_STATE_AA64,
5560       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 2,
5561       .access = PL2_RW, .accessfn = sel2_access,
5562       .fieldoffset = offsetof(CPUARMState, cp15.vstcr_el2) },
5563 };
5564 
5565 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5566                                    bool isread)
5567 {
5568     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5569      * At Secure EL1 it traps to EL3 or EL2.
5570      */
5571     if (arm_current_el(env) == 3) {
5572         return CP_ACCESS_OK;
5573     }
5574     if (arm_is_secure_below_el3(env)) {
5575         if (env->cp15.scr_el3 & SCR_EEL2) {
5576             return CP_ACCESS_TRAP_EL2;
5577         }
5578         return CP_ACCESS_TRAP_EL3;
5579     }
5580     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5581     if (isread) {
5582         return CP_ACCESS_OK;
5583     }
5584     return CP_ACCESS_TRAP_UNCATEGORIZED;
5585 }
5586 
5587 static const ARMCPRegInfo el3_cp_reginfo[] = {
5588     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5589       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5590       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5591       .resetfn = scr_reset, .writefn = scr_write },
5592     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5593       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5594       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5595       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5596       .writefn = scr_write },
5597     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5598       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5599       .access = PL3_RW, .resetvalue = 0,
5600       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5601     { .name = "SDER",
5602       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5603       .access = PL3_RW, .resetvalue = 0,
5604       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5605     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5606       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5607       .writefn = vbar_write, .resetvalue = 0,
5608       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5609     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5610       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5611       .access = PL3_RW, .resetvalue = 0,
5612       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5613     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5614       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5615       .access = PL3_RW,
5616       /* no .writefn needed as this can't cause an ASID change;
5617        * we must provide a .raw_writefn and .resetfn because we handle
5618        * reset and migration for the AArch32 TTBCR(S), which might be
5619        * using mask and base_mask.
5620        */
5621       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5622       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5623     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5624       .type = ARM_CP_ALIAS,
5625       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5626       .access = PL3_RW,
5627       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5628     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5629       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5630       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5631     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5632       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5633       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5634     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5635       .type = ARM_CP_ALIAS,
5636       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5637       .access = PL3_RW,
5638       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5639     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5640       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5641       .access = PL3_RW, .writefn = vbar_write,
5642       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5643       .resetvalue = 0 },
5644     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5645       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5646       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5647       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5648     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5649       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5650       .access = PL3_RW, .resetvalue = 0,
5651       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5652     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5653       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5654       .access = PL3_RW, .type = ARM_CP_CONST,
5655       .resetvalue = 0 },
5656     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5657       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5658       .access = PL3_RW, .type = ARM_CP_CONST,
5659       .resetvalue = 0 },
5660     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5661       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5662       .access = PL3_RW, .type = ARM_CP_CONST,
5663       .resetvalue = 0 },
5664     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5665       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5666       .access = PL3_W, .type = ARM_CP_NO_RAW,
5667       .writefn = tlbi_aa64_alle3is_write },
5668     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5669       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5670       .access = PL3_W, .type = ARM_CP_NO_RAW,
5671       .writefn = tlbi_aa64_vae3is_write },
5672     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5673       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5674       .access = PL3_W, .type = ARM_CP_NO_RAW,
5675       .writefn = tlbi_aa64_vae3is_write },
5676     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5677       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5678       .access = PL3_W, .type = ARM_CP_NO_RAW,
5679       .writefn = tlbi_aa64_alle3_write },
5680     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5681       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5682       .access = PL3_W, .type = ARM_CP_NO_RAW,
5683       .writefn = tlbi_aa64_vae3_write },
5684     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5685       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5686       .access = PL3_W, .type = ARM_CP_NO_RAW,
5687       .writefn = tlbi_aa64_vae3_write },
5688 };
5689 
5690 #ifndef CONFIG_USER_ONLY
5691 /* Test if system register redirection is to occur in the current state.  */
5692 static bool redirect_for_e2h(CPUARMState *env)
5693 {
5694     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5695 }
5696 
5697 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5698 {
5699     CPReadFn *readfn;
5700 
5701     if (redirect_for_e2h(env)) {
5702         /* Switch to the saved EL2 version of the register.  */
5703         ri = ri->opaque;
5704         readfn = ri->readfn;
5705     } else {
5706         readfn = ri->orig_readfn;
5707     }
5708     if (readfn == NULL) {
5709         readfn = raw_read;
5710     }
5711     return readfn(env, ri);
5712 }
5713 
5714 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5715                           uint64_t value)
5716 {
5717     CPWriteFn *writefn;
5718 
5719     if (redirect_for_e2h(env)) {
5720         /* Switch to the saved EL2 version of the register.  */
5721         ri = ri->opaque;
5722         writefn = ri->writefn;
5723     } else {
5724         writefn = ri->orig_writefn;
5725     }
5726     if (writefn == NULL) {
5727         writefn = raw_write;
5728     }
5729     writefn(env, ri, value);
5730 }
5731 
5732 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5733 {
5734     struct E2HAlias {
5735         uint32_t src_key, dst_key, new_key;
5736         const char *src_name, *dst_name, *new_name;
5737         bool (*feature)(const ARMISARegisters *id);
5738     };
5739 
5740 #define K(op0, op1, crn, crm, op2) \
5741     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5742 
5743     static const struct E2HAlias aliases[] = {
5744         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5745           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5746         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5747           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5748         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5749           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5750         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5751           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5752         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5753           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5754         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5755           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5756         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5757           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5758         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5759           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5760         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5761           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5762         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5763           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5764         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5765           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5766         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5767           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5768         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5769           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5770         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5771           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5772         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5773           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5774         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5775           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5776 
5777         /*
5778          * Note that redirection of ZCR is mentioned in the description
5779          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5780          * not in the summary table.
5781          */
5782         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5783           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5784 
5785         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
5786           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
5787 
5788         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5789         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5790     };
5791 #undef K
5792 
5793     size_t i;
5794 
5795     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5796         const struct E2HAlias *a = &aliases[i];
5797         ARMCPRegInfo *src_reg, *dst_reg, *new_reg;
5798         bool ok;
5799 
5800         if (a->feature && !a->feature(&cpu->isar)) {
5801             continue;
5802         }
5803 
5804         src_reg = g_hash_table_lookup(cpu->cp_regs,
5805                                       (gpointer)(uintptr_t)a->src_key);
5806         dst_reg = g_hash_table_lookup(cpu->cp_regs,
5807                                       (gpointer)(uintptr_t)a->dst_key);
5808         g_assert(src_reg != NULL);
5809         g_assert(dst_reg != NULL);
5810 
5811         /* Cross-compare names to detect typos in the keys.  */
5812         g_assert(strcmp(src_reg->name, a->src_name) == 0);
5813         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
5814 
5815         /* None of the core system registers use opaque; we will.  */
5816         g_assert(src_reg->opaque == NULL);
5817 
5818         /* Create alias before redirection so we dup the right data. */
5819         new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
5820 
5821         new_reg->name = a->new_name;
5822         new_reg->type |= ARM_CP_ALIAS;
5823         /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
5824         new_reg->access &= PL2_RW | PL3_RW;
5825 
5826         ok = g_hash_table_insert(cpu->cp_regs,
5827                                  (gpointer)(uintptr_t)a->new_key, new_reg);
5828         g_assert(ok);
5829 
5830         src_reg->opaque = dst_reg;
5831         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
5832         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
5833         if (!src_reg->raw_readfn) {
5834             src_reg->raw_readfn = raw_read;
5835         }
5836         if (!src_reg->raw_writefn) {
5837             src_reg->raw_writefn = raw_write;
5838         }
5839         src_reg->readfn = el2_e2h_read;
5840         src_reg->writefn = el2_e2h_write;
5841     }
5842 }
5843 #endif
5844 
5845 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5846                                      bool isread)
5847 {
5848     int cur_el = arm_current_el(env);
5849 
5850     if (cur_el < 2) {
5851         uint64_t hcr = arm_hcr_el2_eff(env);
5852 
5853         if (cur_el == 0) {
5854             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
5855                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
5856                     return CP_ACCESS_TRAP_EL2;
5857                 }
5858             } else {
5859                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5860                     return CP_ACCESS_TRAP;
5861                 }
5862                 if (hcr & HCR_TID2) {
5863                     return CP_ACCESS_TRAP_EL2;
5864                 }
5865             }
5866         } else if (hcr & HCR_TID2) {
5867             return CP_ACCESS_TRAP_EL2;
5868         }
5869     }
5870 
5871     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
5872         return CP_ACCESS_TRAP_EL2;
5873     }
5874 
5875     return CP_ACCESS_OK;
5876 }
5877 
5878 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5879                         uint64_t value)
5880 {
5881     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5882      * read via a bit in OSLSR_EL1.
5883      */
5884     int oslock;
5885 
5886     if (ri->state == ARM_CP_STATE_AA32) {
5887         oslock = (value == 0xC5ACCE55);
5888     } else {
5889         oslock = value & 1;
5890     }
5891 
5892     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5893 }
5894 
5895 static const ARMCPRegInfo debug_cp_reginfo[] = {
5896     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5897      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5898      * unlike DBGDRAR it is never accessible from EL0.
5899      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5900      * accessor.
5901      */
5902     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5903       .access = PL0_R, .accessfn = access_tdra,
5904       .type = ARM_CP_CONST, .resetvalue = 0 },
5905     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5906       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5907       .access = PL1_R, .accessfn = access_tdra,
5908       .type = ARM_CP_CONST, .resetvalue = 0 },
5909     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5910       .access = PL0_R, .accessfn = access_tdra,
5911       .type = ARM_CP_CONST, .resetvalue = 0 },
5912     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5913     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5914       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5915       .access = PL1_RW, .accessfn = access_tda,
5916       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5917       .resetvalue = 0 },
5918     /*
5919      * MDCCSR_EL0[30:29] map to EDSCR[30:29].  Simply RAZ as the external
5920      * Debug Communication Channel is not implemented.
5921      */
5922     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_AA64,
5923       .opc0 = 2, .opc1 = 3, .crn = 0, .crm = 1, .opc2 = 0,
5924       .access = PL0_R, .accessfn = access_tda,
5925       .type = ARM_CP_CONST, .resetvalue = 0 },
5926     /*
5927      * DBGDSCRint[15,12,5:2] map to MDSCR_EL1[15,12,5:2].  Map all bits as
5928      * it is unlikely a guest will care.
5929      * We don't implement the configurable EL0 access.
5930      */
5931     { .name = "DBGDSCRint", .state = ARM_CP_STATE_AA32,
5932       .cp = 14, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5933       .type = ARM_CP_ALIAS,
5934       .access = PL1_R, .accessfn = access_tda,
5935       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
5936     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
5937       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
5938       .access = PL1_W, .type = ARM_CP_NO_RAW,
5939       .accessfn = access_tdosa,
5940       .writefn = oslar_write },
5941     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
5942       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
5943       .access = PL1_R, .resetvalue = 10,
5944       .accessfn = access_tdosa,
5945       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
5946     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
5947     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
5948       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
5949       .access = PL1_RW, .accessfn = access_tdosa,
5950       .type = ARM_CP_NOP },
5951     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
5952      * implement vector catch debug events yet.
5953      */
5954     { .name = "DBGVCR",
5955       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5956       .access = PL1_RW, .accessfn = access_tda,
5957       .type = ARM_CP_NOP },
5958     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
5959      * to save and restore a 32-bit guest's DBGVCR)
5960      */
5961     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
5962       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
5963       .access = PL2_RW, .accessfn = access_tda,
5964       .type = ARM_CP_NOP | ARM_CP_EL3_NO_EL2_KEEP },
5965     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
5966      * Channel but Linux may try to access this register. The 32-bit
5967      * alias is DBGDCCINT.
5968      */
5969     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
5970       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5971       .access = PL1_RW, .accessfn = access_tda,
5972       .type = ARM_CP_NOP },
5973 };
5974 
5975 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
5976     /* 64 bit access versions of the (dummy) debug registers */
5977     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
5978       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5979     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
5980       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5981 };
5982 
5983 /* Return the exception level to which exceptions should be taken
5984  * via SVEAccessTrap.  If an exception should be routed through
5985  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
5986  * take care of raising that exception.
5987  * C.f. the ARM pseudocode function CheckSVEEnabled.
5988  */
5989 int sve_exception_el(CPUARMState *env, int el)
5990 {
5991 #ifndef CONFIG_USER_ONLY
5992     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
5993 
5994     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
5995         /* Check CPACR.ZEN.  */
5996         switch (extract32(env->cp15.cpacr_el1, 16, 2)) {
5997         case 1:
5998             if (el != 0) {
5999                 break;
6000             }
6001             /* fall through */
6002         case 0:
6003         case 2:
6004             /* route_to_el2 */
6005             return hcr_el2 & HCR_TGE ? 2 : 1;
6006         }
6007 
6008         /* Check CPACR.FPEN.  */
6009         switch (extract32(env->cp15.cpacr_el1, 20, 2)) {
6010         case 1:
6011             if (el != 0) {
6012                 break;
6013             }
6014             /* fall through */
6015         case 0:
6016         case 2:
6017             return 0;
6018         }
6019     }
6020 
6021     /*
6022      * CPTR_EL2 changes format with HCR_EL2.E2H (regardless of TGE).
6023      */
6024     if (el <= 2) {
6025         if (hcr_el2 & HCR_E2H) {
6026             /* Check CPTR_EL2.ZEN.  */
6027             switch (extract32(env->cp15.cptr_el[2], 16, 2)) {
6028             case 1:
6029                 if (el != 0 || !(hcr_el2 & HCR_TGE)) {
6030                     break;
6031                 }
6032                 /* fall through */
6033             case 0:
6034             case 2:
6035                 return 2;
6036             }
6037 
6038             /* Check CPTR_EL2.FPEN.  */
6039             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
6040             case 1:
6041                 if (el == 2 || !(hcr_el2 & HCR_TGE)) {
6042                     break;
6043                 }
6044                 /* fall through */
6045             case 0:
6046             case 2:
6047                 return 0;
6048             }
6049         } else if (arm_is_el2_enabled(env)) {
6050             if (env->cp15.cptr_el[2] & CPTR_TZ) {
6051                 return 2;
6052             }
6053             if (env->cp15.cptr_el[2] & CPTR_TFP) {
6054                 return 0;
6055             }
6056         }
6057     }
6058 
6059     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6060     if (arm_feature(env, ARM_FEATURE_EL3)
6061         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6062         return 3;
6063     }
6064 #endif
6065     return 0;
6066 }
6067 
6068 uint32_t aarch64_sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6069 {
6070     uint32_t end_len;
6071 
6072     start_len = MIN(start_len, ARM_MAX_VQ - 1);
6073     end_len = start_len;
6074 
6075     if (!test_bit(start_len, cpu->sve_vq_map)) {
6076         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6077         assert(end_len < start_len);
6078     }
6079     return end_len;
6080 }
6081 
6082 /*
6083  * Given that SVE is enabled, return the vector length for EL.
6084  */
6085 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6086 {
6087     ARMCPU *cpu = env_archcpu(env);
6088     uint32_t zcr_len = cpu->sve_max_vq - 1;
6089 
6090     if (el <= 1 &&
6091         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6092         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6093     }
6094     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6095         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6096     }
6097     if (arm_feature(env, ARM_FEATURE_EL3)) {
6098         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6099     }
6100 
6101     return aarch64_sve_zcr_get_valid_len(cpu, zcr_len);
6102 }
6103 
6104 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6105                       uint64_t value)
6106 {
6107     int cur_el = arm_current_el(env);
6108     int old_len = sve_zcr_len_for_el(env, cur_el);
6109     int new_len;
6110 
6111     /* Bits other than [3:0] are RAZ/WI.  */
6112     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6113     raw_write(env, ri, value & 0xf);
6114 
6115     /*
6116      * Because we arrived here, we know both FP and SVE are enabled;
6117      * otherwise we would have trapped access to the ZCR_ELn register.
6118      */
6119     new_len = sve_zcr_len_for_el(env, cur_el);
6120     if (new_len < old_len) {
6121         aarch64_sve_narrow_vq(env, new_len + 1);
6122     }
6123 }
6124 
6125 static const ARMCPRegInfo zcr_reginfo[] = {
6126     { .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6127       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6128       .access = PL1_RW, .type = ARM_CP_SVE,
6129       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6130       .writefn = zcr_write, .raw_writefn = raw_write },
6131     { .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6132       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6133       .access = PL2_RW, .type = ARM_CP_SVE,
6134       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6135       .writefn = zcr_write, .raw_writefn = raw_write },
6136     { .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6137       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6138       .access = PL3_RW, .type = ARM_CP_SVE,
6139       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6140       .writefn = zcr_write, .raw_writefn = raw_write },
6141 };
6142 
6143 void hw_watchpoint_update(ARMCPU *cpu, int n)
6144 {
6145     CPUARMState *env = &cpu->env;
6146     vaddr len = 0;
6147     vaddr wvr = env->cp15.dbgwvr[n];
6148     uint64_t wcr = env->cp15.dbgwcr[n];
6149     int mask;
6150     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6151 
6152     if (env->cpu_watchpoint[n]) {
6153         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6154         env->cpu_watchpoint[n] = NULL;
6155     }
6156 
6157     if (!FIELD_EX64(wcr, DBGWCR, E)) {
6158         /* E bit clear : watchpoint disabled */
6159         return;
6160     }
6161 
6162     switch (FIELD_EX64(wcr, DBGWCR, LSC)) {
6163     case 0:
6164         /* LSC 00 is reserved and must behave as if the wp is disabled */
6165         return;
6166     case 1:
6167         flags |= BP_MEM_READ;
6168         break;
6169     case 2:
6170         flags |= BP_MEM_WRITE;
6171         break;
6172     case 3:
6173         flags |= BP_MEM_ACCESS;
6174         break;
6175     }
6176 
6177     /* Attempts to use both MASK and BAS fields simultaneously are
6178      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6179      * thus generating a watchpoint for every byte in the masked region.
6180      */
6181     mask = FIELD_EX64(wcr, DBGWCR, MASK);
6182     if (mask == 1 || mask == 2) {
6183         /* Reserved values of MASK; we must act as if the mask value was
6184          * some non-reserved value, or as if the watchpoint were disabled.
6185          * We choose the latter.
6186          */
6187         return;
6188     } else if (mask) {
6189         /* Watchpoint covers an aligned area up to 2GB in size */
6190         len = 1ULL << mask;
6191         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6192          * whether the watchpoint fires when the unmasked bits match; we opt
6193          * to generate the exceptions.
6194          */
6195         wvr &= ~(len - 1);
6196     } else {
6197         /* Watchpoint covers bytes defined by the byte address select bits */
6198         int bas = FIELD_EX64(wcr, DBGWCR, BAS);
6199         int basstart;
6200 
6201         if (extract64(wvr, 2, 1)) {
6202             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6203              * ignored, and BAS[3:0] define which bytes to watch.
6204              */
6205             bas &= 0xf;
6206         }
6207 
6208         if (bas == 0) {
6209             /* This must act as if the watchpoint is disabled */
6210             return;
6211         }
6212 
6213         /* The BAS bits are supposed to be programmed to indicate a contiguous
6214          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6215          * we fire for each byte in the word/doubleword addressed by the WVR.
6216          * We choose to ignore any non-zero bits after the first range of 1s.
6217          */
6218         basstart = ctz32(bas);
6219         len = cto32(bas >> basstart);
6220         wvr += basstart;
6221     }
6222 
6223     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6224                           &env->cpu_watchpoint[n]);
6225 }
6226 
6227 void hw_watchpoint_update_all(ARMCPU *cpu)
6228 {
6229     int i;
6230     CPUARMState *env = &cpu->env;
6231 
6232     /* Completely clear out existing QEMU watchpoints and our array, to
6233      * avoid possible stale entries following migration load.
6234      */
6235     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6236     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6237 
6238     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6239         hw_watchpoint_update(cpu, i);
6240     }
6241 }
6242 
6243 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6244                          uint64_t value)
6245 {
6246     ARMCPU *cpu = env_archcpu(env);
6247     int i = ri->crm;
6248 
6249     /*
6250      * Bits [1:0] are RES0.
6251      *
6252      * It is IMPLEMENTATION DEFINED whether [63:49] ([63:53] with FEAT_LVA)
6253      * are hardwired to the value of bit [48] ([52] with FEAT_LVA), or if
6254      * they contain the value written.  It is CONSTRAINED UNPREDICTABLE
6255      * whether the RESS bits are ignored when comparing an address.
6256      *
6257      * Therefore we are allowed to compare the entire register, which lets
6258      * us avoid considering whether or not FEAT_LVA is actually enabled.
6259      */
6260     value &= ~3ULL;
6261 
6262     raw_write(env, ri, value);
6263     hw_watchpoint_update(cpu, i);
6264 }
6265 
6266 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6267                          uint64_t value)
6268 {
6269     ARMCPU *cpu = env_archcpu(env);
6270     int i = ri->crm;
6271 
6272     raw_write(env, ri, value);
6273     hw_watchpoint_update(cpu, i);
6274 }
6275 
6276 void hw_breakpoint_update(ARMCPU *cpu, int n)
6277 {
6278     CPUARMState *env = &cpu->env;
6279     uint64_t bvr = env->cp15.dbgbvr[n];
6280     uint64_t bcr = env->cp15.dbgbcr[n];
6281     vaddr addr;
6282     int bt;
6283     int flags = BP_CPU;
6284 
6285     if (env->cpu_breakpoint[n]) {
6286         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6287         env->cpu_breakpoint[n] = NULL;
6288     }
6289 
6290     if (!extract64(bcr, 0, 1)) {
6291         /* E bit clear : watchpoint disabled */
6292         return;
6293     }
6294 
6295     bt = extract64(bcr, 20, 4);
6296 
6297     switch (bt) {
6298     case 4: /* unlinked address mismatch (reserved if AArch64) */
6299     case 5: /* linked address mismatch (reserved if AArch64) */
6300         qemu_log_mask(LOG_UNIMP,
6301                       "arm: address mismatch breakpoint types not implemented\n");
6302         return;
6303     case 0: /* unlinked address match */
6304     case 1: /* linked address match */
6305     {
6306         /*
6307          * Bits [1:0] are RES0.
6308          *
6309          * It is IMPLEMENTATION DEFINED whether bits [63:49]
6310          * ([63:53] for FEAT_LVA) are hardwired to a copy of the sign bit
6311          * of the VA field ([48] or [52] for FEAT_LVA), or whether the
6312          * value is read as written.  It is CONSTRAINED UNPREDICTABLE
6313          * whether the RESS bits are ignored when comparing an address.
6314          * Therefore we are allowed to compare the entire register, which
6315          * lets us avoid considering whether FEAT_LVA is actually enabled.
6316          *
6317          * The BAS field is used to allow setting breakpoints on 16-bit
6318          * wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6319          * a bp will fire if the addresses covered by the bp and the addresses
6320          * covered by the insn overlap but the insn doesn't start at the
6321          * start of the bp address range. We choose to require the insn and
6322          * the bp to have the same address. The constraints on writing to
6323          * BAS enforced in dbgbcr_write mean we have only four cases:
6324          *  0b0000  => no breakpoint
6325          *  0b0011  => breakpoint on addr
6326          *  0b1100  => breakpoint on addr + 2
6327          *  0b1111  => breakpoint on addr
6328          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6329          */
6330         int bas = extract64(bcr, 5, 4);
6331         addr = bvr & ~3ULL;
6332         if (bas == 0) {
6333             return;
6334         }
6335         if (bas == 0xc) {
6336             addr += 2;
6337         }
6338         break;
6339     }
6340     case 2: /* unlinked context ID match */
6341     case 8: /* unlinked VMID match (reserved if no EL2) */
6342     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6343         qemu_log_mask(LOG_UNIMP,
6344                       "arm: unlinked context breakpoint types not implemented\n");
6345         return;
6346     case 9: /* linked VMID match (reserved if no EL2) */
6347     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6348     case 3: /* linked context ID match */
6349     default:
6350         /* We must generate no events for Linked context matches (unless
6351          * they are linked to by some other bp/wp, which is handled in
6352          * updates for the linking bp/wp). We choose to also generate no events
6353          * for reserved values.
6354          */
6355         return;
6356     }
6357 
6358     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6359 }
6360 
6361 void hw_breakpoint_update_all(ARMCPU *cpu)
6362 {
6363     int i;
6364     CPUARMState *env = &cpu->env;
6365 
6366     /* Completely clear out existing QEMU breakpoints and our array, to
6367      * avoid possible stale entries following migration load.
6368      */
6369     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6370     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6371 
6372     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6373         hw_breakpoint_update(cpu, i);
6374     }
6375 }
6376 
6377 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6378                          uint64_t value)
6379 {
6380     ARMCPU *cpu = env_archcpu(env);
6381     int i = ri->crm;
6382 
6383     raw_write(env, ri, value);
6384     hw_breakpoint_update(cpu, i);
6385 }
6386 
6387 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6388                          uint64_t value)
6389 {
6390     ARMCPU *cpu = env_archcpu(env);
6391     int i = ri->crm;
6392 
6393     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6394      * copy of BAS[0].
6395      */
6396     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6397     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6398 
6399     raw_write(env, ri, value);
6400     hw_breakpoint_update(cpu, i);
6401 }
6402 
6403 static void define_debug_regs(ARMCPU *cpu)
6404 {
6405     /* Define v7 and v8 architectural debug registers.
6406      * These are just dummy implementations for now.
6407      */
6408     int i;
6409     int wrps, brps, ctx_cmps;
6410 
6411     /*
6412      * The Arm ARM says DBGDIDR is optional and deprecated if EL1 cannot
6413      * use AArch32.  Given that bit 15 is RES1, if the value is 0 then
6414      * the register must not exist for this cpu.
6415      */
6416     if (cpu->isar.dbgdidr != 0) {
6417         ARMCPRegInfo dbgdidr = {
6418             .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0,
6419             .opc1 = 0, .opc2 = 0,
6420             .access = PL0_R, .accessfn = access_tda,
6421             .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6422         };
6423         define_one_arm_cp_reg(cpu, &dbgdidr);
6424     }
6425 
6426     /* Note that all these register fields hold "number of Xs minus 1". */
6427     brps = arm_num_brps(cpu);
6428     wrps = arm_num_wrps(cpu);
6429     ctx_cmps = arm_num_ctx_cmps(cpu);
6430 
6431     assert(ctx_cmps <= brps);
6432 
6433     define_arm_cp_regs(cpu, debug_cp_reginfo);
6434 
6435     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6436         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6437     }
6438 
6439     for (i = 0; i < brps; i++) {
6440         ARMCPRegInfo dbgregs[] = {
6441             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6442               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6443               .access = PL1_RW, .accessfn = access_tda,
6444               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6445               .writefn = dbgbvr_write, .raw_writefn = raw_write
6446             },
6447             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6448               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6449               .access = PL1_RW, .accessfn = access_tda,
6450               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6451               .writefn = dbgbcr_write, .raw_writefn = raw_write
6452             },
6453         };
6454         define_arm_cp_regs(cpu, dbgregs);
6455     }
6456 
6457     for (i = 0; i < wrps; i++) {
6458         ARMCPRegInfo dbgregs[] = {
6459             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6460               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6461               .access = PL1_RW, .accessfn = access_tda,
6462               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6463               .writefn = dbgwvr_write, .raw_writefn = raw_write
6464             },
6465             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6466               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6467               .access = PL1_RW, .accessfn = access_tda,
6468               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6469               .writefn = dbgwcr_write, .raw_writefn = raw_write
6470             },
6471         };
6472         define_arm_cp_regs(cpu, dbgregs);
6473     }
6474 }
6475 
6476 static void define_pmu_regs(ARMCPU *cpu)
6477 {
6478     /*
6479      * v7 performance monitor control register: same implementor
6480      * field as main ID register, and we implement four counters in
6481      * addition to the cycle count register.
6482      */
6483     unsigned int i, pmcrn = PMCR_NUM_COUNTERS;
6484     ARMCPRegInfo pmcr = {
6485         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6486         .access = PL0_RW,
6487         .type = ARM_CP_IO | ARM_CP_ALIAS,
6488         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6489         .accessfn = pmreg_access, .writefn = pmcr_write,
6490         .raw_writefn = raw_write,
6491     };
6492     ARMCPRegInfo pmcr64 = {
6493         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6494         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6495         .access = PL0_RW, .accessfn = pmreg_access,
6496         .type = ARM_CP_IO,
6497         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6498         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6499                       PMCRLC,
6500         .writefn = pmcr_write, .raw_writefn = raw_write,
6501     };
6502     define_one_arm_cp_reg(cpu, &pmcr);
6503     define_one_arm_cp_reg(cpu, &pmcr64);
6504     for (i = 0; i < pmcrn; i++) {
6505         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6506         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6507         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6508         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6509         ARMCPRegInfo pmev_regs[] = {
6510             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6511               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6512               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6513               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6514               .accessfn = pmreg_access_xevcntr },
6515             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6516               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6517               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access_xevcntr,
6518               .type = ARM_CP_IO,
6519               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6520               .raw_readfn = pmevcntr_rawread,
6521               .raw_writefn = pmevcntr_rawwrite },
6522             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6523               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6524               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6525               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6526               .accessfn = pmreg_access },
6527             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6528               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6529               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6530               .type = ARM_CP_IO,
6531               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6532               .raw_writefn = pmevtyper_rawwrite },
6533         };
6534         define_arm_cp_regs(cpu, pmev_regs);
6535         g_free(pmevcntr_name);
6536         g_free(pmevcntr_el0_name);
6537         g_free(pmevtyper_name);
6538         g_free(pmevtyper_el0_name);
6539     }
6540     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6541         ARMCPRegInfo v81_pmu_regs[] = {
6542             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6543               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6544               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6545               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6546             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6547               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6548               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6549               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6550         };
6551         define_arm_cp_regs(cpu, v81_pmu_regs);
6552     }
6553     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6554         static const ARMCPRegInfo v84_pmmir = {
6555             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6556             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6557             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6558             .resetvalue = 0
6559         };
6560         define_one_arm_cp_reg(cpu, &v84_pmmir);
6561     }
6562 }
6563 
6564 /* We don't know until after realize whether there's a GICv3
6565  * attached, and that is what registers the gicv3 sysregs.
6566  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6567  * at runtime.
6568  */
6569 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6570 {
6571     ARMCPU *cpu = env_archcpu(env);
6572     uint64_t pfr1 = cpu->isar.id_pfr1;
6573 
6574     if (env->gicv3state) {
6575         pfr1 |= 1 << 28;
6576     }
6577     return pfr1;
6578 }
6579 
6580 #ifndef CONFIG_USER_ONLY
6581 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6582 {
6583     ARMCPU *cpu = env_archcpu(env);
6584     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6585 
6586     if (env->gicv3state) {
6587         pfr0 |= 1 << 24;
6588     }
6589     return pfr0;
6590 }
6591 #endif
6592 
6593 /* Shared logic between LORID and the rest of the LOR* registers.
6594  * Secure state exclusion has already been dealt with.
6595  */
6596 static CPAccessResult access_lor_ns(CPUARMState *env,
6597                                     const ARMCPRegInfo *ri, bool isread)
6598 {
6599     int el = arm_current_el(env);
6600 
6601     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6602         return CP_ACCESS_TRAP_EL2;
6603     }
6604     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6605         return CP_ACCESS_TRAP_EL3;
6606     }
6607     return CP_ACCESS_OK;
6608 }
6609 
6610 static CPAccessResult access_lor_other(CPUARMState *env,
6611                                        const ARMCPRegInfo *ri, bool isread)
6612 {
6613     if (arm_is_secure_below_el3(env)) {
6614         /* Access denied in secure mode.  */
6615         return CP_ACCESS_TRAP;
6616     }
6617     return access_lor_ns(env, ri, isread);
6618 }
6619 
6620 /*
6621  * A trivial implementation of ARMv8.1-LOR leaves all of these
6622  * registers fixed at 0, which indicates that there are zero
6623  * supported Limited Ordering regions.
6624  */
6625 static const ARMCPRegInfo lor_reginfo[] = {
6626     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6627       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6628       .access = PL1_RW, .accessfn = access_lor_other,
6629       .type = ARM_CP_CONST, .resetvalue = 0 },
6630     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6631       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6632       .access = PL1_RW, .accessfn = access_lor_other,
6633       .type = ARM_CP_CONST, .resetvalue = 0 },
6634     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6635       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6636       .access = PL1_RW, .accessfn = access_lor_other,
6637       .type = ARM_CP_CONST, .resetvalue = 0 },
6638     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6639       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6640       .access = PL1_RW, .accessfn = access_lor_other,
6641       .type = ARM_CP_CONST, .resetvalue = 0 },
6642     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6643       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6644       .access = PL1_R, .accessfn = access_lor_ns,
6645       .type = ARM_CP_CONST, .resetvalue = 0 },
6646 };
6647 
6648 #ifdef TARGET_AARCH64
6649 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6650                                    bool isread)
6651 {
6652     int el = arm_current_el(env);
6653 
6654     if (el < 2 &&
6655         arm_feature(env, ARM_FEATURE_EL2) &&
6656         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6657         return CP_ACCESS_TRAP_EL2;
6658     }
6659     if (el < 3 &&
6660         arm_feature(env, ARM_FEATURE_EL3) &&
6661         !(env->cp15.scr_el3 & SCR_APK)) {
6662         return CP_ACCESS_TRAP_EL3;
6663     }
6664     return CP_ACCESS_OK;
6665 }
6666 
6667 static const ARMCPRegInfo pauth_reginfo[] = {
6668     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6669       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6670       .access = PL1_RW, .accessfn = access_pauth,
6671       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6672     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6673       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6674       .access = PL1_RW, .accessfn = access_pauth,
6675       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6676     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6677       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6678       .access = PL1_RW, .accessfn = access_pauth,
6679       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6680     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6681       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6682       .access = PL1_RW, .accessfn = access_pauth,
6683       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6684     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6685       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6686       .access = PL1_RW, .accessfn = access_pauth,
6687       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6688     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6689       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6690       .access = PL1_RW, .accessfn = access_pauth,
6691       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6692     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6693       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6694       .access = PL1_RW, .accessfn = access_pauth,
6695       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6696     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6697       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6698       .access = PL1_RW, .accessfn = access_pauth,
6699       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6700     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6701       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6702       .access = PL1_RW, .accessfn = access_pauth,
6703       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6704     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6705       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6706       .access = PL1_RW, .accessfn = access_pauth,
6707       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6708 };
6709 
6710 static const ARMCPRegInfo tlbirange_reginfo[] = {
6711     { .name = "TLBI_RVAE1IS", .state = ARM_CP_STATE_AA64,
6712       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 1,
6713       .access = PL1_W, .type = ARM_CP_NO_RAW,
6714       .writefn = tlbi_aa64_rvae1is_write },
6715     { .name = "TLBI_RVAAE1IS", .state = ARM_CP_STATE_AA64,
6716       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 3,
6717       .access = PL1_W, .type = ARM_CP_NO_RAW,
6718       .writefn = tlbi_aa64_rvae1is_write },
6719    { .name = "TLBI_RVALE1IS", .state = ARM_CP_STATE_AA64,
6720       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 5,
6721       .access = PL1_W, .type = ARM_CP_NO_RAW,
6722       .writefn = tlbi_aa64_rvae1is_write },
6723     { .name = "TLBI_RVAALE1IS", .state = ARM_CP_STATE_AA64,
6724       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 7,
6725       .access = PL1_W, .type = ARM_CP_NO_RAW,
6726       .writefn = tlbi_aa64_rvae1is_write },
6727     { .name = "TLBI_RVAE1OS", .state = ARM_CP_STATE_AA64,
6728       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
6729       .access = PL1_W, .type = ARM_CP_NO_RAW,
6730       .writefn = tlbi_aa64_rvae1is_write },
6731     { .name = "TLBI_RVAAE1OS", .state = ARM_CP_STATE_AA64,
6732       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 3,
6733       .access = PL1_W, .type = ARM_CP_NO_RAW,
6734       .writefn = tlbi_aa64_rvae1is_write },
6735    { .name = "TLBI_RVALE1OS", .state = ARM_CP_STATE_AA64,
6736       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 5,
6737       .access = PL1_W, .type = ARM_CP_NO_RAW,
6738       .writefn = tlbi_aa64_rvae1is_write },
6739     { .name = "TLBI_RVAALE1OS", .state = ARM_CP_STATE_AA64,
6740       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 7,
6741       .access = PL1_W, .type = ARM_CP_NO_RAW,
6742       .writefn = tlbi_aa64_rvae1is_write },
6743     { .name = "TLBI_RVAE1", .state = ARM_CP_STATE_AA64,
6744       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
6745       .access = PL1_W, .type = ARM_CP_NO_RAW,
6746       .writefn = tlbi_aa64_rvae1_write },
6747     { .name = "TLBI_RVAAE1", .state = ARM_CP_STATE_AA64,
6748       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 3,
6749       .access = PL1_W, .type = ARM_CP_NO_RAW,
6750       .writefn = tlbi_aa64_rvae1_write },
6751    { .name = "TLBI_RVALE1", .state = ARM_CP_STATE_AA64,
6752       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 5,
6753       .access = PL1_W, .type = ARM_CP_NO_RAW,
6754       .writefn = tlbi_aa64_rvae1_write },
6755     { .name = "TLBI_RVAALE1", .state = ARM_CP_STATE_AA64,
6756       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 7,
6757       .access = PL1_W, .type = ARM_CP_NO_RAW,
6758       .writefn = tlbi_aa64_rvae1_write },
6759     { .name = "TLBI_RIPAS2E1IS", .state = ARM_CP_STATE_AA64,
6760       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 2,
6761       .access = PL2_W, .type = ARM_CP_NOP },
6762     { .name = "TLBI_RIPAS2LE1IS", .state = ARM_CP_STATE_AA64,
6763       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 6,
6764       .access = PL2_W, .type = ARM_CP_NOP },
6765     { .name = "TLBI_RVAE2IS", .state = ARM_CP_STATE_AA64,
6766       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 1,
6767       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6768       .writefn = tlbi_aa64_rvae2is_write },
6769    { .name = "TLBI_RVALE2IS", .state = ARM_CP_STATE_AA64,
6770       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 5,
6771       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6772       .writefn = tlbi_aa64_rvae2is_write },
6773     { .name = "TLBI_RIPAS2E1", .state = ARM_CP_STATE_AA64,
6774       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 2,
6775       .access = PL2_W, .type = ARM_CP_NOP },
6776    { .name = "TLBI_RIPAS2LE1", .state = ARM_CP_STATE_AA64,
6777       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 6,
6778       .access = PL2_W, .type = ARM_CP_NOP },
6779    { .name = "TLBI_RVAE2OS", .state = ARM_CP_STATE_AA64,
6780       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 1,
6781       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6782       .writefn = tlbi_aa64_rvae2is_write },
6783    { .name = "TLBI_RVALE2OS", .state = ARM_CP_STATE_AA64,
6784       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 5,
6785       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6786       .writefn = tlbi_aa64_rvae2is_write },
6787     { .name = "TLBI_RVAE2", .state = ARM_CP_STATE_AA64,
6788       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 1,
6789       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6790       .writefn = tlbi_aa64_rvae2_write },
6791    { .name = "TLBI_RVALE2", .state = ARM_CP_STATE_AA64,
6792       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 5,
6793       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6794       .writefn = tlbi_aa64_rvae2_write },
6795    { .name = "TLBI_RVAE3IS", .state = ARM_CP_STATE_AA64,
6796       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 1,
6797       .access = PL3_W, .type = ARM_CP_NO_RAW,
6798       .writefn = tlbi_aa64_rvae3is_write },
6799    { .name = "TLBI_RVALE3IS", .state = ARM_CP_STATE_AA64,
6800       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 5,
6801       .access = PL3_W, .type = ARM_CP_NO_RAW,
6802       .writefn = tlbi_aa64_rvae3is_write },
6803    { .name = "TLBI_RVAE3OS", .state = ARM_CP_STATE_AA64,
6804       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 1,
6805       .access = PL3_W, .type = ARM_CP_NO_RAW,
6806       .writefn = tlbi_aa64_rvae3is_write },
6807    { .name = "TLBI_RVALE3OS", .state = ARM_CP_STATE_AA64,
6808       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 5,
6809       .access = PL3_W, .type = ARM_CP_NO_RAW,
6810       .writefn = tlbi_aa64_rvae3is_write },
6811    { .name = "TLBI_RVAE3", .state = ARM_CP_STATE_AA64,
6812       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 1,
6813       .access = PL3_W, .type = ARM_CP_NO_RAW,
6814       .writefn = tlbi_aa64_rvae3_write },
6815    { .name = "TLBI_RVALE3", .state = ARM_CP_STATE_AA64,
6816       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 5,
6817       .access = PL3_W, .type = ARM_CP_NO_RAW,
6818       .writefn = tlbi_aa64_rvae3_write },
6819 };
6820 
6821 static const ARMCPRegInfo tlbios_reginfo[] = {
6822     { .name = "TLBI_VMALLE1OS", .state = ARM_CP_STATE_AA64,
6823       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 0,
6824       .access = PL1_W, .type = ARM_CP_NO_RAW,
6825       .writefn = tlbi_aa64_vmalle1is_write },
6826     { .name = "TLBI_VAE1OS", .state = ARM_CP_STATE_AA64,
6827       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 1,
6828       .access = PL1_W, .type = ARM_CP_NO_RAW,
6829       .writefn = tlbi_aa64_vae1is_write },
6830     { .name = "TLBI_ASIDE1OS", .state = ARM_CP_STATE_AA64,
6831       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 2,
6832       .access = PL1_W, .type = ARM_CP_NO_RAW,
6833       .writefn = tlbi_aa64_vmalle1is_write },
6834     { .name = "TLBI_VAAE1OS", .state = ARM_CP_STATE_AA64,
6835       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 3,
6836       .access = PL1_W, .type = ARM_CP_NO_RAW,
6837       .writefn = tlbi_aa64_vae1is_write },
6838     { .name = "TLBI_VALE1OS", .state = ARM_CP_STATE_AA64,
6839       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 5,
6840       .access = PL1_W, .type = ARM_CP_NO_RAW,
6841       .writefn = tlbi_aa64_vae1is_write },
6842     { .name = "TLBI_VAALE1OS", .state = ARM_CP_STATE_AA64,
6843       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 7,
6844       .access = PL1_W, .type = ARM_CP_NO_RAW,
6845       .writefn = tlbi_aa64_vae1is_write },
6846     { .name = "TLBI_ALLE2OS", .state = ARM_CP_STATE_AA64,
6847       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 0,
6848       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6849       .writefn = tlbi_aa64_alle2is_write },
6850     { .name = "TLBI_VAE2OS", .state = ARM_CP_STATE_AA64,
6851       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 1,
6852       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6853       .writefn = tlbi_aa64_vae2is_write },
6854    { .name = "TLBI_ALLE1OS", .state = ARM_CP_STATE_AA64,
6855       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 4,
6856       .access = PL2_W, .type = ARM_CP_NO_RAW,
6857       .writefn = tlbi_aa64_alle1is_write },
6858     { .name = "TLBI_VALE2OS", .state = ARM_CP_STATE_AA64,
6859       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 5,
6860       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6861       .writefn = tlbi_aa64_vae2is_write },
6862     { .name = "TLBI_VMALLS12E1OS", .state = ARM_CP_STATE_AA64,
6863       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 6,
6864       .access = PL2_W, .type = ARM_CP_NO_RAW,
6865       .writefn = tlbi_aa64_alle1is_write },
6866     { .name = "TLBI_IPAS2E1OS", .state = ARM_CP_STATE_AA64,
6867       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 0,
6868       .access = PL2_W, .type = ARM_CP_NOP },
6869     { .name = "TLBI_RIPAS2E1OS", .state = ARM_CP_STATE_AA64,
6870       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 3,
6871       .access = PL2_W, .type = ARM_CP_NOP },
6872     { .name = "TLBI_IPAS2LE1OS", .state = ARM_CP_STATE_AA64,
6873       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 4,
6874       .access = PL2_W, .type = ARM_CP_NOP },
6875     { .name = "TLBI_RIPAS2LE1OS", .state = ARM_CP_STATE_AA64,
6876       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 7,
6877       .access = PL2_W, .type = ARM_CP_NOP },
6878     { .name = "TLBI_ALLE3OS", .state = ARM_CP_STATE_AA64,
6879       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 0,
6880       .access = PL3_W, .type = ARM_CP_NO_RAW,
6881       .writefn = tlbi_aa64_alle3is_write },
6882     { .name = "TLBI_VAE3OS", .state = ARM_CP_STATE_AA64,
6883       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 1,
6884       .access = PL3_W, .type = ARM_CP_NO_RAW,
6885       .writefn = tlbi_aa64_vae3is_write },
6886     { .name = "TLBI_VALE3OS", .state = ARM_CP_STATE_AA64,
6887       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 5,
6888       .access = PL3_W, .type = ARM_CP_NO_RAW,
6889       .writefn = tlbi_aa64_vae3is_write },
6890 };
6891 
6892 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
6893 {
6894     Error *err = NULL;
6895     uint64_t ret;
6896 
6897     /* Success sets NZCV = 0000.  */
6898     env->NF = env->CF = env->VF = 0, env->ZF = 1;
6899 
6900     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
6901         /*
6902          * ??? Failed, for unknown reasons in the crypto subsystem.
6903          * The best we can do is log the reason and return the
6904          * timed-out indication to the guest.  There is no reason
6905          * we know to expect this failure to be transitory, so the
6906          * guest may well hang retrying the operation.
6907          */
6908         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
6909                       ri->name, error_get_pretty(err));
6910         error_free(err);
6911 
6912         env->ZF = 0; /* NZCF = 0100 */
6913         return 0;
6914     }
6915     return ret;
6916 }
6917 
6918 /* We do not support re-seeding, so the two registers operate the same.  */
6919 static const ARMCPRegInfo rndr_reginfo[] = {
6920     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
6921       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6922       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
6923       .access = PL0_R, .readfn = rndr_readfn },
6924     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
6925       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6926       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
6927       .access = PL0_R, .readfn = rndr_readfn },
6928 };
6929 
6930 #ifndef CONFIG_USER_ONLY
6931 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
6932                           uint64_t value)
6933 {
6934     ARMCPU *cpu = env_archcpu(env);
6935     /* CTR_EL0 System register -> DminLine, bits [19:16] */
6936     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
6937     uint64_t vaddr_in = (uint64_t) value;
6938     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
6939     void *haddr;
6940     int mem_idx = cpu_mmu_index(env, false);
6941 
6942     /* This won't be crossing page boundaries */
6943     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
6944     if (haddr) {
6945 
6946         ram_addr_t offset;
6947         MemoryRegion *mr;
6948 
6949         /* RCU lock is already being held */
6950         mr = memory_region_from_host(haddr, &offset);
6951 
6952         if (mr) {
6953             memory_region_writeback(mr, offset, dline_size);
6954         }
6955     }
6956 }
6957 
6958 static const ARMCPRegInfo dcpop_reg[] = {
6959     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
6960       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
6961       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6962       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6963 };
6964 
6965 static const ARMCPRegInfo dcpodp_reg[] = {
6966     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
6967       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
6968       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6969       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6970 };
6971 #endif /*CONFIG_USER_ONLY*/
6972 
6973 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
6974                                        bool isread)
6975 {
6976     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
6977         return CP_ACCESS_TRAP_EL2;
6978     }
6979 
6980     return CP_ACCESS_OK;
6981 }
6982 
6983 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
6984                                  bool isread)
6985 {
6986     int el = arm_current_el(env);
6987 
6988     if (el < 2 && arm_is_el2_enabled(env)) {
6989         uint64_t hcr = arm_hcr_el2_eff(env);
6990         if (!(hcr & HCR_ATA) && (!(hcr & HCR_E2H) || !(hcr & HCR_TGE))) {
6991             return CP_ACCESS_TRAP_EL2;
6992         }
6993     }
6994     if (el < 3 &&
6995         arm_feature(env, ARM_FEATURE_EL3) &&
6996         !(env->cp15.scr_el3 & SCR_ATA)) {
6997         return CP_ACCESS_TRAP_EL3;
6998     }
6999     return CP_ACCESS_OK;
7000 }
7001 
7002 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
7003 {
7004     return env->pstate & PSTATE_TCO;
7005 }
7006 
7007 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
7008 {
7009     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
7010 }
7011 
7012 static const ARMCPRegInfo mte_reginfo[] = {
7013     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
7014       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
7015       .access = PL1_RW, .accessfn = access_mte,
7016       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
7017     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
7018       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
7019       .access = PL1_RW, .accessfn = access_mte,
7020       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
7021     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
7022       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
7023       .access = PL2_RW, .accessfn = access_mte,
7024       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
7025     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
7026       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
7027       .access = PL3_RW,
7028       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
7029     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
7030       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
7031       .access = PL1_RW, .accessfn = access_mte,
7032       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
7033     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
7034       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
7035       .access = PL1_RW, .accessfn = access_mte,
7036       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
7037     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
7038       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
7039       .access = PL1_R, .accessfn = access_aa64_tid5,
7040       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
7041     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7042       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7043       .type = ARM_CP_NO_RAW,
7044       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
7045     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
7046       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
7047       .type = ARM_CP_NOP, .access = PL1_W,
7048       .accessfn = aa64_cacheop_poc_access },
7049     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
7050       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
7051       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7052     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
7053       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
7054       .type = ARM_CP_NOP, .access = PL1_W,
7055       .accessfn = aa64_cacheop_poc_access },
7056     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
7057       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
7058       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7059     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
7060       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
7061       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7062     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
7063       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
7064       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7065     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
7066       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
7067       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7068     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
7069       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
7070       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7071 };
7072 
7073 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
7074     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7075       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7076       .type = ARM_CP_CONST, .access = PL0_RW, },
7077 };
7078 
7079 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
7080     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
7081       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
7082       .type = ARM_CP_NOP, .access = PL0_W,
7083       .accessfn = aa64_cacheop_poc_access },
7084     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
7085       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
7086       .type = ARM_CP_NOP, .access = PL0_W,
7087       .accessfn = aa64_cacheop_poc_access },
7088     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
7089       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
7090       .type = ARM_CP_NOP, .access = PL0_W,
7091       .accessfn = aa64_cacheop_poc_access },
7092     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
7093       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
7094       .type = ARM_CP_NOP, .access = PL0_W,
7095       .accessfn = aa64_cacheop_poc_access },
7096     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
7097       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
7098       .type = ARM_CP_NOP, .access = PL0_W,
7099       .accessfn = aa64_cacheop_poc_access },
7100     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
7101       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
7102       .type = ARM_CP_NOP, .access = PL0_W,
7103       .accessfn = aa64_cacheop_poc_access },
7104     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
7105       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
7106       .type = ARM_CP_NOP, .access = PL0_W,
7107       .accessfn = aa64_cacheop_poc_access },
7108     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
7109       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
7110       .type = ARM_CP_NOP, .access = PL0_W,
7111       .accessfn = aa64_cacheop_poc_access },
7112     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7113       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7114       .access = PL0_W, .type = ARM_CP_DC_GVA,
7115 #ifndef CONFIG_USER_ONLY
7116       /* Avoid overhead of an access check that always passes in user-mode */
7117       .accessfn = aa64_zva_access,
7118 #endif
7119     },
7120     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7121       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7122       .access = PL0_W, .type = ARM_CP_DC_GZVA,
7123 #ifndef CONFIG_USER_ONLY
7124       /* Avoid overhead of an access check that always passes in user-mode */
7125       .accessfn = aa64_zva_access,
7126 #endif
7127     },
7128 };
7129 
7130 #endif
7131 
7132 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7133                                      bool isread)
7134 {
7135     int el = arm_current_el(env);
7136 
7137     if (el == 0) {
7138         uint64_t sctlr = arm_sctlr(env, el);
7139         if (!(sctlr & SCTLR_EnRCTX)) {
7140             return CP_ACCESS_TRAP;
7141         }
7142     } else if (el == 1) {
7143         uint64_t hcr = arm_hcr_el2_eff(env);
7144         if (hcr & HCR_NV) {
7145             return CP_ACCESS_TRAP_EL2;
7146         }
7147     }
7148     return CP_ACCESS_OK;
7149 }
7150 
7151 static const ARMCPRegInfo predinv_reginfo[] = {
7152     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7153       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7154       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7155     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7156       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7157       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7158     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7159       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7160       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7161     /*
7162      * Note the AArch32 opcodes have a different OPC1.
7163      */
7164     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7165       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7166       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7167     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7168       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7169       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7170     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7171       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7172       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7173 };
7174 
7175 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7176 {
7177     /* Read the high 32 bits of the current CCSIDR */
7178     return extract64(ccsidr_read(env, ri), 32, 32);
7179 }
7180 
7181 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7182     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7183       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7184       .access = PL1_R,
7185       .accessfn = access_aa64_tid2,
7186       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7187 };
7188 
7189 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7190                                        bool isread)
7191 {
7192     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7193         return CP_ACCESS_TRAP_EL2;
7194     }
7195 
7196     return CP_ACCESS_OK;
7197 }
7198 
7199 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7200                                        bool isread)
7201 {
7202     if (arm_feature(env, ARM_FEATURE_V8)) {
7203         return access_aa64_tid3(env, ri, isread);
7204     }
7205 
7206     return CP_ACCESS_OK;
7207 }
7208 
7209 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7210                                      bool isread)
7211 {
7212     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7213         return CP_ACCESS_TRAP_EL2;
7214     }
7215 
7216     return CP_ACCESS_OK;
7217 }
7218 
7219 static CPAccessResult access_joscr_jmcr(CPUARMState *env,
7220                                         const ARMCPRegInfo *ri, bool isread)
7221 {
7222     /*
7223      * HSTR.TJDBX traps JOSCR and JMCR accesses, but it exists only
7224      * in v7A, not in v8A.
7225      */
7226     if (!arm_feature(env, ARM_FEATURE_V8) &&
7227         arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
7228         (env->cp15.hstr_el2 & HSTR_TJDBX)) {
7229         return CP_ACCESS_TRAP_EL2;
7230     }
7231     return CP_ACCESS_OK;
7232 }
7233 
7234 static const ARMCPRegInfo jazelle_regs[] = {
7235     { .name = "JIDR",
7236       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7237       .access = PL1_R, .accessfn = access_jazelle,
7238       .type = ARM_CP_CONST, .resetvalue = 0 },
7239     { .name = "JOSCR",
7240       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7241       .accessfn = access_joscr_jmcr,
7242       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7243     { .name = "JMCR",
7244       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7245       .accessfn = access_joscr_jmcr,
7246       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7247 };
7248 
7249 static const ARMCPRegInfo contextidr_el2 = {
7250     .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7251     .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7252     .access = PL2_RW,
7253     .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2])
7254 };
7255 
7256 static const ARMCPRegInfo vhe_reginfo[] = {
7257     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7258       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7259       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7260       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7261 #ifndef CONFIG_USER_ONLY
7262     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7263       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7264       .fieldoffset =
7265         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7266       .type = ARM_CP_IO, .access = PL2_RW,
7267       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7268     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7269       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7270       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7271       .resetfn = gt_hv_timer_reset,
7272       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7273     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7274       .type = ARM_CP_IO,
7275       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7276       .access = PL2_RW,
7277       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7278       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7279     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7280       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7281       .type = ARM_CP_IO | ARM_CP_ALIAS,
7282       .access = PL2_RW, .accessfn = e2h_access,
7283       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7284       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7285     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7286       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7287       .type = ARM_CP_IO | ARM_CP_ALIAS,
7288       .access = PL2_RW, .accessfn = e2h_access,
7289       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7290       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7291     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7292       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7293       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7294       .access = PL2_RW, .accessfn = e2h_access,
7295       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7296     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7297       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7298       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7299       .access = PL2_RW, .accessfn = e2h_access,
7300       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7301     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7302       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7303       .type = ARM_CP_IO | ARM_CP_ALIAS,
7304       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7305       .access = PL2_RW, .accessfn = e2h_access,
7306       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7307     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7308       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7309       .type = ARM_CP_IO | ARM_CP_ALIAS,
7310       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7311       .access = PL2_RW, .accessfn = e2h_access,
7312       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7313 #endif
7314 };
7315 
7316 #ifndef CONFIG_USER_ONLY
7317 static const ARMCPRegInfo ats1e1_reginfo[] = {
7318     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7319       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7320       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7321       .writefn = ats_write64 },
7322     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7323       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7324       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7325       .writefn = ats_write64 },
7326 };
7327 
7328 static const ARMCPRegInfo ats1cp_reginfo[] = {
7329     { .name = "ATS1CPRP",
7330       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7331       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7332       .writefn = ats_write },
7333     { .name = "ATS1CPWP",
7334       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7335       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7336       .writefn = ats_write },
7337 };
7338 #endif
7339 
7340 /*
7341  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7342  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7343  * is non-zero, which is never for ARMv7, optionally in ARMv8
7344  * and mandatorily for ARMv8.2 and up.
7345  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7346  * implementation is RAZ/WI we can ignore this detail, as we
7347  * do for ACTLR.
7348  */
7349 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7350     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7351       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7352       .access = PL1_RW, .accessfn = access_tacr,
7353       .type = ARM_CP_CONST, .resetvalue = 0 },
7354     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7355       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7356       .access = PL2_RW, .type = ARM_CP_CONST,
7357       .resetvalue = 0 },
7358 };
7359 
7360 void register_cp_regs_for_features(ARMCPU *cpu)
7361 {
7362     /* Register all the coprocessor registers based on feature bits */
7363     CPUARMState *env = &cpu->env;
7364     if (arm_feature(env, ARM_FEATURE_M)) {
7365         /* M profile has no coprocessor registers */
7366         return;
7367     }
7368 
7369     define_arm_cp_regs(cpu, cp_reginfo);
7370     if (!arm_feature(env, ARM_FEATURE_V8)) {
7371         /* Must go early as it is full of wildcards that may be
7372          * overridden by later definitions.
7373          */
7374         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7375     }
7376 
7377     if (arm_feature(env, ARM_FEATURE_V6)) {
7378         /* The ID registers all have impdef reset values */
7379         ARMCPRegInfo v6_idregs[] = {
7380             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7381               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7382               .access = PL1_R, .type = ARM_CP_CONST,
7383               .accessfn = access_aa32_tid3,
7384               .resetvalue = cpu->isar.id_pfr0 },
7385             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7386              * the value of the GIC field until after we define these regs.
7387              */
7388             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7389               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7390               .access = PL1_R, .type = ARM_CP_NO_RAW,
7391               .accessfn = access_aa32_tid3,
7392               .readfn = id_pfr1_read,
7393               .writefn = arm_cp_write_ignore },
7394             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7395               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7396               .access = PL1_R, .type = ARM_CP_CONST,
7397               .accessfn = access_aa32_tid3,
7398               .resetvalue = cpu->isar.id_dfr0 },
7399             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7400               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7401               .access = PL1_R, .type = ARM_CP_CONST,
7402               .accessfn = access_aa32_tid3,
7403               .resetvalue = cpu->id_afr0 },
7404             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7405               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7406               .access = PL1_R, .type = ARM_CP_CONST,
7407               .accessfn = access_aa32_tid3,
7408               .resetvalue = cpu->isar.id_mmfr0 },
7409             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7410               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7411               .access = PL1_R, .type = ARM_CP_CONST,
7412               .accessfn = access_aa32_tid3,
7413               .resetvalue = cpu->isar.id_mmfr1 },
7414             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7415               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7416               .access = PL1_R, .type = ARM_CP_CONST,
7417               .accessfn = access_aa32_tid3,
7418               .resetvalue = cpu->isar.id_mmfr2 },
7419             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7420               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7421               .access = PL1_R, .type = ARM_CP_CONST,
7422               .accessfn = access_aa32_tid3,
7423               .resetvalue = cpu->isar.id_mmfr3 },
7424             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7425               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7426               .access = PL1_R, .type = ARM_CP_CONST,
7427               .accessfn = access_aa32_tid3,
7428               .resetvalue = cpu->isar.id_isar0 },
7429             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7430               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7431               .access = PL1_R, .type = ARM_CP_CONST,
7432               .accessfn = access_aa32_tid3,
7433               .resetvalue = cpu->isar.id_isar1 },
7434             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7435               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7436               .access = PL1_R, .type = ARM_CP_CONST,
7437               .accessfn = access_aa32_tid3,
7438               .resetvalue = cpu->isar.id_isar2 },
7439             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7440               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7441               .access = PL1_R, .type = ARM_CP_CONST,
7442               .accessfn = access_aa32_tid3,
7443               .resetvalue = cpu->isar.id_isar3 },
7444             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7445               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7446               .access = PL1_R, .type = ARM_CP_CONST,
7447               .accessfn = access_aa32_tid3,
7448               .resetvalue = cpu->isar.id_isar4 },
7449             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7450               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7451               .access = PL1_R, .type = ARM_CP_CONST,
7452               .accessfn = access_aa32_tid3,
7453               .resetvalue = cpu->isar.id_isar5 },
7454             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7455               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7456               .access = PL1_R, .type = ARM_CP_CONST,
7457               .accessfn = access_aa32_tid3,
7458               .resetvalue = cpu->isar.id_mmfr4 },
7459             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7460               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7461               .access = PL1_R, .type = ARM_CP_CONST,
7462               .accessfn = access_aa32_tid3,
7463               .resetvalue = cpu->isar.id_isar6 },
7464         };
7465         define_arm_cp_regs(cpu, v6_idregs);
7466         define_arm_cp_regs(cpu, v6_cp_reginfo);
7467     } else {
7468         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7469     }
7470     if (arm_feature(env, ARM_FEATURE_V6K)) {
7471         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7472     }
7473     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7474         !arm_feature(env, ARM_FEATURE_PMSA)) {
7475         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7476     }
7477     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7478         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7479     }
7480     if (arm_feature(env, ARM_FEATURE_V7)) {
7481         ARMCPRegInfo clidr = {
7482             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7483             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7484             .access = PL1_R, .type = ARM_CP_CONST,
7485             .accessfn = access_aa64_tid2,
7486             .resetvalue = cpu->clidr
7487         };
7488         define_one_arm_cp_reg(cpu, &clidr);
7489         define_arm_cp_regs(cpu, v7_cp_reginfo);
7490         define_debug_regs(cpu);
7491         define_pmu_regs(cpu);
7492     } else {
7493         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7494     }
7495     if (arm_feature(env, ARM_FEATURE_V8)) {
7496         /* AArch64 ID registers, which all have impdef reset values.
7497          * Note that within the ID register ranges the unused slots
7498          * must all RAZ, not UNDEF; future architecture versions may
7499          * define new registers here.
7500          */
7501         ARMCPRegInfo v8_idregs[] = {
7502             /*
7503              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7504              * emulation because we don't know the right value for the
7505              * GIC field until after we define these regs.
7506              */
7507             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7508               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7509               .access = PL1_R,
7510 #ifdef CONFIG_USER_ONLY
7511               .type = ARM_CP_CONST,
7512               .resetvalue = cpu->isar.id_aa64pfr0
7513 #else
7514               .type = ARM_CP_NO_RAW,
7515               .accessfn = access_aa64_tid3,
7516               .readfn = id_aa64pfr0_read,
7517               .writefn = arm_cp_write_ignore
7518 #endif
7519             },
7520             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7521               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7522               .access = PL1_R, .type = ARM_CP_CONST,
7523               .accessfn = access_aa64_tid3,
7524               .resetvalue = cpu->isar.id_aa64pfr1},
7525             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7526               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7527               .access = PL1_R, .type = ARM_CP_CONST,
7528               .accessfn = access_aa64_tid3,
7529               .resetvalue = 0 },
7530             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7531               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7532               .access = PL1_R, .type = ARM_CP_CONST,
7533               .accessfn = access_aa64_tid3,
7534               .resetvalue = 0 },
7535             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7536               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7537               .access = PL1_R, .type = ARM_CP_CONST,
7538               .accessfn = access_aa64_tid3,
7539               .resetvalue = cpu->isar.id_aa64zfr0 },
7540             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7541               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7542               .access = PL1_R, .type = ARM_CP_CONST,
7543               .accessfn = access_aa64_tid3,
7544               .resetvalue = 0 },
7545             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7546               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7547               .access = PL1_R, .type = ARM_CP_CONST,
7548               .accessfn = access_aa64_tid3,
7549               .resetvalue = 0 },
7550             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7551               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7552               .access = PL1_R, .type = ARM_CP_CONST,
7553               .accessfn = access_aa64_tid3,
7554               .resetvalue = 0 },
7555             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7556               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7557               .access = PL1_R, .type = ARM_CP_CONST,
7558               .accessfn = access_aa64_tid3,
7559               .resetvalue = cpu->isar.id_aa64dfr0 },
7560             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7561               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7562               .access = PL1_R, .type = ARM_CP_CONST,
7563               .accessfn = access_aa64_tid3,
7564               .resetvalue = cpu->isar.id_aa64dfr1 },
7565             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7566               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7567               .access = PL1_R, .type = ARM_CP_CONST,
7568               .accessfn = access_aa64_tid3,
7569               .resetvalue = 0 },
7570             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7571               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7572               .access = PL1_R, .type = ARM_CP_CONST,
7573               .accessfn = access_aa64_tid3,
7574               .resetvalue = 0 },
7575             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7576               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7577               .access = PL1_R, .type = ARM_CP_CONST,
7578               .accessfn = access_aa64_tid3,
7579               .resetvalue = cpu->id_aa64afr0 },
7580             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7581               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7582               .access = PL1_R, .type = ARM_CP_CONST,
7583               .accessfn = access_aa64_tid3,
7584               .resetvalue = cpu->id_aa64afr1 },
7585             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7586               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7587               .access = PL1_R, .type = ARM_CP_CONST,
7588               .accessfn = access_aa64_tid3,
7589               .resetvalue = 0 },
7590             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7591               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7592               .access = PL1_R, .type = ARM_CP_CONST,
7593               .accessfn = access_aa64_tid3,
7594               .resetvalue = 0 },
7595             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7596               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7597               .access = PL1_R, .type = ARM_CP_CONST,
7598               .accessfn = access_aa64_tid3,
7599               .resetvalue = cpu->isar.id_aa64isar0 },
7600             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7601               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7602               .access = PL1_R, .type = ARM_CP_CONST,
7603               .accessfn = access_aa64_tid3,
7604               .resetvalue = cpu->isar.id_aa64isar1 },
7605             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7606               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7607               .access = PL1_R, .type = ARM_CP_CONST,
7608               .accessfn = access_aa64_tid3,
7609               .resetvalue = 0 },
7610             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7611               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7612               .access = PL1_R, .type = ARM_CP_CONST,
7613               .accessfn = access_aa64_tid3,
7614               .resetvalue = 0 },
7615             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7616               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7617               .access = PL1_R, .type = ARM_CP_CONST,
7618               .accessfn = access_aa64_tid3,
7619               .resetvalue = 0 },
7620             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7621               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7622               .access = PL1_R, .type = ARM_CP_CONST,
7623               .accessfn = access_aa64_tid3,
7624               .resetvalue = 0 },
7625             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7626               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7627               .access = PL1_R, .type = ARM_CP_CONST,
7628               .accessfn = access_aa64_tid3,
7629               .resetvalue = 0 },
7630             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7631               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7632               .access = PL1_R, .type = ARM_CP_CONST,
7633               .accessfn = access_aa64_tid3,
7634               .resetvalue = 0 },
7635             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7636               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7637               .access = PL1_R, .type = ARM_CP_CONST,
7638               .accessfn = access_aa64_tid3,
7639               .resetvalue = cpu->isar.id_aa64mmfr0 },
7640             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7641               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7642               .access = PL1_R, .type = ARM_CP_CONST,
7643               .accessfn = access_aa64_tid3,
7644               .resetvalue = cpu->isar.id_aa64mmfr1 },
7645             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7646               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7647               .access = PL1_R, .type = ARM_CP_CONST,
7648               .accessfn = access_aa64_tid3,
7649               .resetvalue = cpu->isar.id_aa64mmfr2 },
7650             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7651               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7652               .access = PL1_R, .type = ARM_CP_CONST,
7653               .accessfn = access_aa64_tid3,
7654               .resetvalue = 0 },
7655             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7656               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7657               .access = PL1_R, .type = ARM_CP_CONST,
7658               .accessfn = access_aa64_tid3,
7659               .resetvalue = 0 },
7660             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7661               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7662               .access = PL1_R, .type = ARM_CP_CONST,
7663               .accessfn = access_aa64_tid3,
7664               .resetvalue = 0 },
7665             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7666               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7667               .access = PL1_R, .type = ARM_CP_CONST,
7668               .accessfn = access_aa64_tid3,
7669               .resetvalue = 0 },
7670             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7671               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7672               .access = PL1_R, .type = ARM_CP_CONST,
7673               .accessfn = access_aa64_tid3,
7674               .resetvalue = 0 },
7675             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7676               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7677               .access = PL1_R, .type = ARM_CP_CONST,
7678               .accessfn = access_aa64_tid3,
7679               .resetvalue = cpu->isar.mvfr0 },
7680             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7681               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7682               .access = PL1_R, .type = ARM_CP_CONST,
7683               .accessfn = access_aa64_tid3,
7684               .resetvalue = cpu->isar.mvfr1 },
7685             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7686               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7687               .access = PL1_R, .type = ARM_CP_CONST,
7688               .accessfn = access_aa64_tid3,
7689               .resetvalue = cpu->isar.mvfr2 },
7690             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7691               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7692               .access = PL1_R, .type = ARM_CP_CONST,
7693               .accessfn = access_aa64_tid3,
7694               .resetvalue = 0 },
7695             { .name = "ID_PFR2", .state = ARM_CP_STATE_BOTH,
7696               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7697               .access = PL1_R, .type = ARM_CP_CONST,
7698               .accessfn = access_aa64_tid3,
7699               .resetvalue = cpu->isar.id_pfr2 },
7700             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7701               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7702               .access = PL1_R, .type = ARM_CP_CONST,
7703               .accessfn = access_aa64_tid3,
7704               .resetvalue = 0 },
7705             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7706               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7707               .access = PL1_R, .type = ARM_CP_CONST,
7708               .accessfn = access_aa64_tid3,
7709               .resetvalue = 0 },
7710             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7711               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7712               .access = PL1_R, .type = ARM_CP_CONST,
7713               .accessfn = access_aa64_tid3,
7714               .resetvalue = 0 },
7715             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7716               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7717               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7718               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7719             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7720               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7721               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7722               .resetvalue = cpu->pmceid0 },
7723             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7724               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7725               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7726               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7727             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7728               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7729               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7730               .resetvalue = cpu->pmceid1 },
7731         };
7732 #ifdef CONFIG_USER_ONLY
7733         static const ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7734             { .name = "ID_AA64PFR0_EL1",
7735               .exported_bits = 0x000f000f00ff0000,
7736               .fixed_bits    = 0x0000000000000011 },
7737             { .name = "ID_AA64PFR1_EL1",
7738               .exported_bits = 0x00000000000000f0 },
7739             { .name = "ID_AA64PFR*_EL1_RESERVED",
7740               .is_glob = true                     },
7741             { .name = "ID_AA64ZFR0_EL1"           },
7742             { .name = "ID_AA64MMFR0_EL1",
7743               .fixed_bits    = 0x00000000ff000000 },
7744             { .name = "ID_AA64MMFR1_EL1"          },
7745             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7746               .is_glob = true                     },
7747             { .name = "ID_AA64DFR0_EL1",
7748               .fixed_bits    = 0x0000000000000006 },
7749             { .name = "ID_AA64DFR1_EL1"           },
7750             { .name = "ID_AA64DFR*_EL1_RESERVED",
7751               .is_glob = true                     },
7752             { .name = "ID_AA64AFR*",
7753               .is_glob = true                     },
7754             { .name = "ID_AA64ISAR0_EL1",
7755               .exported_bits = 0x00fffffff0fffff0 },
7756             { .name = "ID_AA64ISAR1_EL1",
7757               .exported_bits = 0x000000f0ffffffff },
7758             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7759               .is_glob = true                     },
7760         };
7761         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7762 #endif
7763         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7764         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7765             !arm_feature(env, ARM_FEATURE_EL2)) {
7766             ARMCPRegInfo rvbar = {
7767                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7768                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7769                 .access = PL1_R,
7770                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7771             };
7772             define_one_arm_cp_reg(cpu, &rvbar);
7773         }
7774         define_arm_cp_regs(cpu, v8_idregs);
7775         define_arm_cp_regs(cpu, v8_cp_reginfo);
7776     }
7777 
7778     /*
7779      * Register the base EL2 cpregs.
7780      * Pre v8, these registers are implemented only as part of the
7781      * Virtualization Extensions (EL2 present).  Beginning with v8,
7782      * if EL2 is missing but EL3 is enabled, mostly these become
7783      * RES0 from EL3, with some specific exceptions.
7784      */
7785     if (arm_feature(env, ARM_FEATURE_EL2)
7786         || (arm_feature(env, ARM_FEATURE_EL3)
7787             && arm_feature(env, ARM_FEATURE_V8))) {
7788         uint64_t vmpidr_def = mpidr_read_val(env);
7789         ARMCPRegInfo vpidr_regs[] = {
7790             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7791               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7792               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7793               .resetvalue = cpu->midr,
7794               .type = ARM_CP_ALIAS | ARM_CP_EL3_NO_EL2_C_NZ,
7795               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7796             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7797               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7798               .access = PL2_RW, .resetvalue = cpu->midr,
7799               .type = ARM_CP_EL3_NO_EL2_C_NZ,
7800               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7801             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7802               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7803               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7804               .resetvalue = vmpidr_def,
7805               .type = ARM_CP_ALIAS | ARM_CP_EL3_NO_EL2_C_NZ,
7806               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7807             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7808               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7809               .access = PL2_RW, .resetvalue = vmpidr_def,
7810               .type = ARM_CP_EL3_NO_EL2_C_NZ,
7811               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7812         };
7813         define_arm_cp_regs(cpu, vpidr_regs);
7814         define_arm_cp_regs(cpu, el2_cp_reginfo);
7815         if (arm_feature(env, ARM_FEATURE_V8)) {
7816             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7817         }
7818         if (cpu_isar_feature(aa64_sel2, cpu)) {
7819             define_arm_cp_regs(cpu, el2_sec_cp_reginfo);
7820         }
7821         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7822         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7823             ARMCPRegInfo rvbar = {
7824                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
7825                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
7826                 .access = PL2_R,
7827                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7828             };
7829             define_one_arm_cp_reg(cpu, &rvbar);
7830         }
7831     }
7832 
7833     /* Register the base EL3 cpregs. */
7834     if (arm_feature(env, ARM_FEATURE_EL3)) {
7835         define_arm_cp_regs(cpu, el3_cp_reginfo);
7836         ARMCPRegInfo el3_regs[] = {
7837             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
7838               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
7839               .access = PL3_R,
7840               .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7841             },
7842             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
7843               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
7844               .access = PL3_RW,
7845               .raw_writefn = raw_write, .writefn = sctlr_write,
7846               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
7847               .resetvalue = cpu->reset_sctlr },
7848         };
7849 
7850         define_arm_cp_regs(cpu, el3_regs);
7851     }
7852     /* The behaviour of NSACR is sufficiently various that we don't
7853      * try to describe it in a single reginfo:
7854      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
7855      *     reads as constant 0xc00 from NS EL1 and NS EL2
7856      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
7857      *  if v7 without EL3, register doesn't exist
7858      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
7859      */
7860     if (arm_feature(env, ARM_FEATURE_EL3)) {
7861         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7862             static const ARMCPRegInfo nsacr = {
7863                 .name = "NSACR", .type = ARM_CP_CONST,
7864                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7865                 .access = PL1_RW, .accessfn = nsacr_access,
7866                 .resetvalue = 0xc00
7867             };
7868             define_one_arm_cp_reg(cpu, &nsacr);
7869         } else {
7870             static const ARMCPRegInfo nsacr = {
7871                 .name = "NSACR",
7872                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7873                 .access = PL3_RW | PL1_R,
7874                 .resetvalue = 0,
7875                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
7876             };
7877             define_one_arm_cp_reg(cpu, &nsacr);
7878         }
7879     } else {
7880         if (arm_feature(env, ARM_FEATURE_V8)) {
7881             static const ARMCPRegInfo nsacr = {
7882                 .name = "NSACR", .type = ARM_CP_CONST,
7883                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7884                 .access = PL1_R,
7885                 .resetvalue = 0xc00
7886             };
7887             define_one_arm_cp_reg(cpu, &nsacr);
7888         }
7889     }
7890 
7891     if (arm_feature(env, ARM_FEATURE_PMSA)) {
7892         if (arm_feature(env, ARM_FEATURE_V6)) {
7893             /* PMSAv6 not implemented */
7894             assert(arm_feature(env, ARM_FEATURE_V7));
7895             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7896             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
7897         } else {
7898             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
7899         }
7900     } else {
7901         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7902         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
7903         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
7904         if (cpu_isar_feature(aa32_hpd, cpu)) {
7905             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
7906         }
7907     }
7908     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
7909         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
7910     }
7911     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
7912         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
7913     }
7914     if (arm_feature(env, ARM_FEATURE_VAPA)) {
7915         define_arm_cp_regs(cpu, vapa_cp_reginfo);
7916     }
7917     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
7918         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
7919     }
7920     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
7921         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
7922     }
7923     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
7924         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
7925     }
7926     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
7927         define_arm_cp_regs(cpu, omap_cp_reginfo);
7928     }
7929     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
7930         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
7931     }
7932     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7933         define_arm_cp_regs(cpu, xscale_cp_reginfo);
7934     }
7935     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
7936         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
7937     }
7938     if (arm_feature(env, ARM_FEATURE_LPAE)) {
7939         define_arm_cp_regs(cpu, lpae_cp_reginfo);
7940     }
7941     if (cpu_isar_feature(aa32_jazelle, cpu)) {
7942         define_arm_cp_regs(cpu, jazelle_regs);
7943     }
7944     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
7945      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
7946      * be read-only (ie write causes UNDEF exception).
7947      */
7948     {
7949         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
7950             /* Pre-v8 MIDR space.
7951              * Note that the MIDR isn't a simple constant register because
7952              * of the TI925 behaviour where writes to another register can
7953              * cause the MIDR value to change.
7954              *
7955              * Unimplemented registers in the c15 0 0 0 space default to
7956              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
7957              * and friends override accordingly.
7958              */
7959             { .name = "MIDR",
7960               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
7961               .access = PL1_R, .resetvalue = cpu->midr,
7962               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
7963               .readfn = midr_read,
7964               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7965               .type = ARM_CP_OVERRIDE },
7966             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
7967             { .name = "DUMMY",
7968               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
7969               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7970             { .name = "DUMMY",
7971               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
7972               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7973             { .name = "DUMMY",
7974               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
7975               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7976             { .name = "DUMMY",
7977               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
7978               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7979             { .name = "DUMMY",
7980               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
7981               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7982         };
7983         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
7984             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
7985               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
7986               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
7987               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7988               .readfn = midr_read },
7989             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
7990             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7991               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
7992               .access = PL1_R, .resetvalue = cpu->midr },
7993             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7994               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
7995               .access = PL1_R, .resetvalue = cpu->midr },
7996             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
7997               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
7998               .access = PL1_R,
7999               .accessfn = access_aa64_tid1,
8000               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
8001         };
8002         ARMCPRegInfo id_cp_reginfo[] = {
8003             /* These are common to v8 and pre-v8 */
8004             { .name = "CTR",
8005               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
8006               .access = PL1_R, .accessfn = ctr_el0_access,
8007               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8008             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
8009               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
8010               .access = PL0_R, .accessfn = ctr_el0_access,
8011               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8012             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
8013             { .name = "TCMTR",
8014               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
8015               .access = PL1_R,
8016               .accessfn = access_aa32_tid1,
8017               .type = ARM_CP_CONST, .resetvalue = 0 },
8018         };
8019         /* TLBTR is specific to VMSA */
8020         ARMCPRegInfo id_tlbtr_reginfo = {
8021               .name = "TLBTR",
8022               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
8023               .access = PL1_R,
8024               .accessfn = access_aa32_tid1,
8025               .type = ARM_CP_CONST, .resetvalue = 0,
8026         };
8027         /* MPUIR is specific to PMSA V6+ */
8028         ARMCPRegInfo id_mpuir_reginfo = {
8029               .name = "MPUIR",
8030               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8031               .access = PL1_R, .type = ARM_CP_CONST,
8032               .resetvalue = cpu->pmsav7_dregion << 8
8033         };
8034         static const ARMCPRegInfo crn0_wi_reginfo = {
8035             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
8036             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
8037             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
8038         };
8039 #ifdef CONFIG_USER_ONLY
8040         static const ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
8041             { .name = "MIDR_EL1",
8042               .exported_bits = 0x00000000ffffffff },
8043             { .name = "REVIDR_EL1"                },
8044         };
8045         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
8046 #endif
8047         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
8048             arm_feature(env, ARM_FEATURE_STRONGARM)) {
8049             size_t i;
8050             /* Register the blanket "writes ignored" value first to cover the
8051              * whole space. Then update the specific ID registers to allow write
8052              * access, so that they ignore writes rather than causing them to
8053              * UNDEF.
8054              */
8055             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
8056             for (i = 0; i < ARRAY_SIZE(id_pre_v8_midr_cp_reginfo); ++i) {
8057                 id_pre_v8_midr_cp_reginfo[i].access = PL1_RW;
8058             }
8059             for (i = 0; i < ARRAY_SIZE(id_cp_reginfo); ++i) {
8060                 id_cp_reginfo[i].access = PL1_RW;
8061             }
8062             id_mpuir_reginfo.access = PL1_RW;
8063             id_tlbtr_reginfo.access = PL1_RW;
8064         }
8065         if (arm_feature(env, ARM_FEATURE_V8)) {
8066             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
8067         } else {
8068             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
8069         }
8070         define_arm_cp_regs(cpu, id_cp_reginfo);
8071         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
8072             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
8073         } else if (arm_feature(env, ARM_FEATURE_V7)) {
8074             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
8075         }
8076     }
8077 
8078     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
8079         ARMCPRegInfo mpidr_cp_reginfo[] = {
8080             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
8081               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
8082               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
8083         };
8084 #ifdef CONFIG_USER_ONLY
8085         static const ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
8086             { .name = "MPIDR_EL1",
8087               .fixed_bits = 0x0000000080000000 },
8088         };
8089         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
8090 #endif
8091         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
8092     }
8093 
8094     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
8095         ARMCPRegInfo auxcr_reginfo[] = {
8096             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
8097               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
8098               .access = PL1_RW, .accessfn = access_tacr,
8099               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
8100             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
8101               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
8102               .access = PL2_RW, .type = ARM_CP_CONST,
8103               .resetvalue = 0 },
8104             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8105               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8106               .access = PL3_RW, .type = ARM_CP_CONST,
8107               .resetvalue = 0 },
8108         };
8109         define_arm_cp_regs(cpu, auxcr_reginfo);
8110         if (cpu_isar_feature(aa32_ac2, cpu)) {
8111             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8112         }
8113     }
8114 
8115     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8116         /*
8117          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8118          * There are two flavours:
8119          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8120          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8121          *      32-bit register visible to AArch32 at a different encoding
8122          *      to the "flavour 1" register and with the bits rearranged to
8123          *      be able to squash a 64-bit address into the 32-bit view.
8124          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8125          * in future if we support AArch32-only configs of some of the
8126          * AArch64 cores we might need to add a specific feature flag
8127          * to indicate cores with "flavour 2" CBAR.
8128          */
8129         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8130             /* 32 bit view is [31:18] 0...0 [43:32]. */
8131             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8132                 | extract64(cpu->reset_cbar, 32, 12);
8133             ARMCPRegInfo cbar_reginfo[] = {
8134                 { .name = "CBAR",
8135                   .type = ARM_CP_CONST,
8136                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8137                   .access = PL1_R, .resetvalue = cbar32 },
8138                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8139                   .type = ARM_CP_CONST,
8140                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8141                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8142             };
8143             /* We don't implement a r/w 64 bit CBAR currently */
8144             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8145             define_arm_cp_regs(cpu, cbar_reginfo);
8146         } else {
8147             ARMCPRegInfo cbar = {
8148                 .name = "CBAR",
8149                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8150                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8151                 .fieldoffset = offsetof(CPUARMState,
8152                                         cp15.c15_config_base_address)
8153             };
8154             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8155                 cbar.access = PL1_R;
8156                 cbar.fieldoffset = 0;
8157                 cbar.type = ARM_CP_CONST;
8158             }
8159             define_one_arm_cp_reg(cpu, &cbar);
8160         }
8161     }
8162 
8163     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8164         static const ARMCPRegInfo vbar_cp_reginfo[] = {
8165             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8166               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8167               .access = PL1_RW, .writefn = vbar_write,
8168               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8169                                      offsetof(CPUARMState, cp15.vbar_ns) },
8170               .resetvalue = 0 },
8171         };
8172         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8173     }
8174 
8175     /* Generic registers whose values depend on the implementation */
8176     {
8177         ARMCPRegInfo sctlr = {
8178             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8179             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8180             .access = PL1_RW, .accessfn = access_tvm_trvm,
8181             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8182                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8183             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8184             .raw_writefn = raw_write,
8185         };
8186         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8187             /* Normally we would always end the TB on an SCTLR write, but Linux
8188              * arch/arm/mach-pxa/sleep.S expects two instructions following
8189              * an MMU enable to execute from cache.  Imitate this behaviour.
8190              */
8191             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8192         }
8193         define_one_arm_cp_reg(cpu, &sctlr);
8194     }
8195 
8196     if (cpu_isar_feature(aa64_lor, cpu)) {
8197         define_arm_cp_regs(cpu, lor_reginfo);
8198     }
8199     if (cpu_isar_feature(aa64_pan, cpu)) {
8200         define_one_arm_cp_reg(cpu, &pan_reginfo);
8201     }
8202 #ifndef CONFIG_USER_ONLY
8203     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8204         define_arm_cp_regs(cpu, ats1e1_reginfo);
8205     }
8206     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8207         define_arm_cp_regs(cpu, ats1cp_reginfo);
8208     }
8209 #endif
8210     if (cpu_isar_feature(aa64_uao, cpu)) {
8211         define_one_arm_cp_reg(cpu, &uao_reginfo);
8212     }
8213 
8214     if (cpu_isar_feature(aa64_dit, cpu)) {
8215         define_one_arm_cp_reg(cpu, &dit_reginfo);
8216     }
8217     if (cpu_isar_feature(aa64_ssbs, cpu)) {
8218         define_one_arm_cp_reg(cpu, &ssbs_reginfo);
8219     }
8220 
8221     if (cpu_isar_feature(aa64_vh, cpu) ||
8222         cpu_isar_feature(aa64_debugv8p2, cpu)) {
8223         define_one_arm_cp_reg(cpu, &contextidr_el2);
8224     }
8225     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8226         define_arm_cp_regs(cpu, vhe_reginfo);
8227     }
8228 
8229     if (cpu_isar_feature(aa64_sve, cpu)) {
8230         define_arm_cp_regs(cpu, zcr_reginfo);
8231     }
8232 
8233 #ifdef TARGET_AARCH64
8234     if (cpu_isar_feature(aa64_pauth, cpu)) {
8235         define_arm_cp_regs(cpu, pauth_reginfo);
8236     }
8237     if (cpu_isar_feature(aa64_rndr, cpu)) {
8238         define_arm_cp_regs(cpu, rndr_reginfo);
8239     }
8240     if (cpu_isar_feature(aa64_tlbirange, cpu)) {
8241         define_arm_cp_regs(cpu, tlbirange_reginfo);
8242     }
8243     if (cpu_isar_feature(aa64_tlbios, cpu)) {
8244         define_arm_cp_regs(cpu, tlbios_reginfo);
8245     }
8246 #ifndef CONFIG_USER_ONLY
8247     /* Data Cache clean instructions up to PoP */
8248     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8249         define_one_arm_cp_reg(cpu, dcpop_reg);
8250 
8251         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8252             define_one_arm_cp_reg(cpu, dcpodp_reg);
8253         }
8254     }
8255 #endif /*CONFIG_USER_ONLY*/
8256 
8257     /*
8258      * If full MTE is enabled, add all of the system registers.
8259      * If only "instructions available at EL0" are enabled,
8260      * then define only a RAZ/WI version of PSTATE.TCO.
8261      */
8262     if (cpu_isar_feature(aa64_mte, cpu)) {
8263         define_arm_cp_regs(cpu, mte_reginfo);
8264         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8265     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8266         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8267         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8268     }
8269 #endif
8270 
8271     if (cpu_isar_feature(any_predinv, cpu)) {
8272         define_arm_cp_regs(cpu, predinv_reginfo);
8273     }
8274 
8275     if (cpu_isar_feature(any_ccidx, cpu)) {
8276         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8277     }
8278 
8279 #ifndef CONFIG_USER_ONLY
8280     /*
8281      * Register redirections and aliases must be done last,
8282      * after the registers from the other extensions have been defined.
8283      */
8284     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8285         define_arm_vh_e2h_redirects_aliases(cpu);
8286     }
8287 #endif
8288 }
8289 
8290 /* Sort alphabetically by type name, except for "any". */
8291 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8292 {
8293     ObjectClass *class_a = (ObjectClass *)a;
8294     ObjectClass *class_b = (ObjectClass *)b;
8295     const char *name_a, *name_b;
8296 
8297     name_a = object_class_get_name(class_a);
8298     name_b = object_class_get_name(class_b);
8299     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8300         return 1;
8301     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8302         return -1;
8303     } else {
8304         return strcmp(name_a, name_b);
8305     }
8306 }
8307 
8308 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8309 {
8310     ObjectClass *oc = data;
8311     const char *typename;
8312     char *name;
8313 
8314     typename = object_class_get_name(oc);
8315     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8316     qemu_printf("  %s\n", name);
8317     g_free(name);
8318 }
8319 
8320 void arm_cpu_list(void)
8321 {
8322     GSList *list;
8323 
8324     list = object_class_get_list(TYPE_ARM_CPU, false);
8325     list = g_slist_sort(list, arm_cpu_list_compare);
8326     qemu_printf("Available CPUs:\n");
8327     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8328     g_slist_free(list);
8329 }
8330 
8331 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8332 {
8333     ObjectClass *oc = data;
8334     CpuDefinitionInfoList **cpu_list = user_data;
8335     CpuDefinitionInfo *info;
8336     const char *typename;
8337 
8338     typename = object_class_get_name(oc);
8339     info = g_malloc0(sizeof(*info));
8340     info->name = g_strndup(typename,
8341                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8342     info->q_typename = g_strdup(typename);
8343 
8344     QAPI_LIST_PREPEND(*cpu_list, info);
8345 }
8346 
8347 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8348 {
8349     CpuDefinitionInfoList *cpu_list = NULL;
8350     GSList *list;
8351 
8352     list = object_class_get_list(TYPE_ARM_CPU, false);
8353     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8354     g_slist_free(list);
8355 
8356     return cpu_list;
8357 }
8358 
8359 /*
8360  * Private utility function for define_one_arm_cp_reg_with_opaque():
8361  * add a single reginfo struct to the hash table.
8362  */
8363 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8364                                    void *opaque, CPState state,
8365                                    CPSecureState secstate,
8366                                    int crm, int opc1, int opc2,
8367                                    const char *name)
8368 {
8369     CPUARMState *env = &cpu->env;
8370     uint32_t key;
8371     ARMCPRegInfo *r2;
8372     bool is64 = r->type & ARM_CP_64BIT;
8373     bool ns = secstate & ARM_CP_SECSTATE_NS;
8374     int cp = r->cp;
8375     size_t name_len;
8376     bool make_const;
8377 
8378     switch (state) {
8379     case ARM_CP_STATE_AA32:
8380         /* We assume it is a cp15 register if the .cp field is left unset. */
8381         if (cp == 0 && r->state == ARM_CP_STATE_BOTH) {
8382             cp = 15;
8383         }
8384         key = ENCODE_CP_REG(cp, is64, ns, r->crn, crm, opc1, opc2);
8385         break;
8386     case ARM_CP_STATE_AA64:
8387         /*
8388          * To allow abbreviation of ARMCPRegInfo definitions, we treat
8389          * cp == 0 as equivalent to the value for "standard guest-visible
8390          * sysreg".  STATE_BOTH definitions are also always "standard sysreg"
8391          * in their AArch64 view (the .cp value may be non-zero for the
8392          * benefit of the AArch32 view).
8393          */
8394         if (cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8395             cp = CP_REG_ARM64_SYSREG_CP;
8396         }
8397         key = ENCODE_AA64_CP_REG(cp, r->crn, crm, r->opc0, opc1, opc2);
8398         break;
8399     default:
8400         g_assert_not_reached();
8401     }
8402 
8403     /* Overriding of an existing definition must be explicitly requested. */
8404     if (!(r->type & ARM_CP_OVERRIDE)) {
8405         const ARMCPRegInfo *oldreg = get_arm_cp_reginfo(cpu->cp_regs, key);
8406         if (oldreg) {
8407             assert(oldreg->type & ARM_CP_OVERRIDE);
8408         }
8409     }
8410 
8411     /*
8412      * Eliminate registers that are not present because the EL is missing.
8413      * Doing this here makes it easier to put all registers for a given
8414      * feature into the same ARMCPRegInfo array and define them all at once.
8415      */
8416     make_const = false;
8417     if (arm_feature(env, ARM_FEATURE_EL3)) {
8418         /*
8419          * An EL2 register without EL2 but with EL3 is (usually) RES0.
8420          * See rule RJFFP in section D1.1.3 of DDI0487H.a.
8421          */
8422         int min_el = ctz32(r->access) / 2;
8423         if (min_el == 2 && !arm_feature(env, ARM_FEATURE_EL2)) {
8424             if (r->type & ARM_CP_EL3_NO_EL2_UNDEF) {
8425                 return;
8426             }
8427             make_const = !(r->type & ARM_CP_EL3_NO_EL2_KEEP);
8428         }
8429     } else {
8430         CPAccessRights max_el = (arm_feature(env, ARM_FEATURE_EL2)
8431                                  ? PL2_RW : PL1_RW);
8432         if ((r->access & max_el) == 0) {
8433             return;
8434         }
8435     }
8436 
8437     /* Combine cpreg and name into one allocation. */
8438     name_len = strlen(name) + 1;
8439     r2 = g_malloc(sizeof(*r2) + name_len);
8440     *r2 = *r;
8441     r2->name = memcpy(r2 + 1, name, name_len);
8442 
8443     /*
8444      * Update fields to match the instantiation, overwiting wildcards
8445      * such as CP_ANY, ARM_CP_STATE_BOTH, or ARM_CP_SECSTATE_BOTH.
8446      */
8447     r2->cp = cp;
8448     r2->crm = crm;
8449     r2->opc1 = opc1;
8450     r2->opc2 = opc2;
8451     r2->state = state;
8452     r2->secure = secstate;
8453     if (opaque) {
8454         r2->opaque = opaque;
8455     }
8456 
8457     if (make_const) {
8458         /* This should not have been a very special register to begin. */
8459         int old_special = r2->type & ARM_CP_SPECIAL_MASK;
8460         assert(old_special == 0 || old_special == ARM_CP_NOP);
8461         /*
8462          * Set the special function to CONST, retaining the other flags.
8463          * This is important for e.g. ARM_CP_SVE so that we still
8464          * take the SVE trap if CPTR_EL3.EZ == 0.
8465          */
8466         r2->type = (r2->type & ~ARM_CP_SPECIAL_MASK) | ARM_CP_CONST;
8467         /*
8468          * Usually, these registers become RES0, but there are a few
8469          * special cases like VPIDR_EL2 which have a constant non-zero
8470          * value with writes ignored.
8471          */
8472         if (!(r->type & ARM_CP_EL3_NO_EL2_C_NZ)) {
8473             r2->resetvalue = 0;
8474         }
8475         /*
8476          * ARM_CP_CONST has precedence, so removing the callbacks and
8477          * offsets are not strictly necessary, but it is potentially
8478          * less confusing to debug later.
8479          */
8480         r2->readfn = NULL;
8481         r2->writefn = NULL;
8482         r2->raw_readfn = NULL;
8483         r2->raw_writefn = NULL;
8484         r2->resetfn = NULL;
8485         r2->fieldoffset = 0;
8486         r2->bank_fieldoffsets[0] = 0;
8487         r2->bank_fieldoffsets[1] = 0;
8488     } else {
8489         bool isbanked = r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1];
8490 
8491         if (isbanked) {
8492             /*
8493              * Register is banked (using both entries in array).
8494              * Overwriting fieldoffset as the array is only used to define
8495              * banked registers but later only fieldoffset is used.
8496              */
8497             r2->fieldoffset = r->bank_fieldoffsets[ns];
8498         }
8499         if (state == ARM_CP_STATE_AA32) {
8500             if (isbanked) {
8501                 /*
8502                  * If the register is banked then we don't need to migrate or
8503                  * reset the 32-bit instance in certain cases:
8504                  *
8505                  * 1) If the register has both 32-bit and 64-bit instances
8506                  *    then we can count on the 64-bit instance taking care
8507                  *    of the non-secure bank.
8508                  * 2) If ARMv8 is enabled then we can count on a 64-bit
8509                  *    version taking care of the secure bank.  This requires
8510                  *    that separate 32 and 64-bit definitions are provided.
8511                  */
8512                 if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8513                     (arm_feature(env, ARM_FEATURE_V8) && !ns)) {
8514                     r2->type |= ARM_CP_ALIAS;
8515                 }
8516             } else if ((secstate != r->secure) && !ns) {
8517                 /*
8518                  * The register is not banked so we only want to allow
8519                  * migration of the non-secure instance.
8520                  */
8521                 r2->type |= ARM_CP_ALIAS;
8522             }
8523 
8524             if (HOST_BIG_ENDIAN &&
8525                 r->state == ARM_CP_STATE_BOTH && r2->fieldoffset) {
8526                 r2->fieldoffset += sizeof(uint32_t);
8527             }
8528         }
8529     }
8530 
8531     /*
8532      * By convention, for wildcarded registers only the first
8533      * entry is used for migration; the others are marked as
8534      * ALIAS so we don't try to transfer the register
8535      * multiple times. Special registers (ie NOP/WFI) are
8536      * never migratable and not even raw-accessible.
8537      */
8538     if (r2->type & ARM_CP_SPECIAL_MASK) {
8539         r2->type |= ARM_CP_NO_RAW;
8540     }
8541     if (((r->crm == CP_ANY) && crm != 0) ||
8542         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8543         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8544         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8545     }
8546 
8547     /*
8548      * Check that raw accesses are either forbidden or handled. Note that
8549      * we can't assert this earlier because the setup of fieldoffset for
8550      * banked registers has to be done first.
8551      */
8552     if (!(r2->type & ARM_CP_NO_RAW)) {
8553         assert(!raw_accessors_invalid(r2));
8554     }
8555 
8556     g_hash_table_insert(cpu->cp_regs, (gpointer)(uintptr_t)key, r2);
8557 }
8558 
8559 
8560 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8561                                        const ARMCPRegInfo *r, void *opaque)
8562 {
8563     /* Define implementations of coprocessor registers.
8564      * We store these in a hashtable because typically
8565      * there are less than 150 registers in a space which
8566      * is 16*16*16*8*8 = 262144 in size.
8567      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8568      * If a register is defined twice then the second definition is
8569      * used, so this can be used to define some generic registers and
8570      * then override them with implementation specific variations.
8571      * At least one of the original and the second definition should
8572      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8573      * against accidental use.
8574      *
8575      * The state field defines whether the register is to be
8576      * visible in the AArch32 or AArch64 execution state. If the
8577      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8578      * reginfo structure for the AArch32 view, which sees the lower
8579      * 32 bits of the 64 bit register.
8580      *
8581      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8582      * be wildcarded. AArch64 registers are always considered to be 64
8583      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8584      * the register, if any.
8585      */
8586     int crm, opc1, opc2;
8587     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8588     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8589     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8590     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8591     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8592     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8593     CPState state;
8594 
8595     /* 64 bit registers have only CRm and Opc1 fields */
8596     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8597     /* op0 only exists in the AArch64 encodings */
8598     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8599     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8600     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8601     /*
8602      * This API is only for Arm's system coprocessors (14 and 15) or
8603      * (M-profile or v7A-and-earlier only) for implementation defined
8604      * coprocessors in the range 0..7.  Our decode assumes this, since
8605      * 8..13 can be used for other insns including VFP and Neon. See
8606      * valid_cp() in translate.c.  Assert here that we haven't tried
8607      * to use an invalid coprocessor number.
8608      */
8609     switch (r->state) {
8610     case ARM_CP_STATE_BOTH:
8611         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8612         if (r->cp == 0) {
8613             break;
8614         }
8615         /* fall through */
8616     case ARM_CP_STATE_AA32:
8617         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8618             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8619             assert(r->cp >= 14 && r->cp <= 15);
8620         } else {
8621             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8622         }
8623         break;
8624     case ARM_CP_STATE_AA64:
8625         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8626         break;
8627     default:
8628         g_assert_not_reached();
8629     }
8630     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8631      * encodes a minimum access level for the register. We roll this
8632      * runtime check into our general permission check code, so check
8633      * here that the reginfo's specified permissions are strict enough
8634      * to encompass the generic architectural permission check.
8635      */
8636     if (r->state != ARM_CP_STATE_AA32) {
8637         CPAccessRights mask;
8638         switch (r->opc1) {
8639         case 0:
8640             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8641             mask = PL0U_R | PL1_RW;
8642             break;
8643         case 1: case 2:
8644             /* min_EL EL1 */
8645             mask = PL1_RW;
8646             break;
8647         case 3:
8648             /* min_EL EL0 */
8649             mask = PL0_RW;
8650             break;
8651         case 4:
8652         case 5:
8653             /* min_EL EL2 */
8654             mask = PL2_RW;
8655             break;
8656         case 6:
8657             /* min_EL EL3 */
8658             mask = PL3_RW;
8659             break;
8660         case 7:
8661             /* min_EL EL1, secure mode only (we don't check the latter) */
8662             mask = PL1_RW;
8663             break;
8664         default:
8665             /* broken reginfo with out-of-range opc1 */
8666             g_assert_not_reached();
8667         }
8668         /* assert our permissions are not too lax (stricter is fine) */
8669         assert((r->access & ~mask) == 0);
8670     }
8671 
8672     /* Check that the register definition has enough info to handle
8673      * reads and writes if they are permitted.
8674      */
8675     if (!(r->type & (ARM_CP_SPECIAL_MASK | ARM_CP_CONST))) {
8676         if (r->access & PL3_R) {
8677             assert((r->fieldoffset ||
8678                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8679                    r->readfn);
8680         }
8681         if (r->access & PL3_W) {
8682             assert((r->fieldoffset ||
8683                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8684                    r->writefn);
8685         }
8686     }
8687 
8688     for (crm = crmmin; crm <= crmmax; crm++) {
8689         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8690             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8691                 for (state = ARM_CP_STATE_AA32;
8692                      state <= ARM_CP_STATE_AA64; state++) {
8693                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8694                         continue;
8695                     }
8696                     if (state == ARM_CP_STATE_AA32) {
8697                         /* Under AArch32 CP registers can be common
8698                          * (same for secure and non-secure world) or banked.
8699                          */
8700                         char *name;
8701 
8702                         switch (r->secure) {
8703                         case ARM_CP_SECSTATE_S:
8704                         case ARM_CP_SECSTATE_NS:
8705                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8706                                                    r->secure, crm, opc1, opc2,
8707                                                    r->name);
8708                             break;
8709                         case ARM_CP_SECSTATE_BOTH:
8710                             name = g_strdup_printf("%s_S", r->name);
8711                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8712                                                    ARM_CP_SECSTATE_S,
8713                                                    crm, opc1, opc2, name);
8714                             g_free(name);
8715                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8716                                                    ARM_CP_SECSTATE_NS,
8717                                                    crm, opc1, opc2, r->name);
8718                             break;
8719                         default:
8720                             g_assert_not_reached();
8721                         }
8722                     } else {
8723                         /* AArch64 registers get mapped to non-secure instance
8724                          * of AArch32 */
8725                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8726                                                ARM_CP_SECSTATE_NS,
8727                                                crm, opc1, opc2, r->name);
8728                     }
8729                 }
8730             }
8731         }
8732     }
8733 }
8734 
8735 /* Define a whole list of registers */
8736 void define_arm_cp_regs_with_opaque_len(ARMCPU *cpu, const ARMCPRegInfo *regs,
8737                                         void *opaque, size_t len)
8738 {
8739     size_t i;
8740     for (i = 0; i < len; ++i) {
8741         define_one_arm_cp_reg_with_opaque(cpu, regs + i, opaque);
8742     }
8743 }
8744 
8745 /*
8746  * Modify ARMCPRegInfo for access from userspace.
8747  *
8748  * This is a data driven modification directed by
8749  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8750  * user-space cannot alter any values and dynamic values pertaining to
8751  * execution state are hidden from user space view anyway.
8752  */
8753 void modify_arm_cp_regs_with_len(ARMCPRegInfo *regs, size_t regs_len,
8754                                  const ARMCPRegUserSpaceInfo *mods,
8755                                  size_t mods_len)
8756 {
8757     for (size_t mi = 0; mi < mods_len; ++mi) {
8758         const ARMCPRegUserSpaceInfo *m = mods + mi;
8759         GPatternSpec *pat = NULL;
8760 
8761         if (m->is_glob) {
8762             pat = g_pattern_spec_new(m->name);
8763         }
8764         for (size_t ri = 0; ri < regs_len; ++ri) {
8765             ARMCPRegInfo *r = regs + ri;
8766 
8767             if (pat && g_pattern_match_string(pat, r->name)) {
8768                 r->type = ARM_CP_CONST;
8769                 r->access = PL0U_R;
8770                 r->resetvalue = 0;
8771                 /* continue */
8772             } else if (strcmp(r->name, m->name) == 0) {
8773                 r->type = ARM_CP_CONST;
8774                 r->access = PL0U_R;
8775                 r->resetvalue &= m->exported_bits;
8776                 r->resetvalue |= m->fixed_bits;
8777                 break;
8778             }
8779         }
8780         if (pat) {
8781             g_pattern_spec_free(pat);
8782         }
8783     }
8784 }
8785 
8786 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8787 {
8788     return g_hash_table_lookup(cpregs, (gpointer)(uintptr_t)encoded_cp);
8789 }
8790 
8791 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8792                          uint64_t value)
8793 {
8794     /* Helper coprocessor write function for write-ignore registers */
8795 }
8796 
8797 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8798 {
8799     /* Helper coprocessor write function for read-as-zero registers */
8800     return 0;
8801 }
8802 
8803 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8804 {
8805     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8806 }
8807 
8808 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8809 {
8810     /* Return true if it is not valid for us to switch to
8811      * this CPU mode (ie all the UNPREDICTABLE cases in
8812      * the ARM ARM CPSRWriteByInstr pseudocode).
8813      */
8814 
8815     /* Changes to or from Hyp via MSR and CPS are illegal. */
8816     if (write_type == CPSRWriteByInstr &&
8817         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8818          mode == ARM_CPU_MODE_HYP)) {
8819         return 1;
8820     }
8821 
8822     switch (mode) {
8823     case ARM_CPU_MODE_USR:
8824         return 0;
8825     case ARM_CPU_MODE_SYS:
8826     case ARM_CPU_MODE_SVC:
8827     case ARM_CPU_MODE_ABT:
8828     case ARM_CPU_MODE_UND:
8829     case ARM_CPU_MODE_IRQ:
8830     case ARM_CPU_MODE_FIQ:
8831         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
8832          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
8833          */
8834         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
8835          * and CPS are treated as illegal mode changes.
8836          */
8837         if (write_type == CPSRWriteByInstr &&
8838             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
8839             (arm_hcr_el2_eff(env) & HCR_TGE)) {
8840             return 1;
8841         }
8842         return 0;
8843     case ARM_CPU_MODE_HYP:
8844         return !arm_is_el2_enabled(env) || arm_current_el(env) < 2;
8845     case ARM_CPU_MODE_MON:
8846         return arm_current_el(env) < 3;
8847     default:
8848         return 1;
8849     }
8850 }
8851 
8852 uint32_t cpsr_read(CPUARMState *env)
8853 {
8854     int ZF;
8855     ZF = (env->ZF == 0);
8856     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
8857         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
8858         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
8859         | ((env->condexec_bits & 0xfc) << 8)
8860         | (env->GE << 16) | (env->daif & CPSR_AIF);
8861 }
8862 
8863 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
8864                 CPSRWriteType write_type)
8865 {
8866     uint32_t changed_daif;
8867     bool rebuild_hflags = (write_type != CPSRWriteRaw) &&
8868         (mask & (CPSR_M | CPSR_E | CPSR_IL));
8869 
8870     if (mask & CPSR_NZCV) {
8871         env->ZF = (~val) & CPSR_Z;
8872         env->NF = val;
8873         env->CF = (val >> 29) & 1;
8874         env->VF = (val << 3) & 0x80000000;
8875     }
8876     if (mask & CPSR_Q)
8877         env->QF = ((val & CPSR_Q) != 0);
8878     if (mask & CPSR_T)
8879         env->thumb = ((val & CPSR_T) != 0);
8880     if (mask & CPSR_IT_0_1) {
8881         env->condexec_bits &= ~3;
8882         env->condexec_bits |= (val >> 25) & 3;
8883     }
8884     if (mask & CPSR_IT_2_7) {
8885         env->condexec_bits &= 3;
8886         env->condexec_bits |= (val >> 8) & 0xfc;
8887     }
8888     if (mask & CPSR_GE) {
8889         env->GE = (val >> 16) & 0xf;
8890     }
8891 
8892     /* In a V7 implementation that includes the security extensions but does
8893      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
8894      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
8895      * bits respectively.
8896      *
8897      * In a V8 implementation, it is permitted for privileged software to
8898      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
8899      */
8900     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
8901         arm_feature(env, ARM_FEATURE_EL3) &&
8902         !arm_feature(env, ARM_FEATURE_EL2) &&
8903         !arm_is_secure(env)) {
8904 
8905         changed_daif = (env->daif ^ val) & mask;
8906 
8907         if (changed_daif & CPSR_A) {
8908             /* Check to see if we are allowed to change the masking of async
8909              * abort exceptions from a non-secure state.
8910              */
8911             if (!(env->cp15.scr_el3 & SCR_AW)) {
8912                 qemu_log_mask(LOG_GUEST_ERROR,
8913                               "Ignoring attempt to switch CPSR_A flag from "
8914                               "non-secure world with SCR.AW bit clear\n");
8915                 mask &= ~CPSR_A;
8916             }
8917         }
8918 
8919         if (changed_daif & CPSR_F) {
8920             /* Check to see if we are allowed to change the masking of FIQ
8921              * exceptions from a non-secure state.
8922              */
8923             if (!(env->cp15.scr_el3 & SCR_FW)) {
8924                 qemu_log_mask(LOG_GUEST_ERROR,
8925                               "Ignoring attempt to switch CPSR_F flag from "
8926                               "non-secure world with SCR.FW bit clear\n");
8927                 mask &= ~CPSR_F;
8928             }
8929 
8930             /* Check whether non-maskable FIQ (NMFI) support is enabled.
8931              * If this bit is set software is not allowed to mask
8932              * FIQs, but is allowed to set CPSR_F to 0.
8933              */
8934             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
8935                 (val & CPSR_F)) {
8936                 qemu_log_mask(LOG_GUEST_ERROR,
8937                               "Ignoring attempt to enable CPSR_F flag "
8938                               "(non-maskable FIQ [NMFI] support enabled)\n");
8939                 mask &= ~CPSR_F;
8940             }
8941         }
8942     }
8943 
8944     env->daif &= ~(CPSR_AIF & mask);
8945     env->daif |= val & CPSR_AIF & mask;
8946 
8947     if (write_type != CPSRWriteRaw &&
8948         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
8949         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
8950             /* Note that we can only get here in USR mode if this is a
8951              * gdb stub write; for this case we follow the architectural
8952              * behaviour for guest writes in USR mode of ignoring an attempt
8953              * to switch mode. (Those are caught by translate.c for writes
8954              * triggered by guest instructions.)
8955              */
8956             mask &= ~CPSR_M;
8957         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
8958             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
8959              * v7, and has defined behaviour in v8:
8960              *  + leave CPSR.M untouched
8961              *  + allow changes to the other CPSR fields
8962              *  + set PSTATE.IL
8963              * For user changes via the GDB stub, we don't set PSTATE.IL,
8964              * as this would be unnecessarily harsh for a user error.
8965              */
8966             mask &= ~CPSR_M;
8967             if (write_type != CPSRWriteByGDBStub &&
8968                 arm_feature(env, ARM_FEATURE_V8)) {
8969                 mask |= CPSR_IL;
8970                 val |= CPSR_IL;
8971             }
8972             qemu_log_mask(LOG_GUEST_ERROR,
8973                           "Illegal AArch32 mode switch attempt from %s to %s\n",
8974                           aarch32_mode_name(env->uncached_cpsr),
8975                           aarch32_mode_name(val));
8976         } else {
8977             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
8978                           write_type == CPSRWriteExceptionReturn ?
8979                           "Exception return from AArch32" :
8980                           "AArch32 mode switch from",
8981                           aarch32_mode_name(env->uncached_cpsr),
8982                           aarch32_mode_name(val), env->regs[15]);
8983             switch_mode(env, val & CPSR_M);
8984         }
8985     }
8986     mask &= ~CACHED_CPSR_BITS;
8987     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
8988     if (rebuild_hflags) {
8989         arm_rebuild_hflags(env);
8990     }
8991 }
8992 
8993 /* Sign/zero extend */
8994 uint32_t HELPER(sxtb16)(uint32_t x)
8995 {
8996     uint32_t res;
8997     res = (uint16_t)(int8_t)x;
8998     res |= (uint32_t)(int8_t)(x >> 16) << 16;
8999     return res;
9000 }
9001 
9002 static void handle_possible_div0_trap(CPUARMState *env, uintptr_t ra)
9003 {
9004     /*
9005      * Take a division-by-zero exception if necessary; otherwise return
9006      * to get the usual non-trapping division behaviour (result of 0)
9007      */
9008     if (arm_feature(env, ARM_FEATURE_M)
9009         && (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_DIV_0_TRP_MASK)) {
9010         raise_exception_ra(env, EXCP_DIVBYZERO, 0, 1, ra);
9011     }
9012 }
9013 
9014 uint32_t HELPER(uxtb16)(uint32_t x)
9015 {
9016     uint32_t res;
9017     res = (uint16_t)(uint8_t)x;
9018     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
9019     return res;
9020 }
9021 
9022 int32_t HELPER(sdiv)(CPUARMState *env, int32_t num, int32_t den)
9023 {
9024     if (den == 0) {
9025         handle_possible_div0_trap(env, GETPC());
9026         return 0;
9027     }
9028     if (num == INT_MIN && den == -1) {
9029         return INT_MIN;
9030     }
9031     return num / den;
9032 }
9033 
9034 uint32_t HELPER(udiv)(CPUARMState *env, uint32_t num, uint32_t den)
9035 {
9036     if (den == 0) {
9037         handle_possible_div0_trap(env, GETPC());
9038         return 0;
9039     }
9040     return num / den;
9041 }
9042 
9043 uint32_t HELPER(rbit)(uint32_t x)
9044 {
9045     return revbit32(x);
9046 }
9047 
9048 #ifdef CONFIG_USER_ONLY
9049 
9050 static void switch_mode(CPUARMState *env, int mode)
9051 {
9052     ARMCPU *cpu = env_archcpu(env);
9053 
9054     if (mode != ARM_CPU_MODE_USR) {
9055         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
9056     }
9057 }
9058 
9059 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9060                                  uint32_t cur_el, bool secure)
9061 {
9062     return 1;
9063 }
9064 
9065 void aarch64_sync_64_to_32(CPUARMState *env)
9066 {
9067     g_assert_not_reached();
9068 }
9069 
9070 #else
9071 
9072 static void switch_mode(CPUARMState *env, int mode)
9073 {
9074     int old_mode;
9075     int i;
9076 
9077     old_mode = env->uncached_cpsr & CPSR_M;
9078     if (mode == old_mode)
9079         return;
9080 
9081     if (old_mode == ARM_CPU_MODE_FIQ) {
9082         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
9083         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
9084     } else if (mode == ARM_CPU_MODE_FIQ) {
9085         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
9086         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
9087     }
9088 
9089     i = bank_number(old_mode);
9090     env->banked_r13[i] = env->regs[13];
9091     env->banked_spsr[i] = env->spsr;
9092 
9093     i = bank_number(mode);
9094     env->regs[13] = env->banked_r13[i];
9095     env->spsr = env->banked_spsr[i];
9096 
9097     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
9098     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
9099 }
9100 
9101 /* Physical Interrupt Target EL Lookup Table
9102  *
9103  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
9104  *
9105  * The below multi-dimensional table is used for looking up the target
9106  * exception level given numerous condition criteria.  Specifically, the
9107  * target EL is based on SCR and HCR routing controls as well as the
9108  * currently executing EL and secure state.
9109  *
9110  *    Dimensions:
9111  *    target_el_table[2][2][2][2][2][4]
9112  *                    |  |  |  |  |  +--- Current EL
9113  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
9114  *                    |  |  |  +--------- HCR mask override
9115  *                    |  |  +------------ SCR exec state control
9116  *                    |  +--------------- SCR mask override
9117  *                    +------------------ 32-bit(0)/64-bit(1) EL3
9118  *
9119  *    The table values are as such:
9120  *    0-3 = EL0-EL3
9121  *     -1 = Cannot occur
9122  *
9123  * The ARM ARM target EL table includes entries indicating that an "exception
9124  * is not taken".  The two cases where this is applicable are:
9125  *    1) An exception is taken from EL3 but the SCR does not have the exception
9126  *    routed to EL3.
9127  *    2) An exception is taken from EL2 but the HCR does not have the exception
9128  *    routed to EL2.
9129  * In these two cases, the below table contain a target of EL1.  This value is
9130  * returned as it is expected that the consumer of the table data will check
9131  * for "target EL >= current EL" to ensure the exception is not taken.
9132  *
9133  *            SCR     HCR
9134  *         64  EA     AMO                 From
9135  *        BIT IRQ     IMO      Non-secure         Secure
9136  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
9137  */
9138 static const int8_t target_el_table[2][2][2][2][2][4] = {
9139     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9140        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
9141       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9142        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
9143      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9144        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
9145       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9146        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
9147     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
9148        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 2,  2, -1,  1 },},},
9149       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1,  1,  1 },},
9150        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 2,  2,  2,  1 },},},},
9151      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
9152        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
9153       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},
9154        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},},},},
9155 };
9156 
9157 /*
9158  * Determine the target EL for physical exceptions
9159  */
9160 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9161                                  uint32_t cur_el, bool secure)
9162 {
9163     CPUARMState *env = cs->env_ptr;
9164     bool rw;
9165     bool scr;
9166     bool hcr;
9167     int target_el;
9168     /* Is the highest EL AArch64? */
9169     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9170     uint64_t hcr_el2;
9171 
9172     if (arm_feature(env, ARM_FEATURE_EL3)) {
9173         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9174     } else {
9175         /* Either EL2 is the highest EL (and so the EL2 register width
9176          * is given by is64); or there is no EL2 or EL3, in which case
9177          * the value of 'rw' does not affect the table lookup anyway.
9178          */
9179         rw = is64;
9180     }
9181 
9182     hcr_el2 = arm_hcr_el2_eff(env);
9183     switch (excp_idx) {
9184     case EXCP_IRQ:
9185         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9186         hcr = hcr_el2 & HCR_IMO;
9187         break;
9188     case EXCP_FIQ:
9189         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9190         hcr = hcr_el2 & HCR_FMO;
9191         break;
9192     default:
9193         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9194         hcr = hcr_el2 & HCR_AMO;
9195         break;
9196     };
9197 
9198     /*
9199      * For these purposes, TGE and AMO/IMO/FMO both force the
9200      * interrupt to EL2.  Fold TGE into the bit extracted above.
9201      */
9202     hcr |= (hcr_el2 & HCR_TGE) != 0;
9203 
9204     /* Perform a table-lookup for the target EL given the current state */
9205     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9206 
9207     assert(target_el > 0);
9208 
9209     return target_el;
9210 }
9211 
9212 void arm_log_exception(CPUState *cs)
9213 {
9214     int idx = cs->exception_index;
9215 
9216     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9217         const char *exc = NULL;
9218         static const char * const excnames[] = {
9219             [EXCP_UDEF] = "Undefined Instruction",
9220             [EXCP_SWI] = "SVC",
9221             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9222             [EXCP_DATA_ABORT] = "Data Abort",
9223             [EXCP_IRQ] = "IRQ",
9224             [EXCP_FIQ] = "FIQ",
9225             [EXCP_BKPT] = "Breakpoint",
9226             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9227             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9228             [EXCP_HVC] = "Hypervisor Call",
9229             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9230             [EXCP_SMC] = "Secure Monitor Call",
9231             [EXCP_VIRQ] = "Virtual IRQ",
9232             [EXCP_VFIQ] = "Virtual FIQ",
9233             [EXCP_SEMIHOST] = "Semihosting call",
9234             [EXCP_NOCP] = "v7M NOCP UsageFault",
9235             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9236             [EXCP_STKOF] = "v8M STKOF UsageFault",
9237             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9238             [EXCP_LSERR] = "v8M LSERR UsageFault",
9239             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9240             [EXCP_DIVBYZERO] = "v7M DIVBYZERO UsageFault",
9241         };
9242 
9243         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9244             exc = excnames[idx];
9245         }
9246         if (!exc) {
9247             exc = "unknown";
9248         }
9249         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s] on CPU %d\n",
9250                       idx, exc, cs->cpu_index);
9251     }
9252 }
9253 
9254 /*
9255  * Function used to synchronize QEMU's AArch64 register set with AArch32
9256  * register set.  This is necessary when switching between AArch32 and AArch64
9257  * execution state.
9258  */
9259 void aarch64_sync_32_to_64(CPUARMState *env)
9260 {
9261     int i;
9262     uint32_t mode = env->uncached_cpsr & CPSR_M;
9263 
9264     /* We can blanket copy R[0:7] to X[0:7] */
9265     for (i = 0; i < 8; i++) {
9266         env->xregs[i] = env->regs[i];
9267     }
9268 
9269     /*
9270      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9271      * Otherwise, they come from the banked user regs.
9272      */
9273     if (mode == ARM_CPU_MODE_FIQ) {
9274         for (i = 8; i < 13; i++) {
9275             env->xregs[i] = env->usr_regs[i - 8];
9276         }
9277     } else {
9278         for (i = 8; i < 13; i++) {
9279             env->xregs[i] = env->regs[i];
9280         }
9281     }
9282 
9283     /*
9284      * Registers x13-x23 are the various mode SP and FP registers. Registers
9285      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9286      * from the mode banked register.
9287      */
9288     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9289         env->xregs[13] = env->regs[13];
9290         env->xregs[14] = env->regs[14];
9291     } else {
9292         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9293         /* HYP is an exception in that it is copied from r14 */
9294         if (mode == ARM_CPU_MODE_HYP) {
9295             env->xregs[14] = env->regs[14];
9296         } else {
9297             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9298         }
9299     }
9300 
9301     if (mode == ARM_CPU_MODE_HYP) {
9302         env->xregs[15] = env->regs[13];
9303     } else {
9304         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9305     }
9306 
9307     if (mode == ARM_CPU_MODE_IRQ) {
9308         env->xregs[16] = env->regs[14];
9309         env->xregs[17] = env->regs[13];
9310     } else {
9311         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9312         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9313     }
9314 
9315     if (mode == ARM_CPU_MODE_SVC) {
9316         env->xregs[18] = env->regs[14];
9317         env->xregs[19] = env->regs[13];
9318     } else {
9319         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9320         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9321     }
9322 
9323     if (mode == ARM_CPU_MODE_ABT) {
9324         env->xregs[20] = env->regs[14];
9325         env->xregs[21] = env->regs[13];
9326     } else {
9327         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9328         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9329     }
9330 
9331     if (mode == ARM_CPU_MODE_UND) {
9332         env->xregs[22] = env->regs[14];
9333         env->xregs[23] = env->regs[13];
9334     } else {
9335         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9336         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9337     }
9338 
9339     /*
9340      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9341      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9342      * FIQ bank for r8-r14.
9343      */
9344     if (mode == ARM_CPU_MODE_FIQ) {
9345         for (i = 24; i < 31; i++) {
9346             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9347         }
9348     } else {
9349         for (i = 24; i < 29; i++) {
9350             env->xregs[i] = env->fiq_regs[i - 24];
9351         }
9352         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9353         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9354     }
9355 
9356     env->pc = env->regs[15];
9357 }
9358 
9359 /*
9360  * Function used to synchronize QEMU's AArch32 register set with AArch64
9361  * register set.  This is necessary when switching between AArch32 and AArch64
9362  * execution state.
9363  */
9364 void aarch64_sync_64_to_32(CPUARMState *env)
9365 {
9366     int i;
9367     uint32_t mode = env->uncached_cpsr & CPSR_M;
9368 
9369     /* We can blanket copy X[0:7] to R[0:7] */
9370     for (i = 0; i < 8; i++) {
9371         env->regs[i] = env->xregs[i];
9372     }
9373 
9374     /*
9375      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9376      * Otherwise, we copy x8-x12 into the banked user regs.
9377      */
9378     if (mode == ARM_CPU_MODE_FIQ) {
9379         for (i = 8; i < 13; i++) {
9380             env->usr_regs[i - 8] = env->xregs[i];
9381         }
9382     } else {
9383         for (i = 8; i < 13; i++) {
9384             env->regs[i] = env->xregs[i];
9385         }
9386     }
9387 
9388     /*
9389      * Registers r13 & r14 depend on the current mode.
9390      * If we are in a given mode, we copy the corresponding x registers to r13
9391      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9392      * for the mode.
9393      */
9394     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9395         env->regs[13] = env->xregs[13];
9396         env->regs[14] = env->xregs[14];
9397     } else {
9398         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9399 
9400         /*
9401          * HYP is an exception in that it does not have its own banked r14 but
9402          * shares the USR r14
9403          */
9404         if (mode == ARM_CPU_MODE_HYP) {
9405             env->regs[14] = env->xregs[14];
9406         } else {
9407             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9408         }
9409     }
9410 
9411     if (mode == ARM_CPU_MODE_HYP) {
9412         env->regs[13] = env->xregs[15];
9413     } else {
9414         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9415     }
9416 
9417     if (mode == ARM_CPU_MODE_IRQ) {
9418         env->regs[14] = env->xregs[16];
9419         env->regs[13] = env->xregs[17];
9420     } else {
9421         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9422         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9423     }
9424 
9425     if (mode == ARM_CPU_MODE_SVC) {
9426         env->regs[14] = env->xregs[18];
9427         env->regs[13] = env->xregs[19];
9428     } else {
9429         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9430         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9431     }
9432 
9433     if (mode == ARM_CPU_MODE_ABT) {
9434         env->regs[14] = env->xregs[20];
9435         env->regs[13] = env->xregs[21];
9436     } else {
9437         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9438         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9439     }
9440 
9441     if (mode == ARM_CPU_MODE_UND) {
9442         env->regs[14] = env->xregs[22];
9443         env->regs[13] = env->xregs[23];
9444     } else {
9445         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9446         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9447     }
9448 
9449     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9450      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9451      * FIQ bank for r8-r14.
9452      */
9453     if (mode == ARM_CPU_MODE_FIQ) {
9454         for (i = 24; i < 31; i++) {
9455             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9456         }
9457     } else {
9458         for (i = 24; i < 29; i++) {
9459             env->fiq_regs[i - 24] = env->xregs[i];
9460         }
9461         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9462         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9463     }
9464 
9465     env->regs[15] = env->pc;
9466 }
9467 
9468 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9469                                    uint32_t mask, uint32_t offset,
9470                                    uint32_t newpc)
9471 {
9472     int new_el;
9473 
9474     /* Change the CPU state so as to actually take the exception. */
9475     switch_mode(env, new_mode);
9476 
9477     /*
9478      * For exceptions taken to AArch32 we must clear the SS bit in both
9479      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9480      */
9481     env->pstate &= ~PSTATE_SS;
9482     env->spsr = cpsr_read(env);
9483     /* Clear IT bits.  */
9484     env->condexec_bits = 0;
9485     /* Switch to the new mode, and to the correct instruction set.  */
9486     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9487 
9488     /* This must be after mode switching. */
9489     new_el = arm_current_el(env);
9490 
9491     /* Set new mode endianness */
9492     env->uncached_cpsr &= ~CPSR_E;
9493     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9494         env->uncached_cpsr |= CPSR_E;
9495     }
9496     /* J and IL must always be cleared for exception entry */
9497     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9498     env->daif |= mask;
9499 
9500     if (cpu_isar_feature(aa32_ssbs, env_archcpu(env))) {
9501         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_32) {
9502             env->uncached_cpsr |= CPSR_SSBS;
9503         } else {
9504             env->uncached_cpsr &= ~CPSR_SSBS;
9505         }
9506     }
9507 
9508     if (new_mode == ARM_CPU_MODE_HYP) {
9509         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9510         env->elr_el[2] = env->regs[15];
9511     } else {
9512         /* CPSR.PAN is normally preserved preserved unless...  */
9513         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9514             switch (new_el) {
9515             case 3:
9516                 if (!arm_is_secure_below_el3(env)) {
9517                     /* ... the target is EL3, from non-secure state.  */
9518                     env->uncached_cpsr &= ~CPSR_PAN;
9519                     break;
9520                 }
9521                 /* ... the target is EL3, from secure state ... */
9522                 /* fall through */
9523             case 1:
9524                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9525                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9526                     env->uncached_cpsr |= CPSR_PAN;
9527                 }
9528                 break;
9529             }
9530         }
9531         /*
9532          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9533          * and we should just guard the thumb mode on V4
9534          */
9535         if (arm_feature(env, ARM_FEATURE_V4T)) {
9536             env->thumb =
9537                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9538         }
9539         env->regs[14] = env->regs[15] + offset;
9540     }
9541     env->regs[15] = newpc;
9542     arm_rebuild_hflags(env);
9543 }
9544 
9545 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9546 {
9547     /*
9548      * Handle exception entry to Hyp mode; this is sufficiently
9549      * different to entry to other AArch32 modes that we handle it
9550      * separately here.
9551      *
9552      * The vector table entry used is always the 0x14 Hyp mode entry point,
9553      * unless this is an UNDEF/SVC/HVC/abort taken from Hyp to Hyp.
9554      * The offset applied to the preferred return address is always zero
9555      * (see DDI0487C.a section G1.12.3).
9556      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9557      */
9558     uint32_t addr, mask;
9559     ARMCPU *cpu = ARM_CPU(cs);
9560     CPUARMState *env = &cpu->env;
9561 
9562     switch (cs->exception_index) {
9563     case EXCP_UDEF:
9564         addr = 0x04;
9565         break;
9566     case EXCP_SWI:
9567         addr = 0x08;
9568         break;
9569     case EXCP_BKPT:
9570         /* Fall through to prefetch abort.  */
9571     case EXCP_PREFETCH_ABORT:
9572         env->cp15.ifar_s = env->exception.vaddress;
9573         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9574                       (uint32_t)env->exception.vaddress);
9575         addr = 0x0c;
9576         break;
9577     case EXCP_DATA_ABORT:
9578         env->cp15.dfar_s = env->exception.vaddress;
9579         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9580                       (uint32_t)env->exception.vaddress);
9581         addr = 0x10;
9582         break;
9583     case EXCP_IRQ:
9584         addr = 0x18;
9585         break;
9586     case EXCP_FIQ:
9587         addr = 0x1c;
9588         break;
9589     case EXCP_HVC:
9590         addr = 0x08;
9591         break;
9592     case EXCP_HYP_TRAP:
9593         addr = 0x14;
9594         break;
9595     default:
9596         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9597     }
9598 
9599     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9600         if (!arm_feature(env, ARM_FEATURE_V8)) {
9601             /*
9602              * QEMU syndrome values are v8-style. v7 has the IL bit
9603              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9604              * If this is a v7 CPU, squash the IL bit in those cases.
9605              */
9606             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9607                 (cs->exception_index == EXCP_DATA_ABORT &&
9608                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9609                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9610                 env->exception.syndrome &= ~ARM_EL_IL;
9611             }
9612         }
9613         env->cp15.esr_el[2] = env->exception.syndrome;
9614     }
9615 
9616     if (arm_current_el(env) != 2 && addr < 0x14) {
9617         addr = 0x14;
9618     }
9619 
9620     mask = 0;
9621     if (!(env->cp15.scr_el3 & SCR_EA)) {
9622         mask |= CPSR_A;
9623     }
9624     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9625         mask |= CPSR_I;
9626     }
9627     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9628         mask |= CPSR_F;
9629     }
9630 
9631     addr += env->cp15.hvbar;
9632 
9633     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9634 }
9635 
9636 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9637 {
9638     ARMCPU *cpu = ARM_CPU(cs);
9639     CPUARMState *env = &cpu->env;
9640     uint32_t addr;
9641     uint32_t mask;
9642     int new_mode;
9643     uint32_t offset;
9644     uint32_t moe;
9645 
9646     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9647     switch (syn_get_ec(env->exception.syndrome)) {
9648     case EC_BREAKPOINT:
9649     case EC_BREAKPOINT_SAME_EL:
9650         moe = 1;
9651         break;
9652     case EC_WATCHPOINT:
9653     case EC_WATCHPOINT_SAME_EL:
9654         moe = 10;
9655         break;
9656     case EC_AA32_BKPT:
9657         moe = 3;
9658         break;
9659     case EC_VECTORCATCH:
9660         moe = 5;
9661         break;
9662     default:
9663         moe = 0;
9664         break;
9665     }
9666 
9667     if (moe) {
9668         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9669     }
9670 
9671     if (env->exception.target_el == 2) {
9672         arm_cpu_do_interrupt_aarch32_hyp(cs);
9673         return;
9674     }
9675 
9676     switch (cs->exception_index) {
9677     case EXCP_UDEF:
9678         new_mode = ARM_CPU_MODE_UND;
9679         addr = 0x04;
9680         mask = CPSR_I;
9681         if (env->thumb)
9682             offset = 2;
9683         else
9684             offset = 4;
9685         break;
9686     case EXCP_SWI:
9687         new_mode = ARM_CPU_MODE_SVC;
9688         addr = 0x08;
9689         mask = CPSR_I;
9690         /* The PC already points to the next instruction.  */
9691         offset = 0;
9692         break;
9693     case EXCP_BKPT:
9694         /* Fall through to prefetch abort.  */
9695     case EXCP_PREFETCH_ABORT:
9696         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9697         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9698         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9699                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9700         new_mode = ARM_CPU_MODE_ABT;
9701         addr = 0x0c;
9702         mask = CPSR_A | CPSR_I;
9703         offset = 4;
9704         break;
9705     case EXCP_DATA_ABORT:
9706         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9707         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9708         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9709                       env->exception.fsr,
9710                       (uint32_t)env->exception.vaddress);
9711         new_mode = ARM_CPU_MODE_ABT;
9712         addr = 0x10;
9713         mask = CPSR_A | CPSR_I;
9714         offset = 8;
9715         break;
9716     case EXCP_IRQ:
9717         new_mode = ARM_CPU_MODE_IRQ;
9718         addr = 0x18;
9719         /* Disable IRQ and imprecise data aborts.  */
9720         mask = CPSR_A | CPSR_I;
9721         offset = 4;
9722         if (env->cp15.scr_el3 & SCR_IRQ) {
9723             /* IRQ routed to monitor mode */
9724             new_mode = ARM_CPU_MODE_MON;
9725             mask |= CPSR_F;
9726         }
9727         break;
9728     case EXCP_FIQ:
9729         new_mode = ARM_CPU_MODE_FIQ;
9730         addr = 0x1c;
9731         /* Disable FIQ, IRQ and imprecise data aborts.  */
9732         mask = CPSR_A | CPSR_I | CPSR_F;
9733         if (env->cp15.scr_el3 & SCR_FIQ) {
9734             /* FIQ routed to monitor mode */
9735             new_mode = ARM_CPU_MODE_MON;
9736         }
9737         offset = 4;
9738         break;
9739     case EXCP_VIRQ:
9740         new_mode = ARM_CPU_MODE_IRQ;
9741         addr = 0x18;
9742         /* Disable IRQ and imprecise data aborts.  */
9743         mask = CPSR_A | CPSR_I;
9744         offset = 4;
9745         break;
9746     case EXCP_VFIQ:
9747         new_mode = ARM_CPU_MODE_FIQ;
9748         addr = 0x1c;
9749         /* Disable FIQ, IRQ and imprecise data aborts.  */
9750         mask = CPSR_A | CPSR_I | CPSR_F;
9751         offset = 4;
9752         break;
9753     case EXCP_SMC:
9754         new_mode = ARM_CPU_MODE_MON;
9755         addr = 0x08;
9756         mask = CPSR_A | CPSR_I | CPSR_F;
9757         offset = 0;
9758         break;
9759     default:
9760         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9761         return; /* Never happens.  Keep compiler happy.  */
9762     }
9763 
9764     if (new_mode == ARM_CPU_MODE_MON) {
9765         addr += env->cp15.mvbar;
9766     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9767         /* High vectors. When enabled, base address cannot be remapped. */
9768         addr += 0xffff0000;
9769     } else {
9770         /* ARM v7 architectures provide a vector base address register to remap
9771          * the interrupt vector table.
9772          * This register is only followed in non-monitor mode, and is banked.
9773          * Note: only bits 31:5 are valid.
9774          */
9775         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9776     }
9777 
9778     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9779         env->cp15.scr_el3 &= ~SCR_NS;
9780     }
9781 
9782     take_aarch32_exception(env, new_mode, mask, offset, addr);
9783 }
9784 
9785 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
9786 {
9787     /*
9788      * Return the register number of the AArch64 view of the AArch32
9789      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
9790      * be that of the AArch32 mode the exception came from.
9791      */
9792     int mode = env->uncached_cpsr & CPSR_M;
9793 
9794     switch (aarch32_reg) {
9795     case 0 ... 7:
9796         return aarch32_reg;
9797     case 8 ... 12:
9798         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
9799     case 13:
9800         switch (mode) {
9801         case ARM_CPU_MODE_USR:
9802         case ARM_CPU_MODE_SYS:
9803             return 13;
9804         case ARM_CPU_MODE_HYP:
9805             return 15;
9806         case ARM_CPU_MODE_IRQ:
9807             return 17;
9808         case ARM_CPU_MODE_SVC:
9809             return 19;
9810         case ARM_CPU_MODE_ABT:
9811             return 21;
9812         case ARM_CPU_MODE_UND:
9813             return 23;
9814         case ARM_CPU_MODE_FIQ:
9815             return 29;
9816         default:
9817             g_assert_not_reached();
9818         }
9819     case 14:
9820         switch (mode) {
9821         case ARM_CPU_MODE_USR:
9822         case ARM_CPU_MODE_SYS:
9823         case ARM_CPU_MODE_HYP:
9824             return 14;
9825         case ARM_CPU_MODE_IRQ:
9826             return 16;
9827         case ARM_CPU_MODE_SVC:
9828             return 18;
9829         case ARM_CPU_MODE_ABT:
9830             return 20;
9831         case ARM_CPU_MODE_UND:
9832             return 22;
9833         case ARM_CPU_MODE_FIQ:
9834             return 30;
9835         default:
9836             g_assert_not_reached();
9837         }
9838     case 15:
9839         return 31;
9840     default:
9841         g_assert_not_reached();
9842     }
9843 }
9844 
9845 static uint32_t cpsr_read_for_spsr_elx(CPUARMState *env)
9846 {
9847     uint32_t ret = cpsr_read(env);
9848 
9849     /* Move DIT to the correct location for SPSR_ELx */
9850     if (ret & CPSR_DIT) {
9851         ret &= ~CPSR_DIT;
9852         ret |= PSTATE_DIT;
9853     }
9854     /* Merge PSTATE.SS into SPSR_ELx */
9855     ret |= env->pstate & PSTATE_SS;
9856 
9857     return ret;
9858 }
9859 
9860 /* Handle exception entry to a target EL which is using AArch64 */
9861 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
9862 {
9863     ARMCPU *cpu = ARM_CPU(cs);
9864     CPUARMState *env = &cpu->env;
9865     unsigned int new_el = env->exception.target_el;
9866     target_ulong addr = env->cp15.vbar_el[new_el];
9867     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
9868     unsigned int old_mode;
9869     unsigned int cur_el = arm_current_el(env);
9870     int rt;
9871 
9872     /*
9873      * Note that new_el can never be 0.  If cur_el is 0, then
9874      * el0_a64 is is_a64(), else el0_a64 is ignored.
9875      */
9876     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
9877 
9878     if (cur_el < new_el) {
9879         /* Entry vector offset depends on whether the implemented EL
9880          * immediately lower than the target level is using AArch32 or AArch64
9881          */
9882         bool is_aa64;
9883         uint64_t hcr;
9884 
9885         switch (new_el) {
9886         case 3:
9887             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
9888             break;
9889         case 2:
9890             hcr = arm_hcr_el2_eff(env);
9891             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
9892                 is_aa64 = (hcr & HCR_RW) != 0;
9893                 break;
9894             }
9895             /* fall through */
9896         case 1:
9897             is_aa64 = is_a64(env);
9898             break;
9899         default:
9900             g_assert_not_reached();
9901         }
9902 
9903         if (is_aa64) {
9904             addr += 0x400;
9905         } else {
9906             addr += 0x600;
9907         }
9908     } else if (pstate_read(env) & PSTATE_SP) {
9909         addr += 0x200;
9910     }
9911 
9912     switch (cs->exception_index) {
9913     case EXCP_PREFETCH_ABORT:
9914     case EXCP_DATA_ABORT:
9915         env->cp15.far_el[new_el] = env->exception.vaddress;
9916         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
9917                       env->cp15.far_el[new_el]);
9918         /* fall through */
9919     case EXCP_BKPT:
9920     case EXCP_UDEF:
9921     case EXCP_SWI:
9922     case EXCP_HVC:
9923     case EXCP_HYP_TRAP:
9924     case EXCP_SMC:
9925         switch (syn_get_ec(env->exception.syndrome)) {
9926         case EC_ADVSIMDFPACCESSTRAP:
9927             /*
9928              * QEMU internal FP/SIMD syndromes from AArch32 include the
9929              * TA and coproc fields which are only exposed if the exception
9930              * is taken to AArch32 Hyp mode. Mask them out to get a valid
9931              * AArch64 format syndrome.
9932              */
9933             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
9934             break;
9935         case EC_CP14RTTRAP:
9936         case EC_CP15RTTRAP:
9937         case EC_CP14DTTRAP:
9938             /*
9939              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
9940              * the raw register field from the insn; when taking this to
9941              * AArch64 we must convert it to the AArch64 view of the register
9942              * number. Notice that we read a 4-bit AArch32 register number and
9943              * write back a 5-bit AArch64 one.
9944              */
9945             rt = extract32(env->exception.syndrome, 5, 4);
9946             rt = aarch64_regnum(env, rt);
9947             env->exception.syndrome = deposit32(env->exception.syndrome,
9948                                                 5, 5, rt);
9949             break;
9950         case EC_CP15RRTTRAP:
9951         case EC_CP14RRTTRAP:
9952             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
9953             rt = extract32(env->exception.syndrome, 5, 4);
9954             rt = aarch64_regnum(env, rt);
9955             env->exception.syndrome = deposit32(env->exception.syndrome,
9956                                                 5, 5, rt);
9957             rt = extract32(env->exception.syndrome, 10, 4);
9958             rt = aarch64_regnum(env, rt);
9959             env->exception.syndrome = deposit32(env->exception.syndrome,
9960                                                 10, 5, rt);
9961             break;
9962         }
9963         env->cp15.esr_el[new_el] = env->exception.syndrome;
9964         break;
9965     case EXCP_IRQ:
9966     case EXCP_VIRQ:
9967         addr += 0x80;
9968         break;
9969     case EXCP_FIQ:
9970     case EXCP_VFIQ:
9971         addr += 0x100;
9972         break;
9973     default:
9974         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9975     }
9976 
9977     if (is_a64(env)) {
9978         old_mode = pstate_read(env);
9979         aarch64_save_sp(env, arm_current_el(env));
9980         env->elr_el[new_el] = env->pc;
9981     } else {
9982         old_mode = cpsr_read_for_spsr_elx(env);
9983         env->elr_el[new_el] = env->regs[15];
9984 
9985         aarch64_sync_32_to_64(env);
9986 
9987         env->condexec_bits = 0;
9988     }
9989     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
9990 
9991     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
9992                   env->elr_el[new_el]);
9993 
9994     if (cpu_isar_feature(aa64_pan, cpu)) {
9995         /* The value of PSTATE.PAN is normally preserved, except when ... */
9996         new_mode |= old_mode & PSTATE_PAN;
9997         switch (new_el) {
9998         case 2:
9999             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
10000             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
10001                 != (HCR_E2H | HCR_TGE)) {
10002                 break;
10003             }
10004             /* fall through */
10005         case 1:
10006             /* ... the target is EL1 ... */
10007             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
10008             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
10009                 new_mode |= PSTATE_PAN;
10010             }
10011             break;
10012         }
10013     }
10014     if (cpu_isar_feature(aa64_mte, cpu)) {
10015         new_mode |= PSTATE_TCO;
10016     }
10017 
10018     if (cpu_isar_feature(aa64_ssbs, cpu)) {
10019         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_64) {
10020             new_mode |= PSTATE_SSBS;
10021         } else {
10022             new_mode &= ~PSTATE_SSBS;
10023         }
10024     }
10025 
10026     pstate_write(env, PSTATE_DAIF | new_mode);
10027     env->aarch64 = true;
10028     aarch64_restore_sp(env, new_el);
10029     helper_rebuild_hflags_a64(env, new_el);
10030 
10031     env->pc = addr;
10032 
10033     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10034                   new_el, env->pc, pstate_read(env));
10035 }
10036 
10037 /*
10038  * Do semihosting call and set the appropriate return value. All the
10039  * permission and validity checks have been done at translate time.
10040  *
10041  * We only see semihosting exceptions in TCG only as they are not
10042  * trapped to the hypervisor in KVM.
10043  */
10044 #ifdef CONFIG_TCG
10045 static void handle_semihosting(CPUState *cs)
10046 {
10047     ARMCPU *cpu = ARM_CPU(cs);
10048     CPUARMState *env = &cpu->env;
10049 
10050     if (is_a64(env)) {
10051         qemu_log_mask(CPU_LOG_INT,
10052                       "...handling as semihosting call 0x%" PRIx64 "\n",
10053                       env->xregs[0]);
10054         env->xregs[0] = do_common_semihosting(cs);
10055         env->pc += 4;
10056     } else {
10057         qemu_log_mask(CPU_LOG_INT,
10058                       "...handling as semihosting call 0x%x\n",
10059                       env->regs[0]);
10060         env->regs[0] = do_common_semihosting(cs);
10061         env->regs[15] += env->thumb ? 2 : 4;
10062     }
10063 }
10064 #endif
10065 
10066 /* Handle a CPU exception for A and R profile CPUs.
10067  * Do any appropriate logging, handle PSCI calls, and then hand off
10068  * to the AArch64-entry or AArch32-entry function depending on the
10069  * target exception level's register width.
10070  *
10071  * Note: this is used for both TCG (as the do_interrupt tcg op),
10072  *       and KVM to re-inject guest debug exceptions, and to
10073  *       inject a Synchronous-External-Abort.
10074  */
10075 void arm_cpu_do_interrupt(CPUState *cs)
10076 {
10077     ARMCPU *cpu = ARM_CPU(cs);
10078     CPUARMState *env = &cpu->env;
10079     unsigned int new_el = env->exception.target_el;
10080 
10081     assert(!arm_feature(env, ARM_FEATURE_M));
10082 
10083     arm_log_exception(cs);
10084     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10085                   new_el);
10086     if (qemu_loglevel_mask(CPU_LOG_INT)
10087         && !excp_is_internal(cs->exception_index)) {
10088         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10089                       syn_get_ec(env->exception.syndrome),
10090                       env->exception.syndrome);
10091     }
10092 
10093     if (arm_is_psci_call(cpu, cs->exception_index)) {
10094         arm_handle_psci_call(cpu);
10095         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10096         return;
10097     }
10098 
10099     /*
10100      * Semihosting semantics depend on the register width of the code
10101      * that caused the exception, not the target exception level, so
10102      * must be handled here.
10103      */
10104 #ifdef CONFIG_TCG
10105     if (cs->exception_index == EXCP_SEMIHOST) {
10106         handle_semihosting(cs);
10107         return;
10108     }
10109 #endif
10110 
10111     /* Hooks may change global state so BQL should be held, also the
10112      * BQL needs to be held for any modification of
10113      * cs->interrupt_request.
10114      */
10115     g_assert(qemu_mutex_iothread_locked());
10116 
10117     arm_call_pre_el_change_hook(cpu);
10118 
10119     assert(!excp_is_internal(cs->exception_index));
10120     if (arm_el_is_aa64(env, new_el)) {
10121         arm_cpu_do_interrupt_aarch64(cs);
10122     } else {
10123         arm_cpu_do_interrupt_aarch32(cs);
10124     }
10125 
10126     arm_call_el_change_hook(cpu);
10127 
10128     if (!kvm_enabled()) {
10129         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10130     }
10131 }
10132 #endif /* !CONFIG_USER_ONLY */
10133 
10134 uint64_t arm_sctlr(CPUARMState *env, int el)
10135 {
10136     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
10137     if (el == 0) {
10138         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
10139         el = (mmu_idx == ARMMMUIdx_E20_0 || mmu_idx == ARMMMUIdx_SE20_0)
10140              ? 2 : 1;
10141     }
10142     return env->cp15.sctlr_el[el];
10143 }
10144 
10145 /* Return the SCTLR value which controls this address translation regime */
10146 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10147 {
10148     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10149 }
10150 
10151 #ifndef CONFIG_USER_ONLY
10152 
10153 /* Return true if the specified stage of address translation is disabled */
10154 static inline bool regime_translation_disabled(CPUARMState *env,
10155                                                ARMMMUIdx mmu_idx)
10156 {
10157     uint64_t hcr_el2;
10158 
10159     if (arm_feature(env, ARM_FEATURE_M)) {
10160         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10161                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10162         case R_V7M_MPU_CTRL_ENABLE_MASK:
10163             /* Enabled, but not for HardFault and NMI */
10164             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10165         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10166             /* Enabled for all cases */
10167             return false;
10168         case 0:
10169         default:
10170             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10171              * we warned about that in armv7m_nvic.c when the guest set it.
10172              */
10173             return true;
10174         }
10175     }
10176 
10177     hcr_el2 = arm_hcr_el2_eff(env);
10178 
10179     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10180         /* HCR.DC means HCR.VM behaves as 1 */
10181         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10182     }
10183 
10184     if (hcr_el2 & HCR_TGE) {
10185         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10186         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10187             return true;
10188         }
10189     }
10190 
10191     if ((hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
10192         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10193         return true;
10194     }
10195 
10196     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10197 }
10198 
10199 static inline bool regime_translation_big_endian(CPUARMState *env,
10200                                                  ARMMMUIdx mmu_idx)
10201 {
10202     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10203 }
10204 
10205 /* Return the TTBR associated with this translation regime */
10206 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10207                                    int ttbrn)
10208 {
10209     if (mmu_idx == ARMMMUIdx_Stage2) {
10210         return env->cp15.vttbr_el2;
10211     }
10212     if (mmu_idx == ARMMMUIdx_Stage2_S) {
10213         return env->cp15.vsttbr_el2;
10214     }
10215     if (ttbrn == 0) {
10216         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10217     } else {
10218         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10219     }
10220 }
10221 
10222 #endif /* !CONFIG_USER_ONLY */
10223 
10224 /* Convert a possible stage1+2 MMU index into the appropriate
10225  * stage 1 MMU index
10226  */
10227 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10228 {
10229     switch (mmu_idx) {
10230     case ARMMMUIdx_SE10_0:
10231         return ARMMMUIdx_Stage1_SE0;
10232     case ARMMMUIdx_SE10_1:
10233         return ARMMMUIdx_Stage1_SE1;
10234     case ARMMMUIdx_SE10_1_PAN:
10235         return ARMMMUIdx_Stage1_SE1_PAN;
10236     case ARMMMUIdx_E10_0:
10237         return ARMMMUIdx_Stage1_E0;
10238     case ARMMMUIdx_E10_1:
10239         return ARMMMUIdx_Stage1_E1;
10240     case ARMMMUIdx_E10_1_PAN:
10241         return ARMMMUIdx_Stage1_E1_PAN;
10242     default:
10243         return mmu_idx;
10244     }
10245 }
10246 
10247 /* Return true if the translation regime is using LPAE format page tables */
10248 static inline bool regime_using_lpae_format(CPUARMState *env,
10249                                             ARMMMUIdx mmu_idx)
10250 {
10251     int el = regime_el(env, mmu_idx);
10252     if (el == 2 || arm_el_is_aa64(env, el)) {
10253         return true;
10254     }
10255     if (arm_feature(env, ARM_FEATURE_LPAE)
10256         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10257         return true;
10258     }
10259     return false;
10260 }
10261 
10262 /* Returns true if the stage 1 translation regime is using LPAE format page
10263  * tables. Used when raising alignment exceptions, whose FSR changes depending
10264  * on whether the long or short descriptor format is in use. */
10265 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10266 {
10267     mmu_idx = stage_1_mmu_idx(mmu_idx);
10268 
10269     return regime_using_lpae_format(env, mmu_idx);
10270 }
10271 
10272 #ifndef CONFIG_USER_ONLY
10273 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10274 {
10275     switch (mmu_idx) {
10276     case ARMMMUIdx_SE10_0:
10277     case ARMMMUIdx_E20_0:
10278     case ARMMMUIdx_SE20_0:
10279     case ARMMMUIdx_Stage1_E0:
10280     case ARMMMUIdx_Stage1_SE0:
10281     case ARMMMUIdx_MUser:
10282     case ARMMMUIdx_MSUser:
10283     case ARMMMUIdx_MUserNegPri:
10284     case ARMMMUIdx_MSUserNegPri:
10285         return true;
10286     default:
10287         return false;
10288     case ARMMMUIdx_E10_0:
10289     case ARMMMUIdx_E10_1:
10290     case ARMMMUIdx_E10_1_PAN:
10291         g_assert_not_reached();
10292     }
10293 }
10294 
10295 /* Translate section/page access permissions to page
10296  * R/W protection flags
10297  *
10298  * @env:         CPUARMState
10299  * @mmu_idx:     MMU index indicating required translation regime
10300  * @ap:          The 3-bit access permissions (AP[2:0])
10301  * @domain_prot: The 2-bit domain access permissions
10302  */
10303 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10304                                 int ap, int domain_prot)
10305 {
10306     bool is_user = regime_is_user(env, mmu_idx);
10307 
10308     if (domain_prot == 3) {
10309         return PAGE_READ | PAGE_WRITE;
10310     }
10311 
10312     switch (ap) {
10313     case 0:
10314         if (arm_feature(env, ARM_FEATURE_V7)) {
10315             return 0;
10316         }
10317         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10318         case SCTLR_S:
10319             return is_user ? 0 : PAGE_READ;
10320         case SCTLR_R:
10321             return PAGE_READ;
10322         default:
10323             return 0;
10324         }
10325     case 1:
10326         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10327     case 2:
10328         if (is_user) {
10329             return PAGE_READ;
10330         } else {
10331             return PAGE_READ | PAGE_WRITE;
10332         }
10333     case 3:
10334         return PAGE_READ | PAGE_WRITE;
10335     case 4: /* Reserved.  */
10336         return 0;
10337     case 5:
10338         return is_user ? 0 : PAGE_READ;
10339     case 6:
10340         return PAGE_READ;
10341     case 7:
10342         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10343             return 0;
10344         }
10345         return PAGE_READ;
10346     default:
10347         g_assert_not_reached();
10348     }
10349 }
10350 
10351 /* Translate section/page access permissions to page
10352  * R/W protection flags.
10353  *
10354  * @ap:      The 2-bit simple AP (AP[2:1])
10355  * @is_user: TRUE if accessing from PL0
10356  */
10357 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10358 {
10359     switch (ap) {
10360     case 0:
10361         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10362     case 1:
10363         return PAGE_READ | PAGE_WRITE;
10364     case 2:
10365         return is_user ? 0 : PAGE_READ;
10366     case 3:
10367         return PAGE_READ;
10368     default:
10369         g_assert_not_reached();
10370     }
10371 }
10372 
10373 static inline int
10374 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10375 {
10376     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10377 }
10378 
10379 /* Translate S2 section/page access permissions to protection flags
10380  *
10381  * @env:     CPUARMState
10382  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10383  * @xn:      XN (execute-never) bits
10384  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10385  */
10386 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10387 {
10388     int prot = 0;
10389 
10390     if (s2ap & 1) {
10391         prot |= PAGE_READ;
10392     }
10393     if (s2ap & 2) {
10394         prot |= PAGE_WRITE;
10395     }
10396 
10397     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10398         switch (xn) {
10399         case 0:
10400             prot |= PAGE_EXEC;
10401             break;
10402         case 1:
10403             if (s1_is_el0) {
10404                 prot |= PAGE_EXEC;
10405             }
10406             break;
10407         case 2:
10408             break;
10409         case 3:
10410             if (!s1_is_el0) {
10411                 prot |= PAGE_EXEC;
10412             }
10413             break;
10414         default:
10415             g_assert_not_reached();
10416         }
10417     } else {
10418         if (!extract32(xn, 1, 1)) {
10419             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10420                 prot |= PAGE_EXEC;
10421             }
10422         }
10423     }
10424     return prot;
10425 }
10426 
10427 /* Translate section/page access permissions to protection flags
10428  *
10429  * @env:     CPUARMState
10430  * @mmu_idx: MMU index indicating required translation regime
10431  * @is_aa64: TRUE if AArch64
10432  * @ap:      The 2-bit simple AP (AP[2:1])
10433  * @ns:      NS (non-secure) bit
10434  * @xn:      XN (execute-never) bit
10435  * @pxn:     PXN (privileged execute-never) bit
10436  */
10437 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10438                       int ap, int ns, int xn, int pxn)
10439 {
10440     bool is_user = regime_is_user(env, mmu_idx);
10441     int prot_rw, user_rw;
10442     bool have_wxn;
10443     int wxn = 0;
10444 
10445     assert(mmu_idx != ARMMMUIdx_Stage2);
10446     assert(mmu_idx != ARMMMUIdx_Stage2_S);
10447 
10448     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10449     if (is_user) {
10450         prot_rw = user_rw;
10451     } else {
10452         if (user_rw && regime_is_pan(env, mmu_idx)) {
10453             /* PAN forbids data accesses but doesn't affect insn fetch */
10454             prot_rw = 0;
10455         } else {
10456             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10457         }
10458     }
10459 
10460     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10461         return prot_rw;
10462     }
10463 
10464     /* TODO have_wxn should be replaced with
10465      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10466      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10467      * compatible processors have EL2, which is required for [U]WXN.
10468      */
10469     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10470 
10471     if (have_wxn) {
10472         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10473     }
10474 
10475     if (is_aa64) {
10476         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10477             xn = pxn || (user_rw & PAGE_WRITE);
10478         }
10479     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10480         switch (regime_el(env, mmu_idx)) {
10481         case 1:
10482         case 3:
10483             if (is_user) {
10484                 xn = xn || !(user_rw & PAGE_READ);
10485             } else {
10486                 int uwxn = 0;
10487                 if (have_wxn) {
10488                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10489                 }
10490                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10491                      (uwxn && (user_rw & PAGE_WRITE));
10492             }
10493             break;
10494         case 2:
10495             break;
10496         }
10497     } else {
10498         xn = wxn = 0;
10499     }
10500 
10501     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10502         return prot_rw;
10503     }
10504     return prot_rw | PAGE_EXEC;
10505 }
10506 
10507 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10508                                      uint32_t *table, uint32_t address)
10509 {
10510     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10511     TCR *tcr = regime_tcr(env, mmu_idx);
10512 
10513     if (address & tcr->mask) {
10514         if (tcr->raw_tcr & TTBCR_PD1) {
10515             /* Translation table walk disabled for TTBR1 */
10516             return false;
10517         }
10518         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10519     } else {
10520         if (tcr->raw_tcr & TTBCR_PD0) {
10521             /* Translation table walk disabled for TTBR0 */
10522             return false;
10523         }
10524         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10525     }
10526     *table |= (address >> 18) & 0x3ffc;
10527     return true;
10528 }
10529 
10530 /* Translate a S1 pagetable walk through S2 if needed.  */
10531 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10532                                hwaddr addr, bool *is_secure,
10533                                ARMMMUFaultInfo *fi)
10534 {
10535     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10536         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10537         target_ulong s2size;
10538         hwaddr s2pa;
10539         int s2prot;
10540         int ret;
10541         ARMMMUIdx s2_mmu_idx = *is_secure ? ARMMMUIdx_Stage2_S
10542                                           : ARMMMUIdx_Stage2;
10543         ARMCacheAttrs cacheattrs = {};
10544         MemTxAttrs txattrs = {};
10545 
10546         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, s2_mmu_idx, false,
10547                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10548                                  &cacheattrs);
10549         if (ret) {
10550             assert(fi->type != ARMFault_None);
10551             fi->s2addr = addr;
10552             fi->stage2 = true;
10553             fi->s1ptw = true;
10554             fi->s1ns = !*is_secure;
10555             return ~0;
10556         }
10557         if ((arm_hcr_el2_eff(env) & HCR_PTW) &&
10558             (cacheattrs.attrs & 0xf0) == 0) {
10559             /*
10560              * PTW set and S1 walk touched S2 Device memory:
10561              * generate Permission fault.
10562              */
10563             fi->type = ARMFault_Permission;
10564             fi->s2addr = addr;
10565             fi->stage2 = true;
10566             fi->s1ptw = true;
10567             fi->s1ns = !*is_secure;
10568             return ~0;
10569         }
10570 
10571         if (arm_is_secure_below_el3(env)) {
10572             /* Check if page table walk is to secure or non-secure PA space. */
10573             if (*is_secure) {
10574                 *is_secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
10575             } else {
10576                 *is_secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
10577             }
10578         } else {
10579             assert(!*is_secure);
10580         }
10581 
10582         addr = s2pa;
10583     }
10584     return addr;
10585 }
10586 
10587 /* All loads done in the course of a page table walk go through here. */
10588 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10589                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10590 {
10591     ARMCPU *cpu = ARM_CPU(cs);
10592     CPUARMState *env = &cpu->env;
10593     MemTxAttrs attrs = {};
10594     MemTxResult result = MEMTX_OK;
10595     AddressSpace *as;
10596     uint32_t data;
10597 
10598     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10599     attrs.secure = is_secure;
10600     as = arm_addressspace(cs, attrs);
10601     if (fi->s1ptw) {
10602         return 0;
10603     }
10604     if (regime_translation_big_endian(env, mmu_idx)) {
10605         data = address_space_ldl_be(as, addr, attrs, &result);
10606     } else {
10607         data = address_space_ldl_le(as, addr, attrs, &result);
10608     }
10609     if (result == MEMTX_OK) {
10610         return data;
10611     }
10612     fi->type = ARMFault_SyncExternalOnWalk;
10613     fi->ea = arm_extabort_type(result);
10614     return 0;
10615 }
10616 
10617 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10618                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10619 {
10620     ARMCPU *cpu = ARM_CPU(cs);
10621     CPUARMState *env = &cpu->env;
10622     MemTxAttrs attrs = {};
10623     MemTxResult result = MEMTX_OK;
10624     AddressSpace *as;
10625     uint64_t data;
10626 
10627     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10628     attrs.secure = is_secure;
10629     as = arm_addressspace(cs, attrs);
10630     if (fi->s1ptw) {
10631         return 0;
10632     }
10633     if (regime_translation_big_endian(env, mmu_idx)) {
10634         data = address_space_ldq_be(as, addr, attrs, &result);
10635     } else {
10636         data = address_space_ldq_le(as, addr, attrs, &result);
10637     }
10638     if (result == MEMTX_OK) {
10639         return data;
10640     }
10641     fi->type = ARMFault_SyncExternalOnWalk;
10642     fi->ea = arm_extabort_type(result);
10643     return 0;
10644 }
10645 
10646 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10647                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10648                              hwaddr *phys_ptr, int *prot,
10649                              target_ulong *page_size,
10650                              ARMMMUFaultInfo *fi)
10651 {
10652     CPUState *cs = env_cpu(env);
10653     int level = 1;
10654     uint32_t table;
10655     uint32_t desc;
10656     int type;
10657     int ap;
10658     int domain = 0;
10659     int domain_prot;
10660     hwaddr phys_addr;
10661     uint32_t dacr;
10662 
10663     /* Pagetable walk.  */
10664     /* Lookup l1 descriptor.  */
10665     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10666         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10667         fi->type = ARMFault_Translation;
10668         goto do_fault;
10669     }
10670     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10671                        mmu_idx, fi);
10672     if (fi->type != ARMFault_None) {
10673         goto do_fault;
10674     }
10675     type = (desc & 3);
10676     domain = (desc >> 5) & 0x0f;
10677     if (regime_el(env, mmu_idx) == 1) {
10678         dacr = env->cp15.dacr_ns;
10679     } else {
10680         dacr = env->cp15.dacr_s;
10681     }
10682     domain_prot = (dacr >> (domain * 2)) & 3;
10683     if (type == 0) {
10684         /* Section translation fault.  */
10685         fi->type = ARMFault_Translation;
10686         goto do_fault;
10687     }
10688     if (type != 2) {
10689         level = 2;
10690     }
10691     if (domain_prot == 0 || domain_prot == 2) {
10692         fi->type = ARMFault_Domain;
10693         goto do_fault;
10694     }
10695     if (type == 2) {
10696         /* 1Mb section.  */
10697         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10698         ap = (desc >> 10) & 3;
10699         *page_size = 1024 * 1024;
10700     } else {
10701         /* Lookup l2 entry.  */
10702         if (type == 1) {
10703             /* Coarse pagetable.  */
10704             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10705         } else {
10706             /* Fine pagetable.  */
10707             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10708         }
10709         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10710                            mmu_idx, fi);
10711         if (fi->type != ARMFault_None) {
10712             goto do_fault;
10713         }
10714         switch (desc & 3) {
10715         case 0: /* Page translation fault.  */
10716             fi->type = ARMFault_Translation;
10717             goto do_fault;
10718         case 1: /* 64k page.  */
10719             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10720             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10721             *page_size = 0x10000;
10722             break;
10723         case 2: /* 4k page.  */
10724             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10725             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10726             *page_size = 0x1000;
10727             break;
10728         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10729             if (type == 1) {
10730                 /* ARMv6/XScale extended small page format */
10731                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10732                     || arm_feature(env, ARM_FEATURE_V6)) {
10733                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10734                     *page_size = 0x1000;
10735                 } else {
10736                     /* UNPREDICTABLE in ARMv5; we choose to take a
10737                      * page translation fault.
10738                      */
10739                     fi->type = ARMFault_Translation;
10740                     goto do_fault;
10741                 }
10742             } else {
10743                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10744                 *page_size = 0x400;
10745             }
10746             ap = (desc >> 4) & 3;
10747             break;
10748         default:
10749             /* Never happens, but compiler isn't smart enough to tell.  */
10750             g_assert_not_reached();
10751         }
10752     }
10753     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10754     *prot |= *prot ? PAGE_EXEC : 0;
10755     if (!(*prot & (1 << access_type))) {
10756         /* Access permission fault.  */
10757         fi->type = ARMFault_Permission;
10758         goto do_fault;
10759     }
10760     *phys_ptr = phys_addr;
10761     return false;
10762 do_fault:
10763     fi->domain = domain;
10764     fi->level = level;
10765     return true;
10766 }
10767 
10768 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10769                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10770                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10771                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10772 {
10773     CPUState *cs = env_cpu(env);
10774     ARMCPU *cpu = env_archcpu(env);
10775     int level = 1;
10776     uint32_t table;
10777     uint32_t desc;
10778     uint32_t xn;
10779     uint32_t pxn = 0;
10780     int type;
10781     int ap;
10782     int domain = 0;
10783     int domain_prot;
10784     hwaddr phys_addr;
10785     uint32_t dacr;
10786     bool ns;
10787 
10788     /* Pagetable walk.  */
10789     /* Lookup l1 descriptor.  */
10790     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10791         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10792         fi->type = ARMFault_Translation;
10793         goto do_fault;
10794     }
10795     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10796                        mmu_idx, fi);
10797     if (fi->type != ARMFault_None) {
10798         goto do_fault;
10799     }
10800     type = (desc & 3);
10801     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
10802         /* Section translation fault, or attempt to use the encoding
10803          * which is Reserved on implementations without PXN.
10804          */
10805         fi->type = ARMFault_Translation;
10806         goto do_fault;
10807     }
10808     if ((type == 1) || !(desc & (1 << 18))) {
10809         /* Page or Section.  */
10810         domain = (desc >> 5) & 0x0f;
10811     }
10812     if (regime_el(env, mmu_idx) == 1) {
10813         dacr = env->cp15.dacr_ns;
10814     } else {
10815         dacr = env->cp15.dacr_s;
10816     }
10817     if (type == 1) {
10818         level = 2;
10819     }
10820     domain_prot = (dacr >> (domain * 2)) & 3;
10821     if (domain_prot == 0 || domain_prot == 2) {
10822         /* Section or Page domain fault */
10823         fi->type = ARMFault_Domain;
10824         goto do_fault;
10825     }
10826     if (type != 1) {
10827         if (desc & (1 << 18)) {
10828             /* Supersection.  */
10829             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
10830             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
10831             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
10832             *page_size = 0x1000000;
10833         } else {
10834             /* Section.  */
10835             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10836             *page_size = 0x100000;
10837         }
10838         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
10839         xn = desc & (1 << 4);
10840         pxn = desc & 1;
10841         ns = extract32(desc, 19, 1);
10842     } else {
10843         if (cpu_isar_feature(aa32_pxn, cpu)) {
10844             pxn = (desc >> 2) & 1;
10845         }
10846         ns = extract32(desc, 3, 1);
10847         /* Lookup l2 entry.  */
10848         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10849         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10850                            mmu_idx, fi);
10851         if (fi->type != ARMFault_None) {
10852             goto do_fault;
10853         }
10854         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
10855         switch (desc & 3) {
10856         case 0: /* Page translation fault.  */
10857             fi->type = ARMFault_Translation;
10858             goto do_fault;
10859         case 1: /* 64k page.  */
10860             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10861             xn = desc & (1 << 15);
10862             *page_size = 0x10000;
10863             break;
10864         case 2: case 3: /* 4k page.  */
10865             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10866             xn = desc & 1;
10867             *page_size = 0x1000;
10868             break;
10869         default:
10870             /* Never happens, but compiler isn't smart enough to tell.  */
10871             g_assert_not_reached();
10872         }
10873     }
10874     if (domain_prot == 3) {
10875         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10876     } else {
10877         if (pxn && !regime_is_user(env, mmu_idx)) {
10878             xn = 1;
10879         }
10880         if (xn && access_type == MMU_INST_FETCH) {
10881             fi->type = ARMFault_Permission;
10882             goto do_fault;
10883         }
10884 
10885         if (arm_feature(env, ARM_FEATURE_V6K) &&
10886                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
10887             /* The simplified model uses AP[0] as an access control bit.  */
10888             if ((ap & 1) == 0) {
10889                 /* Access flag fault.  */
10890                 fi->type = ARMFault_AccessFlag;
10891                 goto do_fault;
10892             }
10893             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
10894         } else {
10895             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10896         }
10897         if (*prot && !xn) {
10898             *prot |= PAGE_EXEC;
10899         }
10900         if (!(*prot & (1 << access_type))) {
10901             /* Access permission fault.  */
10902             fi->type = ARMFault_Permission;
10903             goto do_fault;
10904         }
10905     }
10906     if (ns) {
10907         /* The NS bit will (as required by the architecture) have no effect if
10908          * the CPU doesn't support TZ or this is a non-secure translation
10909          * regime, because the attribute will already be non-secure.
10910          */
10911         attrs->secure = false;
10912     }
10913     *phys_ptr = phys_addr;
10914     return false;
10915 do_fault:
10916     fi->domain = domain;
10917     fi->level = level;
10918     return true;
10919 }
10920 
10921 /*
10922  * check_s2_mmu_setup
10923  * @cpu:        ARMCPU
10924  * @is_aa64:    True if the translation regime is in AArch64 state
10925  * @startlevel: Suggested starting level
10926  * @inputsize:  Bitsize of IPAs
10927  * @stride:     Page-table stride (See the ARM ARM)
10928  *
10929  * Returns true if the suggested S2 translation parameters are OK and
10930  * false otherwise.
10931  */
10932 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
10933                                int inputsize, int stride, int outputsize)
10934 {
10935     const int grainsize = stride + 3;
10936     int startsizecheck;
10937 
10938     /*
10939      * Negative levels are usually not allowed...
10940      * Except for FEAT_LPA2, 4k page table, 52-bit address space, which
10941      * begins with level -1.  Note that previous feature tests will have
10942      * eliminated this combination if it is not enabled.
10943      */
10944     if (level < (inputsize == 52 && stride == 9 ? -1 : 0)) {
10945         return false;
10946     }
10947 
10948     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
10949     if (startsizecheck < 1 || startsizecheck > stride + 4) {
10950         return false;
10951     }
10952 
10953     if (is_aa64) {
10954         switch (stride) {
10955         case 13: /* 64KB Pages.  */
10956             if (level == 0 || (level == 1 && outputsize <= 42)) {
10957                 return false;
10958             }
10959             break;
10960         case 11: /* 16KB Pages.  */
10961             if (level == 0 || (level == 1 && outputsize <= 40)) {
10962                 return false;
10963             }
10964             break;
10965         case 9: /* 4KB Pages.  */
10966             if (level == 0 && outputsize <= 42) {
10967                 return false;
10968             }
10969             break;
10970         default:
10971             g_assert_not_reached();
10972         }
10973 
10974         /* Inputsize checks.  */
10975         if (inputsize > outputsize &&
10976             (arm_el_is_aa64(&cpu->env, 1) || inputsize > 40)) {
10977             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
10978             return false;
10979         }
10980     } else {
10981         /* AArch32 only supports 4KB pages. Assert on that.  */
10982         assert(stride == 9);
10983 
10984         if (level == 0) {
10985             return false;
10986         }
10987     }
10988     return true;
10989 }
10990 
10991 /* Translate from the 4-bit stage 2 representation of
10992  * memory attributes (without cache-allocation hints) to
10993  * the 8-bit representation of the stage 1 MAIR registers
10994  * (which includes allocation hints).
10995  *
10996  * ref: shared/translation/attrs/S2AttrDecode()
10997  *      .../S2ConvertAttrsHints()
10998  */
10999 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11000 {
11001     uint8_t hiattr = extract32(s2attrs, 2, 2);
11002     uint8_t loattr = extract32(s2attrs, 0, 2);
11003     uint8_t hihint = 0, lohint = 0;
11004 
11005     if (hiattr != 0) { /* normal memory */
11006         if (arm_hcr_el2_eff(env) & HCR_CD) { /* cache disabled */
11007             hiattr = loattr = 1; /* non-cacheable */
11008         } else {
11009             if (hiattr != 1) { /* Write-through or write-back */
11010                 hihint = 3; /* RW allocate */
11011             }
11012             if (loattr != 1) { /* Write-through or write-back */
11013                 lohint = 3; /* RW allocate */
11014             }
11015         }
11016     }
11017 
11018     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11019 }
11020 #endif /* !CONFIG_USER_ONLY */
11021 
11022 /* This mapping is common between ID_AA64MMFR0.PARANGE and TCR_ELx.{I}PS. */
11023 static const uint8_t pamax_map[] = {
11024     [0] = 32,
11025     [1] = 36,
11026     [2] = 40,
11027     [3] = 42,
11028     [4] = 44,
11029     [5] = 48,
11030     [6] = 52,
11031 };
11032 
11033 /* The cpu-specific constant value of PAMax; also used by hw/arm/virt. */
11034 unsigned int arm_pamax(ARMCPU *cpu)
11035 {
11036     unsigned int parange =
11037         FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11038 
11039     /*
11040      * id_aa64mmfr0 is a read-only register so values outside of the
11041      * supported mappings can be considered an implementation error.
11042      */
11043     assert(parange < ARRAY_SIZE(pamax_map));
11044     return pamax_map[parange];
11045 }
11046 
11047 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
11048 {
11049     if (regime_has_2_ranges(mmu_idx)) {
11050         return extract64(tcr, 37, 2);
11051     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11052         return 0; /* VTCR_EL2 */
11053     } else {
11054         /* Replicate the single TBI bit so we always have 2 bits.  */
11055         return extract32(tcr, 20, 1) * 3;
11056     }
11057 }
11058 
11059 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
11060 {
11061     if (regime_has_2_ranges(mmu_idx)) {
11062         return extract64(tcr, 51, 2);
11063     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11064         return 0; /* VTCR_EL2 */
11065     } else {
11066         /* Replicate the single TBID bit so we always have 2 bits.  */
11067         return extract32(tcr, 29, 1) * 3;
11068     }
11069 }
11070 
11071 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
11072 {
11073     if (regime_has_2_ranges(mmu_idx)) {
11074         return extract64(tcr, 57, 2);
11075     } else {
11076         /* Replicate the single TCMA bit so we always have 2 bits.  */
11077         return extract32(tcr, 30, 1) * 3;
11078     }
11079 }
11080 
11081 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11082                                    ARMMMUIdx mmu_idx, bool data)
11083 {
11084     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11085     bool epd, hpd, using16k, using64k, tsz_oob, ds;
11086     int select, tsz, tbi, max_tsz, min_tsz, ps, sh;
11087     ARMCPU *cpu = env_archcpu(env);
11088 
11089     if (!regime_has_2_ranges(mmu_idx)) {
11090         select = 0;
11091         tsz = extract32(tcr, 0, 6);
11092         using64k = extract32(tcr, 14, 1);
11093         using16k = extract32(tcr, 15, 1);
11094         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11095             /* VTCR_EL2 */
11096             hpd = false;
11097         } else {
11098             hpd = extract32(tcr, 24, 1);
11099         }
11100         epd = false;
11101         sh = extract32(tcr, 12, 2);
11102         ps = extract32(tcr, 16, 3);
11103         ds = extract64(tcr, 32, 1);
11104     } else {
11105         /*
11106          * Bit 55 is always between the two regions, and is canonical for
11107          * determining if address tagging is enabled.
11108          */
11109         select = extract64(va, 55, 1);
11110         if (!select) {
11111             tsz = extract32(tcr, 0, 6);
11112             epd = extract32(tcr, 7, 1);
11113             sh = extract32(tcr, 12, 2);
11114             using64k = extract32(tcr, 14, 1);
11115             using16k = extract32(tcr, 15, 1);
11116             hpd = extract64(tcr, 41, 1);
11117         } else {
11118             int tg = extract32(tcr, 30, 2);
11119             using16k = tg == 1;
11120             using64k = tg == 3;
11121             tsz = extract32(tcr, 16, 6);
11122             epd = extract32(tcr, 23, 1);
11123             sh = extract32(tcr, 28, 2);
11124             hpd = extract64(tcr, 42, 1);
11125         }
11126         ps = extract64(tcr, 32, 3);
11127         ds = extract64(tcr, 59, 1);
11128     }
11129 
11130     if (cpu_isar_feature(aa64_st, cpu)) {
11131         max_tsz = 48 - using64k;
11132     } else {
11133         max_tsz = 39;
11134     }
11135 
11136     /*
11137      * DS is RES0 unless FEAT_LPA2 is supported for the given page size;
11138      * adjust the effective value of DS, as documented.
11139      */
11140     min_tsz = 16;
11141     if (using64k) {
11142         if (cpu_isar_feature(aa64_lva, cpu)) {
11143             min_tsz = 12;
11144         }
11145         ds = false;
11146     } else if (ds) {
11147         switch (mmu_idx) {
11148         case ARMMMUIdx_Stage2:
11149         case ARMMMUIdx_Stage2_S:
11150             if (using16k) {
11151                 ds = cpu_isar_feature(aa64_tgran16_2_lpa2, cpu);
11152             } else {
11153                 ds = cpu_isar_feature(aa64_tgran4_2_lpa2, cpu);
11154             }
11155             break;
11156         default:
11157             if (using16k) {
11158                 ds = cpu_isar_feature(aa64_tgran16_lpa2, cpu);
11159             } else {
11160                 ds = cpu_isar_feature(aa64_tgran4_lpa2, cpu);
11161             }
11162             break;
11163         }
11164         if (ds) {
11165             min_tsz = 12;
11166         }
11167     }
11168 
11169     if (tsz > max_tsz) {
11170         tsz = max_tsz;
11171         tsz_oob = true;
11172     } else if (tsz < min_tsz) {
11173         tsz = min_tsz;
11174         tsz_oob = true;
11175     } else {
11176         tsz_oob = false;
11177     }
11178 
11179     /* Present TBI as a composite with TBID.  */
11180     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11181     if (!data) {
11182         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11183     }
11184     tbi = (tbi >> select) & 1;
11185 
11186     return (ARMVAParameters) {
11187         .tsz = tsz,
11188         .ps = ps,
11189         .sh = sh,
11190         .select = select,
11191         .tbi = tbi,
11192         .epd = epd,
11193         .hpd = hpd,
11194         .using16k = using16k,
11195         .using64k = using64k,
11196         .tsz_oob = tsz_oob,
11197         .ds = ds,
11198     };
11199 }
11200 
11201 #ifndef CONFIG_USER_ONLY
11202 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11203                                           ARMMMUIdx mmu_idx)
11204 {
11205     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11206     uint32_t el = regime_el(env, mmu_idx);
11207     int select, tsz;
11208     bool epd, hpd;
11209 
11210     assert(mmu_idx != ARMMMUIdx_Stage2_S);
11211 
11212     if (mmu_idx == ARMMMUIdx_Stage2) {
11213         /* VTCR */
11214         bool sext = extract32(tcr, 4, 1);
11215         bool sign = extract32(tcr, 3, 1);
11216 
11217         /*
11218          * If the sign-extend bit is not the same as t0sz[3], the result
11219          * is unpredictable. Flag this as a guest error.
11220          */
11221         if (sign != sext) {
11222             qemu_log_mask(LOG_GUEST_ERROR,
11223                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11224         }
11225         tsz = sextract32(tcr, 0, 4) + 8;
11226         select = 0;
11227         hpd = false;
11228         epd = false;
11229     } else if (el == 2) {
11230         /* HTCR */
11231         tsz = extract32(tcr, 0, 3);
11232         select = 0;
11233         hpd = extract64(tcr, 24, 1);
11234         epd = false;
11235     } else {
11236         int t0sz = extract32(tcr, 0, 3);
11237         int t1sz = extract32(tcr, 16, 3);
11238 
11239         if (t1sz == 0) {
11240             select = va > (0xffffffffu >> t0sz);
11241         } else {
11242             /* Note that we will detect errors later.  */
11243             select = va >= ~(0xffffffffu >> t1sz);
11244         }
11245         if (!select) {
11246             tsz = t0sz;
11247             epd = extract32(tcr, 7, 1);
11248             hpd = extract64(tcr, 41, 1);
11249         } else {
11250             tsz = t1sz;
11251             epd = extract32(tcr, 23, 1);
11252             hpd = extract64(tcr, 42, 1);
11253         }
11254         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11255         hpd &= extract32(tcr, 6, 1);
11256     }
11257 
11258     return (ARMVAParameters) {
11259         .tsz = tsz,
11260         .select = select,
11261         .epd = epd,
11262         .hpd = hpd,
11263     };
11264 }
11265 
11266 /**
11267  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
11268  *
11269  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11270  * prot and page_size may not be filled in, and the populated fsr value provides
11271  * information on why the translation aborted, in the format of a long-format
11272  * DFSR/IFSR fault register, with the following caveats:
11273  *  * the WnR bit is never set (the caller must do this).
11274  *
11275  * @env: CPUARMState
11276  * @address: virtual address to get physical address for
11277  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
11278  * @mmu_idx: MMU index indicating required translation regime
11279  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
11280  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
11281  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
11282  * @phys_ptr: set to the physical address corresponding to the virtual address
11283  * @attrs: set to the memory transaction attributes to use
11284  * @prot: set to the permissions for the page containing phys_ptr
11285  * @page_size_ptr: set to the size of the page containing phys_ptr
11286  * @fi: set to fault info if the translation fails
11287  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11288  */
11289 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
11290                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11291                                bool s1_is_el0,
11292                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11293                                target_ulong *page_size_ptr,
11294                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11295 {
11296     ARMCPU *cpu = env_archcpu(env);
11297     CPUState *cs = CPU(cpu);
11298     /* Read an LPAE long-descriptor translation table. */
11299     ARMFaultType fault_type = ARMFault_Translation;
11300     uint32_t level;
11301     ARMVAParameters param;
11302     uint64_t ttbr;
11303     hwaddr descaddr, indexmask, indexmask_grainsize;
11304     uint32_t tableattrs;
11305     target_ulong page_size;
11306     uint32_t attrs;
11307     int32_t stride;
11308     int addrsize, inputsize, outputsize;
11309     TCR *tcr = regime_tcr(env, mmu_idx);
11310     int ap, ns, xn, pxn;
11311     uint32_t el = regime_el(env, mmu_idx);
11312     uint64_t descaddrmask;
11313     bool aarch64 = arm_el_is_aa64(env, el);
11314     bool guarded = false;
11315 
11316     /* TODO: This code does not support shareability levels. */
11317     if (aarch64) {
11318         int ps;
11319 
11320         param = aa64_va_parameters(env, address, mmu_idx,
11321                                    access_type != MMU_INST_FETCH);
11322         level = 0;
11323 
11324         /*
11325          * If TxSZ is programmed to a value larger than the maximum,
11326          * or smaller than the effective minimum, it is IMPLEMENTATION
11327          * DEFINED whether we behave as if the field were programmed
11328          * within bounds, or if a level 0 Translation fault is generated.
11329          *
11330          * With FEAT_LVA, fault on less than minimum becomes required,
11331          * so our choice is to always raise the fault.
11332          */
11333         if (param.tsz_oob) {
11334             fault_type = ARMFault_Translation;
11335             goto do_fault;
11336         }
11337 
11338         addrsize = 64 - 8 * param.tbi;
11339         inputsize = 64 - param.tsz;
11340 
11341         /*
11342          * Bound PS by PARANGE to find the effective output address size.
11343          * ID_AA64MMFR0 is a read-only register so values outside of the
11344          * supported mappings can be considered an implementation error.
11345          */
11346         ps = FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11347         ps = MIN(ps, param.ps);
11348         assert(ps < ARRAY_SIZE(pamax_map));
11349         outputsize = pamax_map[ps];
11350     } else {
11351         param = aa32_va_parameters(env, address, mmu_idx);
11352         level = 1;
11353         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11354         inputsize = addrsize - param.tsz;
11355         outputsize = 40;
11356     }
11357 
11358     /*
11359      * We determined the region when collecting the parameters, but we
11360      * have not yet validated that the address is valid for the region.
11361      * Extract the top bits and verify that they all match select.
11362      *
11363      * For aa32, if inputsize == addrsize, then we have selected the
11364      * region by exclusion in aa32_va_parameters and there is no more
11365      * validation to do here.
11366      */
11367     if (inputsize < addrsize) {
11368         target_ulong top_bits = sextract64(address, inputsize,
11369                                            addrsize - inputsize);
11370         if (-top_bits != param.select) {
11371             /* The gap between the two regions is a Translation fault */
11372             fault_type = ARMFault_Translation;
11373             goto do_fault;
11374         }
11375     }
11376 
11377     if (param.using64k) {
11378         stride = 13;
11379     } else if (param.using16k) {
11380         stride = 11;
11381     } else {
11382         stride = 9;
11383     }
11384 
11385     /* Note that QEMU ignores shareability and cacheability attributes,
11386      * so we don't need to do anything with the SH, ORGN, IRGN fields
11387      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11388      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11389      * implement any ASID-like capability so we can ignore it (instead
11390      * we will always flush the TLB any time the ASID is changed).
11391      */
11392     ttbr = regime_ttbr(env, mmu_idx, param.select);
11393 
11394     /* Here we should have set up all the parameters for the translation:
11395      * inputsize, ttbr, epd, stride, tbi
11396      */
11397 
11398     if (param.epd) {
11399         /* Translation table walk disabled => Translation fault on TLB miss
11400          * Note: This is always 0 on 64-bit EL2 and EL3.
11401          */
11402         goto do_fault;
11403     }
11404 
11405     if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
11406         /* The starting level depends on the virtual address size (which can
11407          * be up to 48 bits) and the translation granule size. It indicates
11408          * the number of strides (stride bits at a time) needed to
11409          * consume the bits of the input address. In the pseudocode this is:
11410          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11411          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11412          * our 'stride + 3' and 'stride' is our 'stride'.
11413          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11414          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11415          * = 4 - (inputsize - 4) / stride;
11416          */
11417         level = 4 - (inputsize - 4) / stride;
11418     } else {
11419         /* For stage 2 translations the starting level is specified by the
11420          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11421          */
11422         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11423         uint32_t sl2 = extract64(tcr->raw_tcr, 33, 1);
11424         uint32_t startlevel;
11425         bool ok;
11426 
11427         /* SL2 is RES0 unless DS=1 & 4kb granule. */
11428         if (param.ds && stride == 9 && sl2) {
11429             if (sl0 != 0) {
11430                 level = 0;
11431                 fault_type = ARMFault_Translation;
11432                 goto do_fault;
11433             }
11434             startlevel = -1;
11435         } else if (!aarch64 || stride == 9) {
11436             /* AArch32 or 4KB pages */
11437             startlevel = 2 - sl0;
11438 
11439             if (cpu_isar_feature(aa64_st, cpu)) {
11440                 startlevel &= 3;
11441             }
11442         } else {
11443             /* 16KB or 64KB pages */
11444             startlevel = 3 - sl0;
11445         }
11446 
11447         /* Check that the starting level is valid. */
11448         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11449                                 inputsize, stride, outputsize);
11450         if (!ok) {
11451             fault_type = ARMFault_Translation;
11452             goto do_fault;
11453         }
11454         level = startlevel;
11455     }
11456 
11457     indexmask_grainsize = MAKE_64BIT_MASK(0, stride + 3);
11458     indexmask = MAKE_64BIT_MASK(0, inputsize - (stride * (4 - level)));
11459 
11460     /* Now we can extract the actual base address from the TTBR */
11461     descaddr = extract64(ttbr, 0, 48);
11462 
11463     /*
11464      * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [5:2] of TTBR.
11465      *
11466      * Otherwise, if the base address is out of range, raise AddressSizeFault.
11467      * In the pseudocode, this is !IsZero(baseregister<47:outputsize>),
11468      * but we've just cleared the bits above 47, so simplify the test.
11469      */
11470     if (outputsize > 48) {
11471         descaddr |= extract64(ttbr, 2, 4) << 48;
11472     } else if (descaddr >> outputsize) {
11473         level = 0;
11474         fault_type = ARMFault_AddressSize;
11475         goto do_fault;
11476     }
11477 
11478     /*
11479      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11480      * and also to mask out CnP (bit 0) which could validly be non-zero.
11481      */
11482     descaddr &= ~indexmask;
11483 
11484     /*
11485      * For AArch32, the address field in the descriptor goes up to bit 39
11486      * for both v7 and v8.  However, for v8 the SBZ bits [47:40] must be 0
11487      * or an AddressSize fault is raised.  So for v8 we extract those SBZ
11488      * bits as part of the address, which will be checked via outputsize.
11489      * For AArch64, the address field goes up to bit 47, or 49 with FEAT_LPA2;
11490      * the highest bits of a 52-bit output are placed elsewhere.
11491      */
11492     if (param.ds) {
11493         descaddrmask = MAKE_64BIT_MASK(0, 50);
11494     } else if (arm_feature(env, ARM_FEATURE_V8)) {
11495         descaddrmask = MAKE_64BIT_MASK(0, 48);
11496     } else {
11497         descaddrmask = MAKE_64BIT_MASK(0, 40);
11498     }
11499     descaddrmask &= ~indexmask_grainsize;
11500 
11501     /* Secure accesses start with the page table in secure memory and
11502      * can be downgraded to non-secure at any step. Non-secure accesses
11503      * remain non-secure. We implement this by just ORing in the NSTable/NS
11504      * bits at each step.
11505      */
11506     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11507     for (;;) {
11508         uint64_t descriptor;
11509         bool nstable;
11510 
11511         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11512         descaddr &= ~7ULL;
11513         nstable = extract32(tableattrs, 4, 1);
11514         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11515         if (fi->type != ARMFault_None) {
11516             goto do_fault;
11517         }
11518 
11519         if (!(descriptor & 1) ||
11520             (!(descriptor & 2) && (level == 3))) {
11521             /* Invalid, or the Reserved level 3 encoding */
11522             goto do_fault;
11523         }
11524 
11525         descaddr = descriptor & descaddrmask;
11526 
11527         /*
11528          * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [15:12]
11529          * of descriptor.  For FEAT_LPA2 and effective DS, bits [51:50] of
11530          * descaddr are in [9:8].  Otherwise, if descaddr is out of range,
11531          * raise AddressSizeFault.
11532          */
11533         if (outputsize > 48) {
11534             if (param.ds) {
11535                 descaddr |= extract64(descriptor, 8, 2) << 50;
11536             } else {
11537                 descaddr |= extract64(descriptor, 12, 4) << 48;
11538             }
11539         } else if (descaddr >> outputsize) {
11540             fault_type = ARMFault_AddressSize;
11541             goto do_fault;
11542         }
11543 
11544         if ((descriptor & 2) && (level < 3)) {
11545             /* Table entry. The top five bits are attributes which may
11546              * propagate down through lower levels of the table (and
11547              * which are all arranged so that 0 means "no effect", so
11548              * we can gather them up by ORing in the bits at each level).
11549              */
11550             tableattrs |= extract64(descriptor, 59, 5);
11551             level++;
11552             indexmask = indexmask_grainsize;
11553             continue;
11554         }
11555         /*
11556          * Block entry at level 1 or 2, or page entry at level 3.
11557          * These are basically the same thing, although the number
11558          * of bits we pull in from the vaddr varies. Note that although
11559          * descaddrmask masks enough of the low bits of the descriptor
11560          * to give a correct page or table address, the address field
11561          * in a block descriptor is smaller; so we need to explicitly
11562          * clear the lower bits here before ORing in the low vaddr bits.
11563          */
11564         page_size = (1ULL << ((stride * (4 - level)) + 3));
11565         descaddr &= ~(page_size - 1);
11566         descaddr |= (address & (page_size - 1));
11567         /* Extract attributes from the descriptor */
11568         attrs = extract64(descriptor, 2, 10)
11569             | (extract64(descriptor, 52, 12) << 10);
11570 
11571         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11572             /* Stage 2 table descriptors do not include any attribute fields */
11573             break;
11574         }
11575         /* Merge in attributes from table descriptors */
11576         attrs |= nstable << 3; /* NS */
11577         guarded = extract64(descriptor, 50, 1);  /* GP */
11578         if (param.hpd) {
11579             /* HPD disables all the table attributes except NSTable.  */
11580             break;
11581         }
11582         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11583         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11584          * means "force PL1 access only", which means forcing AP[1] to 0.
11585          */
11586         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11587         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11588         break;
11589     }
11590     /* Here descaddr is the final physical address, and attributes
11591      * are all in attrs.
11592      */
11593     fault_type = ARMFault_AccessFlag;
11594     if ((attrs & (1 << 8)) == 0) {
11595         /* Access flag */
11596         goto do_fault;
11597     }
11598 
11599     ap = extract32(attrs, 4, 2);
11600 
11601     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11602         ns = mmu_idx == ARMMMUIdx_Stage2;
11603         xn = extract32(attrs, 11, 2);
11604         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11605     } else {
11606         ns = extract32(attrs, 3, 1);
11607         xn = extract32(attrs, 12, 1);
11608         pxn = extract32(attrs, 11, 1);
11609         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11610     }
11611 
11612     fault_type = ARMFault_Permission;
11613     if (!(*prot & (1 << access_type))) {
11614         goto do_fault;
11615     }
11616 
11617     if (ns) {
11618         /* The NS bit will (as required by the architecture) have no effect if
11619          * the CPU doesn't support TZ or this is a non-secure translation
11620          * regime, because the attribute will already be non-secure.
11621          */
11622         txattrs->secure = false;
11623     }
11624     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11625     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11626         arm_tlb_bti_gp(txattrs) = true;
11627     }
11628 
11629     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11630         cacheattrs->attrs = convert_stage2_attrs(env, extract32(attrs, 0, 4));
11631     } else {
11632         /* Index into MAIR registers for cache attributes */
11633         uint8_t attrindx = extract32(attrs, 0, 3);
11634         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11635         assert(attrindx <= 7);
11636         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11637     }
11638 
11639     /*
11640      * For FEAT_LPA2 and effective DS, the SH field in the attributes
11641      * was re-purposed for output address bits.  The SH attribute in
11642      * that case comes from TCR_ELx, which we extracted earlier.
11643      */
11644     if (param.ds) {
11645         cacheattrs->shareability = param.sh;
11646     } else {
11647         cacheattrs->shareability = extract32(attrs, 6, 2);
11648     }
11649 
11650     *phys_ptr = descaddr;
11651     *page_size_ptr = page_size;
11652     return false;
11653 
11654 do_fault:
11655     fi->type = fault_type;
11656     fi->level = level;
11657     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11658     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2 ||
11659                                mmu_idx == ARMMMUIdx_Stage2_S);
11660     fi->s1ns = mmu_idx == ARMMMUIdx_Stage2;
11661     return true;
11662 }
11663 
11664 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11665                                                 ARMMMUIdx mmu_idx,
11666                                                 int32_t address, int *prot)
11667 {
11668     if (!arm_feature(env, ARM_FEATURE_M)) {
11669         *prot = PAGE_READ | PAGE_WRITE;
11670         switch (address) {
11671         case 0xF0000000 ... 0xFFFFFFFF:
11672             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11673                 /* hivecs execing is ok */
11674                 *prot |= PAGE_EXEC;
11675             }
11676             break;
11677         case 0x00000000 ... 0x7FFFFFFF:
11678             *prot |= PAGE_EXEC;
11679             break;
11680         }
11681     } else {
11682         /* Default system address map for M profile cores.
11683          * The architecture specifies which regions are execute-never;
11684          * at the MPU level no other checks are defined.
11685          */
11686         switch (address) {
11687         case 0x00000000 ... 0x1fffffff: /* ROM */
11688         case 0x20000000 ... 0x3fffffff: /* SRAM */
11689         case 0x60000000 ... 0x7fffffff: /* RAM */
11690         case 0x80000000 ... 0x9fffffff: /* RAM */
11691             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11692             break;
11693         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11694         case 0xa0000000 ... 0xbfffffff: /* Device */
11695         case 0xc0000000 ... 0xdfffffff: /* Device */
11696         case 0xe0000000 ... 0xffffffff: /* System */
11697             *prot = PAGE_READ | PAGE_WRITE;
11698             break;
11699         default:
11700             g_assert_not_reached();
11701         }
11702     }
11703 }
11704 
11705 static bool pmsav7_use_background_region(ARMCPU *cpu,
11706                                          ARMMMUIdx mmu_idx, bool is_user)
11707 {
11708     /* Return true if we should use the default memory map as a
11709      * "background" region if there are no hits against any MPU regions.
11710      */
11711     CPUARMState *env = &cpu->env;
11712 
11713     if (is_user) {
11714         return false;
11715     }
11716 
11717     if (arm_feature(env, ARM_FEATURE_M)) {
11718         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11719             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11720     } else {
11721         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11722     }
11723 }
11724 
11725 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11726 {
11727     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11728     return arm_feature(env, ARM_FEATURE_M) &&
11729         extract32(address, 20, 12) == 0xe00;
11730 }
11731 
11732 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11733 {
11734     /* True if address is in the M profile system region
11735      * 0xe0000000 - 0xffffffff
11736      */
11737     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11738 }
11739 
11740 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11741                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11742                                  hwaddr *phys_ptr, int *prot,
11743                                  target_ulong *page_size,
11744                                  ARMMMUFaultInfo *fi)
11745 {
11746     ARMCPU *cpu = env_archcpu(env);
11747     int n;
11748     bool is_user = regime_is_user(env, mmu_idx);
11749 
11750     *phys_ptr = address;
11751     *page_size = TARGET_PAGE_SIZE;
11752     *prot = 0;
11753 
11754     if (regime_translation_disabled(env, mmu_idx) ||
11755         m_is_ppb_region(env, address)) {
11756         /* MPU disabled or M profile PPB access: use default memory map.
11757          * The other case which uses the default memory map in the
11758          * v7M ARM ARM pseudocode is exception vector reads from the vector
11759          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11760          * which always does a direct read using address_space_ldl(), rather
11761          * than going via this function, so we don't need to check that here.
11762          */
11763         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11764     } else { /* MPU enabled */
11765         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11766             /* region search */
11767             uint32_t base = env->pmsav7.drbar[n];
11768             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11769             uint32_t rmask;
11770             bool srdis = false;
11771 
11772             if (!(env->pmsav7.drsr[n] & 0x1)) {
11773                 continue;
11774             }
11775 
11776             if (!rsize) {
11777                 qemu_log_mask(LOG_GUEST_ERROR,
11778                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11779                 continue;
11780             }
11781             rsize++;
11782             rmask = (1ull << rsize) - 1;
11783 
11784             if (base & rmask) {
11785                 qemu_log_mask(LOG_GUEST_ERROR,
11786                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11787                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11788                               n, base, rmask);
11789                 continue;
11790             }
11791 
11792             if (address < base || address > base + rmask) {
11793                 /*
11794                  * Address not in this region. We must check whether the
11795                  * region covers addresses in the same page as our address.
11796                  * In that case we must not report a size that covers the
11797                  * whole page for a subsequent hit against a different MPU
11798                  * region or the background region, because it would result in
11799                  * incorrect TLB hits for subsequent accesses to addresses that
11800                  * are in this MPU region.
11801                  */
11802                 if (ranges_overlap(base, rmask,
11803                                    address & TARGET_PAGE_MASK,
11804                                    TARGET_PAGE_SIZE)) {
11805                     *page_size = 1;
11806                 }
11807                 continue;
11808             }
11809 
11810             /* Region matched */
11811 
11812             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11813                 int i, snd;
11814                 uint32_t srdis_mask;
11815 
11816                 rsize -= 3; /* sub region size (power of 2) */
11817                 snd = ((address - base) >> rsize) & 0x7;
11818                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11819 
11820                 srdis_mask = srdis ? 0x3 : 0x0;
11821                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11822                     /* This will check in groups of 2, 4 and then 8, whether
11823                      * the subregion bits are consistent. rsize is incremented
11824                      * back up to give the region size, considering consistent
11825                      * adjacent subregions as one region. Stop testing if rsize
11826                      * is already big enough for an entire QEMU page.
11827                      */
11828                     int snd_rounded = snd & ~(i - 1);
11829                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11830                                                      snd_rounded + 8, i);
11831                     if (srdis_mask ^ srdis_multi) {
11832                         break;
11833                     }
11834                     srdis_mask = (srdis_mask << i) | srdis_mask;
11835                     rsize++;
11836                 }
11837             }
11838             if (srdis) {
11839                 continue;
11840             }
11841             if (rsize < TARGET_PAGE_BITS) {
11842                 *page_size = 1 << rsize;
11843             }
11844             break;
11845         }
11846 
11847         if (n == -1) { /* no hits */
11848             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11849                 /* background fault */
11850                 fi->type = ARMFault_Background;
11851                 return true;
11852             }
11853             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11854         } else { /* a MPU hit! */
11855             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11856             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11857 
11858             if (m_is_system_region(env, address)) {
11859                 /* System space is always execute never */
11860                 xn = 1;
11861             }
11862 
11863             if (is_user) { /* User mode AP bit decoding */
11864                 switch (ap) {
11865                 case 0:
11866                 case 1:
11867                 case 5:
11868                     break; /* no access */
11869                 case 3:
11870                     *prot |= PAGE_WRITE;
11871                     /* fall through */
11872                 case 2:
11873                 case 6:
11874                     *prot |= PAGE_READ | PAGE_EXEC;
11875                     break;
11876                 case 7:
11877                     /* for v7M, same as 6; for R profile a reserved value */
11878                     if (arm_feature(env, ARM_FEATURE_M)) {
11879                         *prot |= PAGE_READ | PAGE_EXEC;
11880                         break;
11881                     }
11882                     /* fall through */
11883                 default:
11884                     qemu_log_mask(LOG_GUEST_ERROR,
11885                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11886                                   PRIx32 "\n", n, ap);
11887                 }
11888             } else { /* Priv. mode AP bits decoding */
11889                 switch (ap) {
11890                 case 0:
11891                     break; /* no access */
11892                 case 1:
11893                 case 2:
11894                 case 3:
11895                     *prot |= PAGE_WRITE;
11896                     /* fall through */
11897                 case 5:
11898                 case 6:
11899                     *prot |= PAGE_READ | PAGE_EXEC;
11900                     break;
11901                 case 7:
11902                     /* for v7M, same as 6; for R profile a reserved value */
11903                     if (arm_feature(env, ARM_FEATURE_M)) {
11904                         *prot |= PAGE_READ | PAGE_EXEC;
11905                         break;
11906                     }
11907                     /* fall through */
11908                 default:
11909                     qemu_log_mask(LOG_GUEST_ERROR,
11910                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11911                                   PRIx32 "\n", n, ap);
11912                 }
11913             }
11914 
11915             /* execute never */
11916             if (xn) {
11917                 *prot &= ~PAGE_EXEC;
11918             }
11919         }
11920     }
11921 
11922     fi->type = ARMFault_Permission;
11923     fi->level = 1;
11924     return !(*prot & (1 << access_type));
11925 }
11926 
11927 static bool v8m_is_sau_exempt(CPUARMState *env,
11928                               uint32_t address, MMUAccessType access_type)
11929 {
11930     /* The architecture specifies that certain address ranges are
11931      * exempt from v8M SAU/IDAU checks.
11932      */
11933     return
11934         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
11935         (address >= 0xe0000000 && address <= 0xe0002fff) ||
11936         (address >= 0xe000e000 && address <= 0xe000efff) ||
11937         (address >= 0xe002e000 && address <= 0xe002efff) ||
11938         (address >= 0xe0040000 && address <= 0xe0041fff) ||
11939         (address >= 0xe00ff000 && address <= 0xe00fffff);
11940 }
11941 
11942 void v8m_security_lookup(CPUARMState *env, uint32_t address,
11943                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
11944                                 V8M_SAttributes *sattrs)
11945 {
11946     /* Look up the security attributes for this address. Compare the
11947      * pseudocode SecurityCheck() function.
11948      * We assume the caller has zero-initialized *sattrs.
11949      */
11950     ARMCPU *cpu = env_archcpu(env);
11951     int r;
11952     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
11953     int idau_region = IREGION_NOTVALID;
11954     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11955     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11956 
11957     if (cpu->idau) {
11958         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
11959         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
11960 
11961         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
11962                    &idau_nsc);
11963     }
11964 
11965     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
11966         /* 0xf0000000..0xffffffff is always S for insn fetches */
11967         return;
11968     }
11969 
11970     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
11971         sattrs->ns = !regime_is_secure(env, mmu_idx);
11972         return;
11973     }
11974 
11975     if (idau_region != IREGION_NOTVALID) {
11976         sattrs->irvalid = true;
11977         sattrs->iregion = idau_region;
11978     }
11979 
11980     switch (env->sau.ctrl & 3) {
11981     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
11982         break;
11983     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
11984         sattrs->ns = true;
11985         break;
11986     default: /* SAU.ENABLE == 1 */
11987         for (r = 0; r < cpu->sau_sregion; r++) {
11988             if (env->sau.rlar[r] & 1) {
11989                 uint32_t base = env->sau.rbar[r] & ~0x1f;
11990                 uint32_t limit = env->sau.rlar[r] | 0x1f;
11991 
11992                 if (base <= address && limit >= address) {
11993                     if (base > addr_page_base || limit < addr_page_limit) {
11994                         sattrs->subpage = true;
11995                     }
11996                     if (sattrs->srvalid) {
11997                         /* If we hit in more than one region then we must report
11998                          * as Secure, not NS-Callable, with no valid region
11999                          * number info.
12000                          */
12001                         sattrs->ns = false;
12002                         sattrs->nsc = false;
12003                         sattrs->sregion = 0;
12004                         sattrs->srvalid = false;
12005                         break;
12006                     } else {
12007                         if (env->sau.rlar[r] & 2) {
12008                             sattrs->nsc = true;
12009                         } else {
12010                             sattrs->ns = true;
12011                         }
12012                         sattrs->srvalid = true;
12013                         sattrs->sregion = r;
12014                     }
12015                 } else {
12016                     /*
12017                      * Address not in this region. We must check whether the
12018                      * region covers addresses in the same page as our address.
12019                      * In that case we must not report a size that covers the
12020                      * whole page for a subsequent hit against a different MPU
12021                      * region or the background region, because it would result
12022                      * in incorrect TLB hits for subsequent accesses to
12023                      * addresses that are in this MPU region.
12024                      */
12025                     if (limit >= base &&
12026                         ranges_overlap(base, limit - base + 1,
12027                                        addr_page_base,
12028                                        TARGET_PAGE_SIZE)) {
12029                         sattrs->subpage = true;
12030                     }
12031                 }
12032             }
12033         }
12034         break;
12035     }
12036 
12037     /*
12038      * The IDAU will override the SAU lookup results if it specifies
12039      * higher security than the SAU does.
12040      */
12041     if (!idau_ns) {
12042         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12043             sattrs->ns = false;
12044             sattrs->nsc = idau_nsc;
12045         }
12046     }
12047 }
12048 
12049 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12050                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12051                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12052                               int *prot, bool *is_subpage,
12053                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12054 {
12055     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12056      * that a full phys-to-virt translation does).
12057      * mregion is (if not NULL) set to the region number which matched,
12058      * or -1 if no region number is returned (MPU off, address did not
12059      * hit a region, address hit in multiple regions).
12060      * We set is_subpage to true if the region hit doesn't cover the
12061      * entire TARGET_PAGE the address is within.
12062      */
12063     ARMCPU *cpu = env_archcpu(env);
12064     bool is_user = regime_is_user(env, mmu_idx);
12065     uint32_t secure = regime_is_secure(env, mmu_idx);
12066     int n;
12067     int matchregion = -1;
12068     bool hit = false;
12069     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12070     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12071 
12072     *is_subpage = false;
12073     *phys_ptr = address;
12074     *prot = 0;
12075     if (mregion) {
12076         *mregion = -1;
12077     }
12078 
12079     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12080      * was an exception vector read from the vector table (which is always
12081      * done using the default system address map), because those accesses
12082      * are done in arm_v7m_load_vector(), which always does a direct
12083      * read using address_space_ldl(), rather than going via this function.
12084      */
12085     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12086         hit = true;
12087     } else if (m_is_ppb_region(env, address)) {
12088         hit = true;
12089     } else {
12090         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12091             hit = true;
12092         }
12093 
12094         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12095             /* region search */
12096             /* Note that the base address is bits [31:5] from the register
12097              * with bits [4:0] all zeroes, but the limit address is bits
12098              * [31:5] from the register with bits [4:0] all ones.
12099              */
12100             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12101             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12102 
12103             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12104                 /* Region disabled */
12105                 continue;
12106             }
12107 
12108             if (address < base || address > limit) {
12109                 /*
12110                  * Address not in this region. We must check whether the
12111                  * region covers addresses in the same page as our address.
12112                  * In that case we must not report a size that covers the
12113                  * whole page for a subsequent hit against a different MPU
12114                  * region or the background region, because it would result in
12115                  * incorrect TLB hits for subsequent accesses to addresses that
12116                  * are in this MPU region.
12117                  */
12118                 if (limit >= base &&
12119                     ranges_overlap(base, limit - base + 1,
12120                                    addr_page_base,
12121                                    TARGET_PAGE_SIZE)) {
12122                     *is_subpage = true;
12123                 }
12124                 continue;
12125             }
12126 
12127             if (base > addr_page_base || limit < addr_page_limit) {
12128                 *is_subpage = true;
12129             }
12130 
12131             if (matchregion != -1) {
12132                 /* Multiple regions match -- always a failure (unlike
12133                  * PMSAv7 where highest-numbered-region wins)
12134                  */
12135                 fi->type = ARMFault_Permission;
12136                 fi->level = 1;
12137                 return true;
12138             }
12139 
12140             matchregion = n;
12141             hit = true;
12142         }
12143     }
12144 
12145     if (!hit) {
12146         /* background fault */
12147         fi->type = ARMFault_Background;
12148         return true;
12149     }
12150 
12151     if (matchregion == -1) {
12152         /* hit using the background region */
12153         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12154     } else {
12155         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12156         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12157         bool pxn = false;
12158 
12159         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
12160             pxn = extract32(env->pmsav8.rlar[secure][matchregion], 4, 1);
12161         }
12162 
12163         if (m_is_system_region(env, address)) {
12164             /* System space is always execute never */
12165             xn = 1;
12166         }
12167 
12168         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12169         if (*prot && !xn && !(pxn && !is_user)) {
12170             *prot |= PAGE_EXEC;
12171         }
12172         /* We don't need to look the attribute up in the MAIR0/MAIR1
12173          * registers because that only tells us about cacheability.
12174          */
12175         if (mregion) {
12176             *mregion = matchregion;
12177         }
12178     }
12179 
12180     fi->type = ARMFault_Permission;
12181     fi->level = 1;
12182     return !(*prot & (1 << access_type));
12183 }
12184 
12185 
12186 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12187                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12188                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12189                                  int *prot, target_ulong *page_size,
12190                                  ARMMMUFaultInfo *fi)
12191 {
12192     uint32_t secure = regime_is_secure(env, mmu_idx);
12193     V8M_SAttributes sattrs = {};
12194     bool ret;
12195     bool mpu_is_subpage;
12196 
12197     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12198         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12199         if (access_type == MMU_INST_FETCH) {
12200             /* Instruction fetches always use the MMU bank and the
12201              * transaction attribute determined by the fetch address,
12202              * regardless of CPU state. This is painful for QEMU
12203              * to handle, because it would mean we need to encode
12204              * into the mmu_idx not just the (user, negpri) information
12205              * for the current security state but also that for the
12206              * other security state, which would balloon the number
12207              * of mmu_idx values needed alarmingly.
12208              * Fortunately we can avoid this because it's not actually
12209              * possible to arbitrarily execute code from memory with
12210              * the wrong security attribute: it will always generate
12211              * an exception of some kind or another, apart from the
12212              * special case of an NS CPU executing an SG instruction
12213              * in S&NSC memory. So we always just fail the translation
12214              * here and sort things out in the exception handler
12215              * (including possibly emulating an SG instruction).
12216              */
12217             if (sattrs.ns != !secure) {
12218                 if (sattrs.nsc) {
12219                     fi->type = ARMFault_QEMU_NSCExec;
12220                 } else {
12221                     fi->type = ARMFault_QEMU_SFault;
12222                 }
12223                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12224                 *phys_ptr = address;
12225                 *prot = 0;
12226                 return true;
12227             }
12228         } else {
12229             /* For data accesses we always use the MMU bank indicated
12230              * by the current CPU state, but the security attributes
12231              * might downgrade a secure access to nonsecure.
12232              */
12233             if (sattrs.ns) {
12234                 txattrs->secure = false;
12235             } else if (!secure) {
12236                 /* NS access to S memory must fault.
12237                  * Architecturally we should first check whether the
12238                  * MPU information for this address indicates that we
12239                  * are doing an unaligned access to Device memory, which
12240                  * should generate a UsageFault instead. QEMU does not
12241                  * currently check for that kind of unaligned access though.
12242                  * If we added it we would need to do so as a special case
12243                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12244                  */
12245                 fi->type = ARMFault_QEMU_SFault;
12246                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12247                 *phys_ptr = address;
12248                 *prot = 0;
12249                 return true;
12250             }
12251         }
12252     }
12253 
12254     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12255                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12256     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12257     return ret;
12258 }
12259 
12260 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12261                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12262                                  hwaddr *phys_ptr, int *prot,
12263                                  ARMMMUFaultInfo *fi)
12264 {
12265     int n;
12266     uint32_t mask;
12267     uint32_t base;
12268     bool is_user = regime_is_user(env, mmu_idx);
12269 
12270     if (regime_translation_disabled(env, mmu_idx)) {
12271         /* MPU disabled.  */
12272         *phys_ptr = address;
12273         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12274         return false;
12275     }
12276 
12277     *phys_ptr = address;
12278     for (n = 7; n >= 0; n--) {
12279         base = env->cp15.c6_region[n];
12280         if ((base & 1) == 0) {
12281             continue;
12282         }
12283         mask = 1 << ((base >> 1) & 0x1f);
12284         /* Keep this shift separate from the above to avoid an
12285            (undefined) << 32.  */
12286         mask = (mask << 1) - 1;
12287         if (((base ^ address) & ~mask) == 0) {
12288             break;
12289         }
12290     }
12291     if (n < 0) {
12292         fi->type = ARMFault_Background;
12293         return true;
12294     }
12295 
12296     if (access_type == MMU_INST_FETCH) {
12297         mask = env->cp15.pmsav5_insn_ap;
12298     } else {
12299         mask = env->cp15.pmsav5_data_ap;
12300     }
12301     mask = (mask >> (n * 4)) & 0xf;
12302     switch (mask) {
12303     case 0:
12304         fi->type = ARMFault_Permission;
12305         fi->level = 1;
12306         return true;
12307     case 1:
12308         if (is_user) {
12309             fi->type = ARMFault_Permission;
12310             fi->level = 1;
12311             return true;
12312         }
12313         *prot = PAGE_READ | PAGE_WRITE;
12314         break;
12315     case 2:
12316         *prot = PAGE_READ;
12317         if (!is_user) {
12318             *prot |= PAGE_WRITE;
12319         }
12320         break;
12321     case 3:
12322         *prot = PAGE_READ | PAGE_WRITE;
12323         break;
12324     case 5:
12325         if (is_user) {
12326             fi->type = ARMFault_Permission;
12327             fi->level = 1;
12328             return true;
12329         }
12330         *prot = PAGE_READ;
12331         break;
12332     case 6:
12333         *prot = PAGE_READ;
12334         break;
12335     default:
12336         /* Bad permission.  */
12337         fi->type = ARMFault_Permission;
12338         fi->level = 1;
12339         return true;
12340     }
12341     *prot |= PAGE_EXEC;
12342     return false;
12343 }
12344 
12345 /* Combine either inner or outer cacheability attributes for normal
12346  * memory, according to table D4-42 and pseudocode procedure
12347  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12348  *
12349  * NB: only stage 1 includes allocation hints (RW bits), leading to
12350  * some asymmetry.
12351  */
12352 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12353 {
12354     if (s1 == 4 || s2 == 4) {
12355         /* non-cacheable has precedence */
12356         return 4;
12357     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12358         /* stage 1 write-through takes precedence */
12359         return s1;
12360     } else if (extract32(s2, 2, 2) == 2) {
12361         /* stage 2 write-through takes precedence, but the allocation hint
12362          * is still taken from stage 1
12363          */
12364         return (2 << 2) | extract32(s1, 0, 2);
12365     } else { /* write-back */
12366         return s1;
12367     }
12368 }
12369 
12370 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12371  * and CombineS1S2Desc()
12372  *
12373  * @s1:      Attributes from stage 1 walk
12374  * @s2:      Attributes from stage 2 walk
12375  */
12376 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12377 {
12378     uint8_t s1lo, s2lo, s1hi, s2hi;
12379     ARMCacheAttrs ret;
12380     bool tagged = false;
12381 
12382     if (s1.attrs == 0xf0) {
12383         tagged = true;
12384         s1.attrs = 0xff;
12385     }
12386 
12387     s1lo = extract32(s1.attrs, 0, 4);
12388     s2lo = extract32(s2.attrs, 0, 4);
12389     s1hi = extract32(s1.attrs, 4, 4);
12390     s2hi = extract32(s2.attrs, 4, 4);
12391 
12392     /* Combine shareability attributes (table D4-43) */
12393     if (s1.shareability == 2 || s2.shareability == 2) {
12394         /* if either are outer-shareable, the result is outer-shareable */
12395         ret.shareability = 2;
12396     } else if (s1.shareability == 3 || s2.shareability == 3) {
12397         /* if either are inner-shareable, the result is inner-shareable */
12398         ret.shareability = 3;
12399     } else {
12400         /* both non-shareable */
12401         ret.shareability = 0;
12402     }
12403 
12404     /* Combine memory type and cacheability attributes */
12405     if (s1hi == 0 || s2hi == 0) {
12406         /* Device has precedence over normal */
12407         if (s1lo == 0 || s2lo == 0) {
12408             /* nGnRnE has precedence over anything */
12409             ret.attrs = 0;
12410         } else if (s1lo == 4 || s2lo == 4) {
12411             /* non-Reordering has precedence over Reordering */
12412             ret.attrs = 4;  /* nGnRE */
12413         } else if (s1lo == 8 || s2lo == 8) {
12414             /* non-Gathering has precedence over Gathering */
12415             ret.attrs = 8;  /* nGRE */
12416         } else {
12417             ret.attrs = 0xc; /* GRE */
12418         }
12419 
12420         /* Any location for which the resultant memory type is any
12421          * type of Device memory is always treated as Outer Shareable.
12422          */
12423         ret.shareability = 2;
12424     } else { /* Normal memory */
12425         /* Outer/inner cacheability combine independently */
12426         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12427                   | combine_cacheattr_nibble(s1lo, s2lo);
12428 
12429         if (ret.attrs == 0x44) {
12430             /* Any location for which the resultant memory type is Normal
12431              * Inner Non-cacheable, Outer Non-cacheable is always treated
12432              * as Outer Shareable.
12433              */
12434             ret.shareability = 2;
12435         }
12436     }
12437 
12438     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12439     if (tagged && ret.attrs == 0xff) {
12440         ret.attrs = 0xf0;
12441     }
12442 
12443     return ret;
12444 }
12445 
12446 
12447 /* get_phys_addr - get the physical address for this virtual address
12448  *
12449  * Find the physical address corresponding to the given virtual address,
12450  * by doing a translation table walk on MMU based systems or using the
12451  * MPU state on MPU based systems.
12452  *
12453  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12454  * prot and page_size may not be filled in, and the populated fsr value provides
12455  * information on why the translation aborted, in the format of a
12456  * DFSR/IFSR fault register, with the following caveats:
12457  *  * we honour the short vs long DFSR format differences.
12458  *  * the WnR bit is never set (the caller must do this).
12459  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12460  *    value.
12461  *
12462  * @env: CPUARMState
12463  * @address: virtual address to get physical address for
12464  * @access_type: 0 for read, 1 for write, 2 for execute
12465  * @mmu_idx: MMU index indicating required translation regime
12466  * @phys_ptr: set to the physical address corresponding to the virtual address
12467  * @attrs: set to the memory transaction attributes to use
12468  * @prot: set to the permissions for the page containing phys_ptr
12469  * @page_size: set to the size of the page containing phys_ptr
12470  * @fi: set to fault info if the translation fails
12471  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12472  */
12473 bool get_phys_addr(CPUARMState *env, target_ulong address,
12474                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12475                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12476                    target_ulong *page_size,
12477                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12478 {
12479     ARMMMUIdx s1_mmu_idx = stage_1_mmu_idx(mmu_idx);
12480 
12481     if (mmu_idx != s1_mmu_idx) {
12482         /* Call ourselves recursively to do the stage 1 and then stage 2
12483          * translations if mmu_idx is a two-stage regime.
12484          */
12485         if (arm_feature(env, ARM_FEATURE_EL2)) {
12486             hwaddr ipa;
12487             int s2_prot;
12488             int ret;
12489             bool ipa_secure;
12490             ARMCacheAttrs cacheattrs2 = {};
12491             ARMMMUIdx s2_mmu_idx;
12492             bool is_el0;
12493 
12494             ret = get_phys_addr(env, address, access_type, s1_mmu_idx, &ipa,
12495                                 attrs, prot, page_size, fi, cacheattrs);
12496 
12497             /* If S1 fails or S2 is disabled, return early.  */
12498             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12499                 *phys_ptr = ipa;
12500                 return ret;
12501             }
12502 
12503             ipa_secure = attrs->secure;
12504             if (arm_is_secure_below_el3(env)) {
12505                 if (ipa_secure) {
12506                     attrs->secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
12507                 } else {
12508                     attrs->secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
12509                 }
12510             } else {
12511                 assert(!ipa_secure);
12512             }
12513 
12514             s2_mmu_idx = attrs->secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
12515             is_el0 = mmu_idx == ARMMMUIdx_E10_0 || mmu_idx == ARMMMUIdx_SE10_0;
12516 
12517             /* S1 is done. Now do S2 translation.  */
12518             ret = get_phys_addr_lpae(env, ipa, access_type, s2_mmu_idx, is_el0,
12519                                      phys_ptr, attrs, &s2_prot,
12520                                      page_size, fi, &cacheattrs2);
12521             fi->s2addr = ipa;
12522             /* Combine the S1 and S2 perms.  */
12523             *prot &= s2_prot;
12524 
12525             /* If S2 fails, return early.  */
12526             if (ret) {
12527                 return ret;
12528             }
12529 
12530             /* Combine the S1 and S2 cache attributes. */
12531             if (arm_hcr_el2_eff(env) & HCR_DC) {
12532                 /*
12533                  * HCR.DC forces the first stage attributes to
12534                  *  Normal Non-Shareable,
12535                  *  Inner Write-Back Read-Allocate Write-Allocate,
12536                  *  Outer Write-Back Read-Allocate Write-Allocate.
12537                  * Do not overwrite Tagged within attrs.
12538                  */
12539                 if (cacheattrs->attrs != 0xf0) {
12540                     cacheattrs->attrs = 0xff;
12541                 }
12542                 cacheattrs->shareability = 0;
12543             }
12544             *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12545 
12546             /* Check if IPA translates to secure or non-secure PA space. */
12547             if (arm_is_secure_below_el3(env)) {
12548                 if (ipa_secure) {
12549                     attrs->secure =
12550                         !(env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW));
12551                 } else {
12552                     attrs->secure =
12553                         !((env->cp15.vtcr_el2.raw_tcr & (VTCR_NSA | VTCR_NSW))
12554                         || (env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW)));
12555                 }
12556             }
12557             return 0;
12558         } else {
12559             /*
12560              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12561              */
12562             mmu_idx = stage_1_mmu_idx(mmu_idx);
12563         }
12564     }
12565 
12566     /* The page table entries may downgrade secure to non-secure, but
12567      * cannot upgrade an non-secure translation regime's attributes
12568      * to secure.
12569      */
12570     attrs->secure = regime_is_secure(env, mmu_idx);
12571     attrs->user = regime_is_user(env, mmu_idx);
12572 
12573     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12574      * In v7 and earlier it affects all stage 1 translations.
12575      */
12576     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12577         && !arm_feature(env, ARM_FEATURE_V8)) {
12578         if (regime_el(env, mmu_idx) == 3) {
12579             address += env->cp15.fcseidr_s;
12580         } else {
12581             address += env->cp15.fcseidr_ns;
12582         }
12583     }
12584 
12585     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12586         bool ret;
12587         *page_size = TARGET_PAGE_SIZE;
12588 
12589         if (arm_feature(env, ARM_FEATURE_V8)) {
12590             /* PMSAv8 */
12591             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12592                                        phys_ptr, attrs, prot, page_size, fi);
12593         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12594             /* PMSAv7 */
12595             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12596                                        phys_ptr, prot, page_size, fi);
12597         } else {
12598             /* Pre-v7 MPU */
12599             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12600                                        phys_ptr, prot, fi);
12601         }
12602         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12603                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12604                       access_type == MMU_DATA_LOAD ? "reading" :
12605                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12606                       (uint32_t)address, mmu_idx,
12607                       ret ? "Miss" : "Hit",
12608                       *prot & PAGE_READ ? 'r' : '-',
12609                       *prot & PAGE_WRITE ? 'w' : '-',
12610                       *prot & PAGE_EXEC ? 'x' : '-');
12611 
12612         return ret;
12613     }
12614 
12615     /* Definitely a real MMU, not an MPU */
12616 
12617     if (regime_translation_disabled(env, mmu_idx)) {
12618         uint64_t hcr;
12619         uint8_t memattr;
12620 
12621         /*
12622          * MMU disabled.  S1 addresses within aa64 translation regimes are
12623          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12624          */
12625         if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
12626             int r_el = regime_el(env, mmu_idx);
12627             if (arm_el_is_aa64(env, r_el)) {
12628                 int pamax = arm_pamax(env_archcpu(env));
12629                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
12630                 int addrtop, tbi;
12631 
12632                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
12633                 if (access_type == MMU_INST_FETCH) {
12634                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
12635                 }
12636                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
12637                 addrtop = (tbi ? 55 : 63);
12638 
12639                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
12640                     fi->type = ARMFault_AddressSize;
12641                     fi->level = 0;
12642                     fi->stage2 = false;
12643                     return 1;
12644                 }
12645 
12646                 /*
12647                  * When TBI is disabled, we've just validated that all of the
12648                  * bits above PAMax are zero, so logically we only need to
12649                  * clear the top byte for TBI.  But it's clearer to follow
12650                  * the pseudocode set of addrdesc.paddress.
12651                  */
12652                 address = extract64(address, 0, 52);
12653             }
12654         }
12655         *phys_ptr = address;
12656         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12657         *page_size = TARGET_PAGE_SIZE;
12658 
12659         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
12660         hcr = arm_hcr_el2_eff(env);
12661         cacheattrs->shareability = 0;
12662         if (hcr & HCR_DC) {
12663             if (hcr & HCR_DCT) {
12664                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
12665             } else {
12666                 memattr = 0xff;  /* Normal, WB, RWA */
12667             }
12668         } else if (access_type == MMU_INST_FETCH) {
12669             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
12670                 memattr = 0xee;  /* Normal, WT, RA, NT */
12671             } else {
12672                 memattr = 0x44;  /* Normal, NC, No */
12673             }
12674             cacheattrs->shareability = 2; /* outer sharable */
12675         } else {
12676             memattr = 0x00;      /* Device, nGnRnE */
12677         }
12678         cacheattrs->attrs = memattr;
12679         return 0;
12680     }
12681 
12682     if (regime_using_lpae_format(env, mmu_idx)) {
12683         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
12684                                   phys_ptr, attrs, prot, page_size,
12685                                   fi, cacheattrs);
12686     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12687         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12688                                 phys_ptr, attrs, prot, page_size, fi);
12689     } else {
12690         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12691                                     phys_ptr, prot, page_size, fi);
12692     }
12693 }
12694 
12695 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12696                                          MemTxAttrs *attrs)
12697 {
12698     ARMCPU *cpu = ARM_CPU(cs);
12699     CPUARMState *env = &cpu->env;
12700     hwaddr phys_addr;
12701     target_ulong page_size;
12702     int prot;
12703     bool ret;
12704     ARMMMUFaultInfo fi = {};
12705     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12706     ARMCacheAttrs cacheattrs = {};
12707 
12708     *attrs = (MemTxAttrs) {};
12709 
12710     ret = get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &phys_addr,
12711                         attrs, &prot, &page_size, &fi, &cacheattrs);
12712 
12713     if (ret) {
12714         return -1;
12715     }
12716     return phys_addr;
12717 }
12718 
12719 #endif
12720 
12721 /* Note that signed overflow is undefined in C.  The following routines are
12722    careful to use unsigned types where modulo arithmetic is required.
12723    Failure to do so _will_ break on newer gcc.  */
12724 
12725 /* Signed saturating arithmetic.  */
12726 
12727 /* Perform 16-bit signed saturating addition.  */
12728 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
12729 {
12730     uint16_t res;
12731 
12732     res = a + b;
12733     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
12734         if (a & 0x8000)
12735             res = 0x8000;
12736         else
12737             res = 0x7fff;
12738     }
12739     return res;
12740 }
12741 
12742 /* Perform 8-bit signed saturating addition.  */
12743 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
12744 {
12745     uint8_t res;
12746 
12747     res = a + b;
12748     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
12749         if (a & 0x80)
12750             res = 0x80;
12751         else
12752             res = 0x7f;
12753     }
12754     return res;
12755 }
12756 
12757 /* Perform 16-bit signed saturating subtraction.  */
12758 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
12759 {
12760     uint16_t res;
12761 
12762     res = a - b;
12763     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
12764         if (a & 0x8000)
12765             res = 0x8000;
12766         else
12767             res = 0x7fff;
12768     }
12769     return res;
12770 }
12771 
12772 /* Perform 8-bit signed saturating subtraction.  */
12773 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12774 {
12775     uint8_t res;
12776 
12777     res = a - b;
12778     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12779         if (a & 0x80)
12780             res = 0x80;
12781         else
12782             res = 0x7f;
12783     }
12784     return res;
12785 }
12786 
12787 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12788 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12789 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12790 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12791 #define PFX q
12792 
12793 #include "op_addsub.h"
12794 
12795 /* Unsigned saturating arithmetic.  */
12796 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12797 {
12798     uint16_t res;
12799     res = a + b;
12800     if (res < a)
12801         res = 0xffff;
12802     return res;
12803 }
12804 
12805 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12806 {
12807     if (a > b)
12808         return a - b;
12809     else
12810         return 0;
12811 }
12812 
12813 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12814 {
12815     uint8_t res;
12816     res = a + b;
12817     if (res < a)
12818         res = 0xff;
12819     return res;
12820 }
12821 
12822 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12823 {
12824     if (a > b)
12825         return a - b;
12826     else
12827         return 0;
12828 }
12829 
12830 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12831 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12832 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12833 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12834 #define PFX uq
12835 
12836 #include "op_addsub.h"
12837 
12838 /* Signed modulo arithmetic.  */
12839 #define SARITH16(a, b, n, op) do { \
12840     int32_t sum; \
12841     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12842     RESULT(sum, n, 16); \
12843     if (sum >= 0) \
12844         ge |= 3 << (n * 2); \
12845     } while(0)
12846 
12847 #define SARITH8(a, b, n, op) do { \
12848     int32_t sum; \
12849     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
12850     RESULT(sum, n, 8); \
12851     if (sum >= 0) \
12852         ge |= 1 << n; \
12853     } while(0)
12854 
12855 
12856 #define ADD16(a, b, n) SARITH16(a, b, n, +)
12857 #define SUB16(a, b, n) SARITH16(a, b, n, -)
12858 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
12859 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
12860 #define PFX s
12861 #define ARITH_GE
12862 
12863 #include "op_addsub.h"
12864 
12865 /* Unsigned modulo arithmetic.  */
12866 #define ADD16(a, b, n) do { \
12867     uint32_t sum; \
12868     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
12869     RESULT(sum, n, 16); \
12870     if ((sum >> 16) == 1) \
12871         ge |= 3 << (n * 2); \
12872     } while(0)
12873 
12874 #define ADD8(a, b, n) do { \
12875     uint32_t sum; \
12876     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
12877     RESULT(sum, n, 8); \
12878     if ((sum >> 8) == 1) \
12879         ge |= 1 << n; \
12880     } while(0)
12881 
12882 #define SUB16(a, b, n) do { \
12883     uint32_t sum; \
12884     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
12885     RESULT(sum, n, 16); \
12886     if ((sum >> 16) == 0) \
12887         ge |= 3 << (n * 2); \
12888     } while(0)
12889 
12890 #define SUB8(a, b, n) do { \
12891     uint32_t sum; \
12892     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
12893     RESULT(sum, n, 8); \
12894     if ((sum >> 8) == 0) \
12895         ge |= 1 << n; \
12896     } while(0)
12897 
12898 #define PFX u
12899 #define ARITH_GE
12900 
12901 #include "op_addsub.h"
12902 
12903 /* Halved signed arithmetic.  */
12904 #define ADD16(a, b, n) \
12905   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
12906 #define SUB16(a, b, n) \
12907   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
12908 #define ADD8(a, b, n) \
12909   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
12910 #define SUB8(a, b, n) \
12911   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
12912 #define PFX sh
12913 
12914 #include "op_addsub.h"
12915 
12916 /* Halved unsigned arithmetic.  */
12917 #define ADD16(a, b, n) \
12918   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12919 #define SUB16(a, b, n) \
12920   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12921 #define ADD8(a, b, n) \
12922   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12923 #define SUB8(a, b, n) \
12924   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12925 #define PFX uh
12926 
12927 #include "op_addsub.h"
12928 
12929 static inline uint8_t do_usad(uint8_t a, uint8_t b)
12930 {
12931     if (a > b)
12932         return a - b;
12933     else
12934         return b - a;
12935 }
12936 
12937 /* Unsigned sum of absolute byte differences.  */
12938 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
12939 {
12940     uint32_t sum;
12941     sum = do_usad(a, b);
12942     sum += do_usad(a >> 8, b >> 8);
12943     sum += do_usad(a >> 16, b >> 16);
12944     sum += do_usad(a >> 24, b >> 24);
12945     return sum;
12946 }
12947 
12948 /* For ARMv6 SEL instruction.  */
12949 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
12950 {
12951     uint32_t mask;
12952 
12953     mask = 0;
12954     if (flags & 1)
12955         mask |= 0xff;
12956     if (flags & 2)
12957         mask |= 0xff00;
12958     if (flags & 4)
12959         mask |= 0xff0000;
12960     if (flags & 8)
12961         mask |= 0xff000000;
12962     return (a & mask) | (b & ~mask);
12963 }
12964 
12965 /* CRC helpers.
12966  * The upper bytes of val (above the number specified by 'bytes') must have
12967  * been zeroed out by the caller.
12968  */
12969 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12970 {
12971     uint8_t buf[4];
12972 
12973     stl_le_p(buf, val);
12974 
12975     /* zlib crc32 converts the accumulator and output to one's complement.  */
12976     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12977 }
12978 
12979 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12980 {
12981     uint8_t buf[4];
12982 
12983     stl_le_p(buf, val);
12984 
12985     /* Linux crc32c converts the output to one's complement.  */
12986     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12987 }
12988 
12989 /* Return the exception level to which FP-disabled exceptions should
12990  * be taken, or 0 if FP is enabled.
12991  */
12992 int fp_exception_el(CPUARMState *env, int cur_el)
12993 {
12994 #ifndef CONFIG_USER_ONLY
12995     uint64_t hcr_el2;
12996 
12997     /* CPACR and the CPTR registers don't exist before v6, so FP is
12998      * always accessible
12999      */
13000     if (!arm_feature(env, ARM_FEATURE_V6)) {
13001         return 0;
13002     }
13003 
13004     if (arm_feature(env, ARM_FEATURE_M)) {
13005         /* CPACR can cause a NOCP UsageFault taken to current security state */
13006         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13007             return 1;
13008         }
13009 
13010         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13011             if (!extract32(env->v7m.nsacr, 10, 1)) {
13012                 /* FP insns cause a NOCP UsageFault taken to Secure */
13013                 return 3;
13014             }
13015         }
13016 
13017         return 0;
13018     }
13019 
13020     hcr_el2 = arm_hcr_el2_eff(env);
13021 
13022     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13023      * 0, 2 : trap EL0 and EL1/PL1 accesses
13024      * 1    : trap only EL0 accesses
13025      * 3    : trap no accesses
13026      * This register is ignored if E2H+TGE are both set.
13027      */
13028     if ((hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13029         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
13030 
13031         switch (fpen) {
13032         case 0:
13033         case 2:
13034             if (cur_el == 0 || cur_el == 1) {
13035                 /* Trap to PL1, which might be EL1 or EL3 */
13036                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13037                     return 3;
13038                 }
13039                 return 1;
13040             }
13041             if (cur_el == 3 && !is_a64(env)) {
13042                 /* Secure PL1 running at EL3 */
13043                 return 3;
13044             }
13045             break;
13046         case 1:
13047             if (cur_el == 0) {
13048                 return 1;
13049             }
13050             break;
13051         case 3:
13052             break;
13053         }
13054     }
13055 
13056     /*
13057      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
13058      * to control non-secure access to the FPU. It doesn't have any
13059      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
13060      */
13061     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
13062          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
13063         if (!extract32(env->cp15.nsacr, 10, 1)) {
13064             /* FP insns act as UNDEF */
13065             return cur_el == 2 ? 2 : 1;
13066         }
13067     }
13068 
13069     /*
13070      * CPTR_EL2 is present in v7VE or v8, and changes format
13071      * with HCR_EL2.E2H (regardless of TGE).
13072      */
13073     if (cur_el <= 2) {
13074         if (hcr_el2 & HCR_E2H) {
13075             /* Check CPTR_EL2.FPEN.  */
13076             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
13077             case 1:
13078                 if (cur_el != 0 || !(hcr_el2 & HCR_TGE)) {
13079                     break;
13080                 }
13081                 /* fall through */
13082             case 0:
13083             case 2:
13084                 return 2;
13085             }
13086         } else if (arm_is_el2_enabled(env)) {
13087             if (env->cp15.cptr_el[2] & CPTR_TFP) {
13088                 return 2;
13089             }
13090         }
13091     }
13092 
13093     /* CPTR_EL3 : present in v8 */
13094     if (env->cp15.cptr_el[3] & CPTR_TFP) {
13095         /* Trap all FP ops to EL3 */
13096         return 3;
13097     }
13098 #endif
13099     return 0;
13100 }
13101 
13102 /* Return the exception level we're running at if this is our mmu_idx */
13103 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
13104 {
13105     if (mmu_idx & ARM_MMU_IDX_M) {
13106         return mmu_idx & ARM_MMU_IDX_M_PRIV;
13107     }
13108 
13109     switch (mmu_idx) {
13110     case ARMMMUIdx_E10_0:
13111     case ARMMMUIdx_E20_0:
13112     case ARMMMUIdx_SE10_0:
13113     case ARMMMUIdx_SE20_0:
13114         return 0;
13115     case ARMMMUIdx_E10_1:
13116     case ARMMMUIdx_E10_1_PAN:
13117     case ARMMMUIdx_SE10_1:
13118     case ARMMMUIdx_SE10_1_PAN:
13119         return 1;
13120     case ARMMMUIdx_E2:
13121     case ARMMMUIdx_E20_2:
13122     case ARMMMUIdx_E20_2_PAN:
13123     case ARMMMUIdx_SE2:
13124     case ARMMMUIdx_SE20_2:
13125     case ARMMMUIdx_SE20_2_PAN:
13126         return 2;
13127     case ARMMMUIdx_SE3:
13128         return 3;
13129     default:
13130         g_assert_not_reached();
13131     }
13132 }
13133 
13134 #ifndef CONFIG_TCG
13135 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13136 {
13137     g_assert_not_reached();
13138 }
13139 #endif
13140 
13141 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
13142 {
13143     ARMMMUIdx idx;
13144     uint64_t hcr;
13145 
13146     if (arm_feature(env, ARM_FEATURE_M)) {
13147         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13148     }
13149 
13150     /* See ARM pseudo-function ELIsInHost.  */
13151     switch (el) {
13152     case 0:
13153         hcr = arm_hcr_el2_eff(env);
13154         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
13155             idx = ARMMMUIdx_E20_0;
13156         } else {
13157             idx = ARMMMUIdx_E10_0;
13158         }
13159         break;
13160     case 1:
13161         if (env->pstate & PSTATE_PAN) {
13162             idx = ARMMMUIdx_E10_1_PAN;
13163         } else {
13164             idx = ARMMMUIdx_E10_1;
13165         }
13166         break;
13167     case 2:
13168         /* Note that TGE does not apply at EL2.  */
13169         if (arm_hcr_el2_eff(env) & HCR_E2H) {
13170             if (env->pstate & PSTATE_PAN) {
13171                 idx = ARMMMUIdx_E20_2_PAN;
13172             } else {
13173                 idx = ARMMMUIdx_E20_2;
13174             }
13175         } else {
13176             idx = ARMMMUIdx_E2;
13177         }
13178         break;
13179     case 3:
13180         return ARMMMUIdx_SE3;
13181     default:
13182         g_assert_not_reached();
13183     }
13184 
13185     if (arm_is_secure_below_el3(env)) {
13186         idx &= ~ARM_MMU_IDX_A_NS;
13187     }
13188 
13189     return idx;
13190 }
13191 
13192 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13193 {
13194     return arm_mmu_idx_el(env, arm_current_el(env));
13195 }
13196 
13197 #ifndef CONFIG_USER_ONLY
13198 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13199 {
13200     return stage_1_mmu_idx(arm_mmu_idx(env));
13201 }
13202 #endif
13203 
13204 static CPUARMTBFlags rebuild_hflags_common(CPUARMState *env, int fp_el,
13205                                            ARMMMUIdx mmu_idx,
13206                                            CPUARMTBFlags flags)
13207 {
13208     DP_TBFLAG_ANY(flags, FPEXC_EL, fp_el);
13209     DP_TBFLAG_ANY(flags, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13210 
13211     if (arm_singlestep_active(env)) {
13212         DP_TBFLAG_ANY(flags, SS_ACTIVE, 1);
13213     }
13214     return flags;
13215 }
13216 
13217 static CPUARMTBFlags rebuild_hflags_common_32(CPUARMState *env, int fp_el,
13218                                               ARMMMUIdx mmu_idx,
13219                                               CPUARMTBFlags flags)
13220 {
13221     bool sctlr_b = arm_sctlr_b(env);
13222 
13223     if (sctlr_b) {
13224         DP_TBFLAG_A32(flags, SCTLR__B, 1);
13225     }
13226     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
13227         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13228     }
13229     DP_TBFLAG_A32(flags, NS, !access_secure_reg(env));
13230 
13231     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13232 }
13233 
13234 static CPUARMTBFlags rebuild_hflags_m32(CPUARMState *env, int fp_el,
13235                                         ARMMMUIdx mmu_idx)
13236 {
13237     CPUARMTBFlags flags = {};
13238     uint32_t ccr = env->v7m.ccr[env->v7m.secure];
13239 
13240     /* Without HaveMainExt, CCR.UNALIGN_TRP is RES1. */
13241     if (ccr & R_V7M_CCR_UNALIGN_TRP_MASK) {
13242         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13243     }
13244 
13245     if (arm_v7m_is_handler_mode(env)) {
13246         DP_TBFLAG_M32(flags, HANDLER, 1);
13247     }
13248 
13249     /*
13250      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
13251      * is suppressing them because the requested execution priority
13252      * is less than 0.
13253      */
13254     if (arm_feature(env, ARM_FEATURE_V8) &&
13255         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
13256           (ccr & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13257         DP_TBFLAG_M32(flags, STACKCHECK, 1);
13258     }
13259 
13260     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13261 }
13262 
13263 static CPUARMTBFlags rebuild_hflags_aprofile(CPUARMState *env)
13264 {
13265     CPUARMTBFlags flags = {};
13266 
13267     DP_TBFLAG_ANY(flags, DEBUG_TARGET_EL, arm_debug_target_el(env));
13268     return flags;
13269 }
13270 
13271 static CPUARMTBFlags rebuild_hflags_a32(CPUARMState *env, int fp_el,
13272                                         ARMMMUIdx mmu_idx)
13273 {
13274     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13275     int el = arm_current_el(env);
13276 
13277     if (arm_sctlr(env, el) & SCTLR_A) {
13278         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13279     }
13280 
13281     if (arm_el_is_aa64(env, 1)) {
13282         DP_TBFLAG_A32(flags, VFPEN, 1);
13283     }
13284 
13285     if (el < 2 && env->cp15.hstr_el2 &&
13286         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13287         DP_TBFLAG_A32(flags, HSTR_ACTIVE, 1);
13288     }
13289 
13290     if (env->uncached_cpsr & CPSR_IL) {
13291         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13292     }
13293 
13294     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13295 }
13296 
13297 static CPUARMTBFlags rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
13298                                         ARMMMUIdx mmu_idx)
13299 {
13300     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13301     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13302     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
13303     uint64_t sctlr;
13304     int tbii, tbid;
13305 
13306     DP_TBFLAG_ANY(flags, AARCH64_STATE, 1);
13307 
13308     /* Get control bits for tagged addresses.  */
13309     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
13310     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
13311 
13312     DP_TBFLAG_A64(flags, TBII, tbii);
13313     DP_TBFLAG_A64(flags, TBID, tbid);
13314 
13315     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
13316         int sve_el = sve_exception_el(env, el);
13317         uint32_t zcr_len;
13318 
13319         /*
13320          * If SVE is disabled, but FP is enabled,
13321          * then the effective len is 0.
13322          */
13323         if (sve_el != 0 && fp_el == 0) {
13324             zcr_len = 0;
13325         } else {
13326             zcr_len = sve_zcr_len_for_el(env, el);
13327         }
13328         DP_TBFLAG_A64(flags, SVEEXC_EL, sve_el);
13329         DP_TBFLAG_A64(flags, ZCR_LEN, zcr_len);
13330     }
13331 
13332     sctlr = regime_sctlr(env, stage1);
13333 
13334     if (sctlr & SCTLR_A) {
13335         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13336     }
13337 
13338     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
13339         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13340     }
13341 
13342     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
13343         /*
13344          * In order to save space in flags, we record only whether
13345          * pauth is "inactive", meaning all insns are implemented as
13346          * a nop, or "active" when some action must be performed.
13347          * The decision of which action to take is left to a helper.
13348          */
13349         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13350             DP_TBFLAG_A64(flags, PAUTH_ACTIVE, 1);
13351         }
13352     }
13353 
13354     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13355         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13356         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13357             DP_TBFLAG_A64(flags, BT, 1);
13358         }
13359     }
13360 
13361     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
13362     if (!(env->pstate & PSTATE_UAO)) {
13363         switch (mmu_idx) {
13364         case ARMMMUIdx_E10_1:
13365         case ARMMMUIdx_E10_1_PAN:
13366         case ARMMMUIdx_SE10_1:
13367         case ARMMMUIdx_SE10_1_PAN:
13368             /* TODO: ARMv8.3-NV */
13369             DP_TBFLAG_A64(flags, UNPRIV, 1);
13370             break;
13371         case ARMMMUIdx_E20_2:
13372         case ARMMMUIdx_E20_2_PAN:
13373         case ARMMMUIdx_SE20_2:
13374         case ARMMMUIdx_SE20_2_PAN:
13375             /*
13376              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
13377              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
13378              */
13379             if (env->cp15.hcr_el2 & HCR_TGE) {
13380                 DP_TBFLAG_A64(flags, UNPRIV, 1);
13381             }
13382             break;
13383         default:
13384             break;
13385         }
13386     }
13387 
13388     if (env->pstate & PSTATE_IL) {
13389         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13390     }
13391 
13392     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
13393         /*
13394          * Set MTE_ACTIVE if any access may be Checked, and leave clear
13395          * if all accesses must be Unchecked:
13396          * 1) If no TBI, then there are no tags in the address to check,
13397          * 2) If Tag Check Override, then all accesses are Unchecked,
13398          * 3) If Tag Check Fail == 0, then Checked access have no effect,
13399          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
13400          */
13401         if (allocation_tag_access_enabled(env, el, sctlr)) {
13402             DP_TBFLAG_A64(flags, ATA, 1);
13403             if (tbid
13404                 && !(env->pstate & PSTATE_TCO)
13405                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
13406                 DP_TBFLAG_A64(flags, MTE_ACTIVE, 1);
13407             }
13408         }
13409         /* And again for unprivileged accesses, if required.  */
13410         if (EX_TBFLAG_A64(flags, UNPRIV)
13411             && tbid
13412             && !(env->pstate & PSTATE_TCO)
13413             && (sctlr & SCTLR_TCF0)
13414             && allocation_tag_access_enabled(env, 0, sctlr)) {
13415             DP_TBFLAG_A64(flags, MTE0_ACTIVE, 1);
13416         }
13417         /* Cache TCMA as well as TBI. */
13418         DP_TBFLAG_A64(flags, TCMA, aa64_va_parameter_tcma(tcr, mmu_idx));
13419     }
13420 
13421     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13422 }
13423 
13424 static CPUARMTBFlags rebuild_hflags_internal(CPUARMState *env)
13425 {
13426     int el = arm_current_el(env);
13427     int fp_el = fp_exception_el(env, el);
13428     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13429 
13430     if (is_a64(env)) {
13431         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13432     } else if (arm_feature(env, ARM_FEATURE_M)) {
13433         return rebuild_hflags_m32(env, fp_el, mmu_idx);
13434     } else {
13435         return rebuild_hflags_a32(env, fp_el, mmu_idx);
13436     }
13437 }
13438 
13439 void arm_rebuild_hflags(CPUARMState *env)
13440 {
13441     env->hflags = rebuild_hflags_internal(env);
13442 }
13443 
13444 /*
13445  * If we have triggered a EL state change we can't rely on the
13446  * translator having passed it to us, we need to recompute.
13447  */
13448 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
13449 {
13450     int el = arm_current_el(env);
13451     int fp_el = fp_exception_el(env, el);
13452     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13453 
13454     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13455 }
13456 
13457 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
13458 {
13459     int fp_el = fp_exception_el(env, el);
13460     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13461 
13462     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13463 }
13464 
13465 /*
13466  * If we have triggered a EL state change we can't rely on the
13467  * translator having passed it to us, we need to recompute.
13468  */
13469 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
13470 {
13471     int el = arm_current_el(env);
13472     int fp_el = fp_exception_el(env, el);
13473     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13474     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13475 }
13476 
13477 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
13478 {
13479     int fp_el = fp_exception_el(env, el);
13480     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13481 
13482     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13483 }
13484 
13485 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
13486 {
13487     int fp_el = fp_exception_el(env, el);
13488     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13489 
13490     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13491 }
13492 
13493 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
13494 {
13495 #ifdef CONFIG_DEBUG_TCG
13496     CPUARMTBFlags c = env->hflags;
13497     CPUARMTBFlags r = rebuild_hflags_internal(env);
13498 
13499     if (unlikely(c.flags != r.flags || c.flags2 != r.flags2)) {
13500         fprintf(stderr, "TCG hflags mismatch "
13501                         "(current:(0x%08x,0x" TARGET_FMT_lx ")"
13502                         " rebuilt:(0x%08x,0x" TARGET_FMT_lx ")\n",
13503                 c.flags, c.flags2, r.flags, r.flags2);
13504         abort();
13505     }
13506 #endif
13507 }
13508 
13509 static bool mve_no_pred(CPUARMState *env)
13510 {
13511     /*
13512      * Return true if there is definitely no predication of MVE
13513      * instructions by VPR or LTPSIZE. (Returning false even if there
13514      * isn't any predication is OK; generated code will just be
13515      * a little worse.)
13516      * If the CPU does not implement MVE then this TB flag is always 0.
13517      *
13518      * NOTE: if you change this logic, the "recalculate s->mve_no_pred"
13519      * logic in gen_update_fp_context() needs to be updated to match.
13520      *
13521      * We do not include the effect of the ECI bits here -- they are
13522      * tracked in other TB flags. This simplifies the logic for
13523      * "when did we emit code that changes the MVE_NO_PRED TB flag
13524      * and thus need to end the TB?".
13525      */
13526     if (cpu_isar_feature(aa32_mve, env_archcpu(env))) {
13527         return false;
13528     }
13529     if (env->v7m.vpr) {
13530         return false;
13531     }
13532     if (env->v7m.ltpsize < 4) {
13533         return false;
13534     }
13535     return true;
13536 }
13537 
13538 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13539                           target_ulong *cs_base, uint32_t *pflags)
13540 {
13541     CPUARMTBFlags flags;
13542 
13543     assert_hflags_rebuild_correctly(env);
13544     flags = env->hflags;
13545 
13546     if (EX_TBFLAG_ANY(flags, AARCH64_STATE)) {
13547         *pc = env->pc;
13548         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13549             DP_TBFLAG_A64(flags, BTYPE, env->btype);
13550         }
13551     } else {
13552         *pc = env->regs[15];
13553 
13554         if (arm_feature(env, ARM_FEATURE_M)) {
13555             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13556                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13557                 != env->v7m.secure) {
13558                 DP_TBFLAG_M32(flags, FPCCR_S_WRONG, 1);
13559             }
13560 
13561             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13562                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13563                  (env->v7m.secure &&
13564                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13565                 /*
13566                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13567                  * active FP context; we must create a new FP context before
13568                  * executing any FP insn.
13569                  */
13570                 DP_TBFLAG_M32(flags, NEW_FP_CTXT_NEEDED, 1);
13571             }
13572 
13573             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13574             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13575                 DP_TBFLAG_M32(flags, LSPACT, 1);
13576             }
13577 
13578             if (mve_no_pred(env)) {
13579                 DP_TBFLAG_M32(flags, MVE_NO_PRED, 1);
13580             }
13581         } else {
13582             /*
13583              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13584              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13585              */
13586             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13587                 DP_TBFLAG_A32(flags, XSCALE_CPAR, env->cp15.c15_cpar);
13588             } else {
13589                 DP_TBFLAG_A32(flags, VECLEN, env->vfp.vec_len);
13590                 DP_TBFLAG_A32(flags, VECSTRIDE, env->vfp.vec_stride);
13591             }
13592             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13593                 DP_TBFLAG_A32(flags, VFPEN, 1);
13594             }
13595         }
13596 
13597         DP_TBFLAG_AM32(flags, THUMB, env->thumb);
13598         DP_TBFLAG_AM32(flags, CONDEXEC, env->condexec_bits);
13599     }
13600 
13601     /*
13602      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13603      * states defined in the ARM ARM for software singlestep:
13604      *  SS_ACTIVE   PSTATE.SS   State
13605      *     0            x       Inactive (the TB flag for SS is always 0)
13606      *     1            0       Active-pending
13607      *     1            1       Active-not-pending
13608      * SS_ACTIVE is set in hflags; PSTATE__SS is computed every TB.
13609      */
13610     if (EX_TBFLAG_ANY(flags, SS_ACTIVE) && (env->pstate & PSTATE_SS)) {
13611         DP_TBFLAG_ANY(flags, PSTATE__SS, 1);
13612     }
13613 
13614     *pflags = flags.flags;
13615     *cs_base = flags.flags2;
13616 }
13617 
13618 #ifdef TARGET_AARCH64
13619 /*
13620  * The manual says that when SVE is enabled and VQ is widened the
13621  * implementation is allowed to zero the previously inaccessible
13622  * portion of the registers.  The corollary to that is that when
13623  * SVE is enabled and VQ is narrowed we are also allowed to zero
13624  * the now inaccessible portion of the registers.
13625  *
13626  * The intent of this is that no predicate bit beyond VQ is ever set.
13627  * Which means that some operations on predicate registers themselves
13628  * may operate on full uint64_t or even unrolled across the maximum
13629  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13630  * may well be cheaper than conditionals to restrict the operation
13631  * to the relevant portion of a uint16_t[16].
13632  */
13633 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13634 {
13635     int i, j;
13636     uint64_t pmask;
13637 
13638     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13639     assert(vq <= env_archcpu(env)->sve_max_vq);
13640 
13641     /* Zap the high bits of the zregs.  */
13642     for (i = 0; i < 32; i++) {
13643         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13644     }
13645 
13646     /* Zap the high bits of the pregs and ffr.  */
13647     pmask = 0;
13648     if (vq & 3) {
13649         pmask = ~(-1ULL << (16 * (vq & 3)));
13650     }
13651     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13652         for (i = 0; i < 17; ++i) {
13653             env->vfp.pregs[i].p[j] &= pmask;
13654         }
13655         pmask = 0;
13656     }
13657 }
13658 
13659 /*
13660  * Notice a change in SVE vector size when changing EL.
13661  */
13662 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13663                            int new_el, bool el0_a64)
13664 {
13665     ARMCPU *cpu = env_archcpu(env);
13666     int old_len, new_len;
13667     bool old_a64, new_a64;
13668 
13669     /* Nothing to do if no SVE.  */
13670     if (!cpu_isar_feature(aa64_sve, cpu)) {
13671         return;
13672     }
13673 
13674     /* Nothing to do if FP is disabled in either EL.  */
13675     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13676         return;
13677     }
13678 
13679     /*
13680      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13681      * at ELx, or not available because the EL is in AArch32 state, then
13682      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13683      * has an effective value of 0".
13684      *
13685      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13686      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13687      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13688      * we already have the correct register contents when encountering the
13689      * vq0->vq0 transition between EL0->EL1.
13690      */
13691     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13692     old_len = (old_a64 && !sve_exception_el(env, old_el)
13693                ? sve_zcr_len_for_el(env, old_el) : 0);
13694     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13695     new_len = (new_a64 && !sve_exception_el(env, new_el)
13696                ? sve_zcr_len_for_el(env, new_el) : 0);
13697 
13698     /* When changing vector length, clear inaccessible state.  */
13699     if (new_len < old_len) {
13700         aarch64_sve_narrow_vq(env, new_len + 1);
13701     }
13702 }
13703 #endif
13704