]> Git Repo - qemu.git/blob - target/arm/helper.c
target/arm: Implement XPSR GE bits
[qemu.git] / target / arm / helper.c
1 #include "qemu/osdep.h"
2 #include "target/arm/idau.h"
3 #include "trace.h"
4 #include "cpu.h"
5 #include "internals.h"
6 #include "exec/gdbstub.h"
7 #include "exec/helper-proto.h"
8 #include "qemu/host-utils.h"
9 #include "sysemu/arch_init.h"
10 #include "sysemu/sysemu.h"
11 #include "qemu/bitops.h"
12 #include "qemu/crc32c.h"
13 #include "qemu/qemu-print.h"
14 #include "exec/exec-all.h"
15 #include "exec/cpu_ldst.h"
16 #include "arm_ldst.h"
17 #include <zlib.h> /* For crc32 */
18 #include "exec/semihost.h"
19 #include "sysemu/cpus.h"
20 #include "sysemu/kvm.h"
21 #include "fpu/softfloat.h"
22 #include "qemu/range.h"
23 #include "qapi/qapi-commands-target.h"
24
25 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
26
27 #ifndef CONFIG_USER_ONLY
28 /* Cacheability and shareability attributes for a memory access */
29 typedef struct ARMCacheAttrs {
30     unsigned int attrs:8; /* as in the MAIR register encoding */
31     unsigned int shareability:2; /* as in the SH field of the VMSAv8-64 PTEs */
32 } ARMCacheAttrs;
33
34 static bool get_phys_addr(CPUARMState *env, target_ulong address,
35                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
36                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
37                           target_ulong *page_size,
38                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
39
40 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
41                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
42                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
43                                target_ulong *page_size_ptr,
44                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
45
46 /* Security attributes for an address, as returned by v8m_security_lookup. */
47 typedef struct V8M_SAttributes {
48     bool subpage; /* true if these attrs don't cover the whole TARGET_PAGE */
49     bool ns;
50     bool nsc;
51     uint8_t sregion;
52     bool srvalid;
53     uint8_t iregion;
54     bool irvalid;
55 } V8M_SAttributes;
56
57 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
58                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
59                                 V8M_SAttributes *sattrs);
60 #endif
61
62 static void switch_mode(CPUARMState *env, int mode);
63
64 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
65 {
66     int nregs;
67
68     /* VFP data registers are always little-endian.  */
69     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
70     if (reg < nregs) {
71         stq_le_p(buf, *aa32_vfp_dreg(env, reg));
72         return 8;
73     }
74     if (arm_feature(env, ARM_FEATURE_NEON)) {
75         /* Aliases for Q regs.  */
76         nregs += 16;
77         if (reg < nregs) {
78             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
79             stq_le_p(buf, q[0]);
80             stq_le_p(buf + 8, q[1]);
81             return 16;
82         }
83     }
84     switch (reg - nregs) {
85     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
86     case 1: stl_p(buf, vfp_get_fpscr(env)); return 4;
87     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
88     }
89     return 0;
90 }
91
92 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
93 {
94     int nregs;
95
96     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
97     if (reg < nregs) {
98         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
99         return 8;
100     }
101     if (arm_feature(env, ARM_FEATURE_NEON)) {
102         nregs += 16;
103         if (reg < nregs) {
104             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
105             q[0] = ldq_le_p(buf);
106             q[1] = ldq_le_p(buf + 8);
107             return 16;
108         }
109     }
110     switch (reg - nregs) {
111     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
112     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
113     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
114     }
115     return 0;
116 }
117
118 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
119 {
120     switch (reg) {
121     case 0 ... 31:
122         /* 128 bit FP register */
123         {
124             uint64_t *q = aa64_vfp_qreg(env, reg);
125             stq_le_p(buf, q[0]);
126             stq_le_p(buf + 8, q[1]);
127             return 16;
128         }
129     case 32:
130         /* FPSR */
131         stl_p(buf, vfp_get_fpsr(env));
132         return 4;
133     case 33:
134         /* FPCR */
135         stl_p(buf, vfp_get_fpcr(env));
136         return 4;
137     default:
138         return 0;
139     }
140 }
141
142 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
143 {
144     switch (reg) {
145     case 0 ... 31:
146         /* 128 bit FP register */
147         {
148             uint64_t *q = aa64_vfp_qreg(env, reg);
149             q[0] = ldq_le_p(buf);
150             q[1] = ldq_le_p(buf + 8);
151             return 16;
152         }
153     case 32:
154         /* FPSR */
155         vfp_set_fpsr(env, ldl_p(buf));
156         return 4;
157     case 33:
158         /* FPCR */
159         vfp_set_fpcr(env, ldl_p(buf));
160         return 4;
161     default:
162         return 0;
163     }
164 }
165
166 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
167 {
168     assert(ri->fieldoffset);
169     if (cpreg_field_is_64bit(ri)) {
170         return CPREG_FIELD64(env, ri);
171     } else {
172         return CPREG_FIELD32(env, ri);
173     }
174 }
175
176 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
177                       uint64_t value)
178 {
179     assert(ri->fieldoffset);
180     if (cpreg_field_is_64bit(ri)) {
181         CPREG_FIELD64(env, ri) = value;
182     } else {
183         CPREG_FIELD32(env, ri) = value;
184     }
185 }
186
187 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
188 {
189     return (char *)env + ri->fieldoffset;
190 }
191
192 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
193 {
194     /* Raw read of a coprocessor register (as needed for migration, etc). */
195     if (ri->type & ARM_CP_CONST) {
196         return ri->resetvalue;
197     } else if (ri->raw_readfn) {
198         return ri->raw_readfn(env, ri);
199     } else if (ri->readfn) {
200         return ri->readfn(env, ri);
201     } else {
202         return raw_read(env, ri);
203     }
204 }
205
206 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
207                              uint64_t v)
208 {
209     /* Raw write of a coprocessor register (as needed for migration, etc).
210      * Note that constant registers are treated as write-ignored; the
211      * caller should check for success by whether a readback gives the
212      * value written.
213      */
214     if (ri->type & ARM_CP_CONST) {
215         return;
216     } else if (ri->raw_writefn) {
217         ri->raw_writefn(env, ri, v);
218     } else if (ri->writefn) {
219         ri->writefn(env, ri, v);
220     } else {
221         raw_write(env, ri, v);
222     }
223 }
224
225 static int arm_gdb_get_sysreg(CPUARMState *env, uint8_t *buf, int reg)
226 {
227     ARMCPU *cpu = arm_env_get_cpu(env);
228     const ARMCPRegInfo *ri;
229     uint32_t key;
230
231     key = cpu->dyn_xml.cpregs_keys[reg];
232     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
233     if (ri) {
234         if (cpreg_field_is_64bit(ri)) {
235             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
236         } else {
237             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
238         }
239     }
240     return 0;
241 }
242
243 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
244 {
245     return 0;
246 }
247
248 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
249 {
250    /* Return true if the regdef would cause an assertion if you called
251     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
252     * program bug for it not to have the NO_RAW flag).
253     * NB that returning false here doesn't necessarily mean that calling
254     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
255     * read/write access functions which are safe for raw use" from "has
256     * read/write access functions which have side effects but has forgotten
257     * to provide raw access functions".
258     * The tests here line up with the conditions in read/write_raw_cp_reg()
259     * and assertions in raw_read()/raw_write().
260     */
261     if ((ri->type & ARM_CP_CONST) ||
262         ri->fieldoffset ||
263         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
264         return false;
265     }
266     return true;
267 }
268
269 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
270 {
271     /* Write the coprocessor state from cpu->env to the (index,value) list. */
272     int i;
273     bool ok = true;
274
275     for (i = 0; i < cpu->cpreg_array_len; i++) {
276         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
277         const ARMCPRegInfo *ri;
278         uint64_t newval;
279
280         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
281         if (!ri) {
282             ok = false;
283             continue;
284         }
285         if (ri->type & ARM_CP_NO_RAW) {
286             continue;
287         }
288
289         newval = read_raw_cp_reg(&cpu->env, ri);
290         if (kvm_sync) {
291             /*
292              * Only sync if the previous list->cpustate sync succeeded.
293              * Rather than tracking the success/failure state for every
294              * item in the list, we just recheck "does the raw write we must
295              * have made in write_list_to_cpustate() read back OK" here.
296              */
297             uint64_t oldval = cpu->cpreg_values[i];
298
299             if (oldval == newval) {
300                 continue;
301             }
302
303             write_raw_cp_reg(&cpu->env, ri, oldval);
304             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
305                 continue;
306             }
307
308             write_raw_cp_reg(&cpu->env, ri, newval);
309         }
310         cpu->cpreg_values[i] = newval;
311     }
312     return ok;
313 }
314
315 bool write_list_to_cpustate(ARMCPU *cpu)
316 {
317     int i;
318     bool ok = true;
319
320     for (i = 0; i < cpu->cpreg_array_len; i++) {
321         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
322         uint64_t v = cpu->cpreg_values[i];
323         const ARMCPRegInfo *ri;
324
325         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
326         if (!ri) {
327             ok = false;
328             continue;
329         }
330         if (ri->type & ARM_CP_NO_RAW) {
331             continue;
332         }
333         /* Write value and confirm it reads back as written
334          * (to catch read-only registers and partially read-only
335          * registers where the incoming migration value doesn't match)
336          */
337         write_raw_cp_reg(&cpu->env, ri, v);
338         if (read_raw_cp_reg(&cpu->env, ri) != v) {
339             ok = false;
340         }
341     }
342     return ok;
343 }
344
345 static void add_cpreg_to_list(gpointer key, gpointer opaque)
346 {
347     ARMCPU *cpu = opaque;
348     uint64_t regidx;
349     const ARMCPRegInfo *ri;
350
351     regidx = *(uint32_t *)key;
352     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
353
354     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
355         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
356         /* The value array need not be initialized at this point */
357         cpu->cpreg_array_len++;
358     }
359 }
360
361 static void count_cpreg(gpointer key, gpointer opaque)
362 {
363     ARMCPU *cpu = opaque;
364     uint64_t regidx;
365     const ARMCPRegInfo *ri;
366
367     regidx = *(uint32_t *)key;
368     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
369
370     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
371         cpu->cpreg_array_len++;
372     }
373 }
374
375 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
376 {
377     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
378     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
379
380     if (aidx > bidx) {
381         return 1;
382     }
383     if (aidx < bidx) {
384         return -1;
385     }
386     return 0;
387 }
388
389 void init_cpreg_list(ARMCPU *cpu)
390 {
391     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
392      * Note that we require cpreg_tuples[] to be sorted by key ID.
393      */
394     GList *keys;
395     int arraylen;
396
397     keys = g_hash_table_get_keys(cpu->cp_regs);
398     keys = g_list_sort(keys, cpreg_key_compare);
399
400     cpu->cpreg_array_len = 0;
401
402     g_list_foreach(keys, count_cpreg, cpu);
403
404     arraylen = cpu->cpreg_array_len;
405     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
406     cpu->cpreg_values = g_new(uint64_t, arraylen);
407     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
408     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
409     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
410     cpu->cpreg_array_len = 0;
411
412     g_list_foreach(keys, add_cpreg_to_list, cpu);
413
414     assert(cpu->cpreg_array_len == arraylen);
415
416     g_list_free(keys);
417 }
418
419 /*
420  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
421  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
422  *
423  * access_el3_aa32ns: Used to check AArch32 register views.
424  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
425  */
426 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
427                                         const ARMCPRegInfo *ri,
428                                         bool isread)
429 {
430     bool secure = arm_is_secure_below_el3(env);
431
432     assert(!arm_el_is_aa64(env, 3));
433     if (secure) {
434         return CP_ACCESS_TRAP_UNCATEGORIZED;
435     }
436     return CP_ACCESS_OK;
437 }
438
439 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
440                                                 const ARMCPRegInfo *ri,
441                                                 bool isread)
442 {
443     if (!arm_el_is_aa64(env, 3)) {
444         return access_el3_aa32ns(env, ri, isread);
445     }
446     return CP_ACCESS_OK;
447 }
448
449 /* Some secure-only AArch32 registers trap to EL3 if used from
450  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
451  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
452  * We assume that the .access field is set to PL1_RW.
453  */
454 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
455                                             const ARMCPRegInfo *ri,
456                                             bool isread)
457 {
458     if (arm_current_el(env) == 3) {
459         return CP_ACCESS_OK;
460     }
461     if (arm_is_secure_below_el3(env)) {
462         return CP_ACCESS_TRAP_EL3;
463     }
464     /* This will be EL1 NS and EL2 NS, which just UNDEF */
465     return CP_ACCESS_TRAP_UNCATEGORIZED;
466 }
467
468 /* Check for traps to "powerdown debug" registers, which are controlled
469  * by MDCR.TDOSA
470  */
471 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
472                                    bool isread)
473 {
474     int el = arm_current_el(env);
475     bool mdcr_el2_tdosa = (env->cp15.mdcr_el2 & MDCR_TDOSA) ||
476         (env->cp15.mdcr_el2 & MDCR_TDE) ||
477         (arm_hcr_el2_eff(env) & HCR_TGE);
478
479     if (el < 2 && mdcr_el2_tdosa && !arm_is_secure_below_el3(env)) {
480         return CP_ACCESS_TRAP_EL2;
481     }
482     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
483         return CP_ACCESS_TRAP_EL3;
484     }
485     return CP_ACCESS_OK;
486 }
487
488 /* Check for traps to "debug ROM" registers, which are controlled
489  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
490  */
491 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
492                                   bool isread)
493 {
494     int el = arm_current_el(env);
495     bool mdcr_el2_tdra = (env->cp15.mdcr_el2 & MDCR_TDRA) ||
496         (env->cp15.mdcr_el2 & MDCR_TDE) ||
497         (arm_hcr_el2_eff(env) & HCR_TGE);
498
499     if (el < 2 && mdcr_el2_tdra && !arm_is_secure_below_el3(env)) {
500         return CP_ACCESS_TRAP_EL2;
501     }
502     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
503         return CP_ACCESS_TRAP_EL3;
504     }
505     return CP_ACCESS_OK;
506 }
507
508 /* Check for traps to general debug registers, which are controlled
509  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
510  */
511 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
512                                   bool isread)
513 {
514     int el = arm_current_el(env);
515     bool mdcr_el2_tda = (env->cp15.mdcr_el2 & MDCR_TDA) ||
516         (env->cp15.mdcr_el2 & MDCR_TDE) ||
517         (arm_hcr_el2_eff(env) & HCR_TGE);
518
519     if (el < 2 && mdcr_el2_tda && !arm_is_secure_below_el3(env)) {
520         return CP_ACCESS_TRAP_EL2;
521     }
522     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
523         return CP_ACCESS_TRAP_EL3;
524     }
525     return CP_ACCESS_OK;
526 }
527
528 /* Check for traps to performance monitor registers, which are controlled
529  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
530  */
531 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
532                                  bool isread)
533 {
534     int el = arm_current_el(env);
535
536     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
537         && !arm_is_secure_below_el3(env)) {
538         return CP_ACCESS_TRAP_EL2;
539     }
540     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
541         return CP_ACCESS_TRAP_EL3;
542     }
543     return CP_ACCESS_OK;
544 }
545
546 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
547 {
548     ARMCPU *cpu = arm_env_get_cpu(env);
549
550     raw_write(env, ri, value);
551     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
552 }
553
554 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
555 {
556     ARMCPU *cpu = arm_env_get_cpu(env);
557
558     if (raw_read(env, ri) != value) {
559         /* Unlike real hardware the qemu TLB uses virtual addresses,
560          * not modified virtual addresses, so this causes a TLB flush.
561          */
562         tlb_flush(CPU(cpu));
563         raw_write(env, ri, value);
564     }
565 }
566
567 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
568                              uint64_t value)
569 {
570     ARMCPU *cpu = arm_env_get_cpu(env);
571
572     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
573         && !extended_addresses_enabled(env)) {
574         /* For VMSA (when not using the LPAE long descriptor page table
575          * format) this register includes the ASID, so do a TLB flush.
576          * For PMSA it is purely a process ID and no action is needed.
577          */
578         tlb_flush(CPU(cpu));
579     }
580     raw_write(env, ri, value);
581 }
582
583 /* IS variants of TLB operations must affect all cores */
584 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
585                              uint64_t value)
586 {
587     CPUState *cs = ENV_GET_CPU(env);
588
589     tlb_flush_all_cpus_synced(cs);
590 }
591
592 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
593                              uint64_t value)
594 {
595     CPUState *cs = ENV_GET_CPU(env);
596
597     tlb_flush_all_cpus_synced(cs);
598 }
599
600 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
601                              uint64_t value)
602 {
603     CPUState *cs = ENV_GET_CPU(env);
604
605     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
606 }
607
608 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
609                              uint64_t value)
610 {
611     CPUState *cs = ENV_GET_CPU(env);
612
613     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
614 }
615
616 /*
617  * Non-IS variants of TLB operations are upgraded to
618  * IS versions if we are at NS EL1 and HCR_EL2.FB is set to
619  * force broadcast of these operations.
620  */
621 static bool tlb_force_broadcast(CPUARMState *env)
622 {
623     return (env->cp15.hcr_el2 & HCR_FB) &&
624         arm_current_el(env) == 1 && arm_is_secure_below_el3(env);
625 }
626
627 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
628                           uint64_t value)
629 {
630     /* Invalidate all (TLBIALL) */
631     ARMCPU *cpu = arm_env_get_cpu(env);
632
633     if (tlb_force_broadcast(env)) {
634         tlbiall_is_write(env, NULL, value);
635         return;
636     }
637
638     tlb_flush(CPU(cpu));
639 }
640
641 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
642                           uint64_t value)
643 {
644     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
645     ARMCPU *cpu = arm_env_get_cpu(env);
646
647     if (tlb_force_broadcast(env)) {
648         tlbimva_is_write(env, NULL, value);
649         return;
650     }
651
652     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
653 }
654
655 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
656                            uint64_t value)
657 {
658     /* Invalidate by ASID (TLBIASID) */
659     ARMCPU *cpu = arm_env_get_cpu(env);
660
661     if (tlb_force_broadcast(env)) {
662         tlbiasid_is_write(env, NULL, value);
663         return;
664     }
665
666     tlb_flush(CPU(cpu));
667 }
668
669 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
670                            uint64_t value)
671 {
672     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
673     ARMCPU *cpu = arm_env_get_cpu(env);
674
675     if (tlb_force_broadcast(env)) {
676         tlbimvaa_is_write(env, NULL, value);
677         return;
678     }
679
680     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
681 }
682
683 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
684                                uint64_t value)
685 {
686     CPUState *cs = ENV_GET_CPU(env);
687
688     tlb_flush_by_mmuidx(cs,
689                         ARMMMUIdxBit_S12NSE1 |
690                         ARMMMUIdxBit_S12NSE0 |
691                         ARMMMUIdxBit_S2NS);
692 }
693
694 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
695                                   uint64_t value)
696 {
697     CPUState *cs = ENV_GET_CPU(env);
698
699     tlb_flush_by_mmuidx_all_cpus_synced(cs,
700                                         ARMMMUIdxBit_S12NSE1 |
701                                         ARMMMUIdxBit_S12NSE0 |
702                                         ARMMMUIdxBit_S2NS);
703 }
704
705 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
706                             uint64_t value)
707 {
708     /* Invalidate by IPA. This has to invalidate any structures that
709      * contain only stage 2 translation information, but does not need
710      * to apply to structures that contain combined stage 1 and stage 2
711      * translation information.
712      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
713      */
714     CPUState *cs = ENV_GET_CPU(env);
715     uint64_t pageaddr;
716
717     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
718         return;
719     }
720
721     pageaddr = sextract64(value << 12, 0, 40);
722
723     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
724 }
725
726 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
727                                uint64_t value)
728 {
729     CPUState *cs = ENV_GET_CPU(env);
730     uint64_t pageaddr;
731
732     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
733         return;
734     }
735
736     pageaddr = sextract64(value << 12, 0, 40);
737
738     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
739                                              ARMMMUIdxBit_S2NS);
740 }
741
742 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
743                               uint64_t value)
744 {
745     CPUState *cs = ENV_GET_CPU(env);
746
747     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
748 }
749
750 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
751                                  uint64_t value)
752 {
753     CPUState *cs = ENV_GET_CPU(env);
754
755     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
756 }
757
758 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
759                               uint64_t value)
760 {
761     CPUState *cs = ENV_GET_CPU(env);
762     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
763
764     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
765 }
766
767 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
768                                  uint64_t value)
769 {
770     CPUState *cs = ENV_GET_CPU(env);
771     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
772
773     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
774                                              ARMMMUIdxBit_S1E2);
775 }
776
777 static const ARMCPRegInfo cp_reginfo[] = {
778     /* Define the secure and non-secure FCSE identifier CP registers
779      * separately because there is no secure bank in V8 (no _EL3).  This allows
780      * the secure register to be properly reset and migrated. There is also no
781      * v8 EL1 version of the register so the non-secure instance stands alone.
782      */
783     { .name = "FCSEIDR",
784       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
785       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
786       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
787       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
788     { .name = "FCSEIDR_S",
789       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
790       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
791       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
792       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
793     /* Define the secure and non-secure context identifier CP registers
794      * separately because there is no secure bank in V8 (no _EL3).  This allows
795      * the secure register to be properly reset and migrated.  In the
796      * non-secure case, the 32-bit register will have reset and migration
797      * disabled during registration as it is handled by the 64-bit instance.
798      */
799     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
800       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
801       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
802       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
803       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
804     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
805       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
806       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
807       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
808       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
809     REGINFO_SENTINEL
810 };
811
812 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
813     /* NB: Some of these registers exist in v8 but with more precise
814      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
815      */
816     /* MMU Domain access control / MPU write buffer control */
817     { .name = "DACR",
818       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
819       .access = PL1_RW, .resetvalue = 0,
820       .writefn = dacr_write, .raw_writefn = raw_write,
821       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
822                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
823     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
824      * For v6 and v5, these mappings are overly broad.
825      */
826     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
827       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
828     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
829       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
830     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
831       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
832     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
833       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
834     /* Cache maintenance ops; some of this space may be overridden later. */
835     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
836       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
837       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
838     REGINFO_SENTINEL
839 };
840
841 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
842     /* Not all pre-v6 cores implemented this WFI, so this is slightly
843      * over-broad.
844      */
845     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
846       .access = PL1_W, .type = ARM_CP_WFI },
847     REGINFO_SENTINEL
848 };
849
850 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
851     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
852      * is UNPREDICTABLE; we choose to NOP as most implementations do).
853      */
854     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
855       .access = PL1_W, .type = ARM_CP_WFI },
856     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
857      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
858      * OMAPCP will override this space.
859      */
860     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
861       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
862       .resetvalue = 0 },
863     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
864       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
865       .resetvalue = 0 },
866     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
867     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
868       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
869       .resetvalue = 0 },
870     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
871      * implementing it as RAZ means the "debug architecture version" bits
872      * will read as a reserved value, which should cause Linux to not try
873      * to use the debug hardware.
874      */
875     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
876       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
877     /* MMU TLB control. Note that the wildcarding means we cover not just
878      * the unified TLB ops but also the dside/iside/inner-shareable variants.
879      */
880     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
881       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
882       .type = ARM_CP_NO_RAW },
883     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
884       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
885       .type = ARM_CP_NO_RAW },
886     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
887       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
888       .type = ARM_CP_NO_RAW },
889     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
890       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
891       .type = ARM_CP_NO_RAW },
892     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
893       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
894     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
895       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
896     REGINFO_SENTINEL
897 };
898
899 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
900                         uint64_t value)
901 {
902     uint32_t mask = 0;
903
904     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
905     if (!arm_feature(env, ARM_FEATURE_V8)) {
906         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
907          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
908          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
909          */
910         if (arm_feature(env, ARM_FEATURE_VFP)) {
911             /* VFP coprocessor: cp10 & cp11 [23:20] */
912             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
913
914             if (!arm_feature(env, ARM_FEATURE_NEON)) {
915                 /* ASEDIS [31] bit is RAO/WI */
916                 value |= (1 << 31);
917             }
918
919             /* VFPv3 and upwards with NEON implement 32 double precision
920              * registers (D0-D31).
921              */
922             if (!arm_feature(env, ARM_FEATURE_NEON) ||
923                     !arm_feature(env, ARM_FEATURE_VFP3)) {
924                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
925                 value |= (1 << 30);
926             }
927         }
928         value &= mask;
929     }
930     env->cp15.cpacr_el1 = value;
931 }
932
933 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
934 {
935     /* Call cpacr_write() so that we reset with the correct RAO bits set
936      * for our CPU features.
937      */
938     cpacr_write(env, ri, 0);
939 }
940
941 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
942                                    bool isread)
943 {
944     if (arm_feature(env, ARM_FEATURE_V8)) {
945         /* Check if CPACR accesses are to be trapped to EL2 */
946         if (arm_current_el(env) == 1 &&
947             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
948             return CP_ACCESS_TRAP_EL2;
949         /* Check if CPACR accesses are to be trapped to EL3 */
950         } else if (arm_current_el(env) < 3 &&
951                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
952             return CP_ACCESS_TRAP_EL3;
953         }
954     }
955
956     return CP_ACCESS_OK;
957 }
958
959 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
960                                   bool isread)
961 {
962     /* Check if CPTR accesses are set to trap to EL3 */
963     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
964         return CP_ACCESS_TRAP_EL3;
965     }
966
967     return CP_ACCESS_OK;
968 }
969
970 static const ARMCPRegInfo v6_cp_reginfo[] = {
971     /* prefetch by MVA in v6, NOP in v7 */
972     { .name = "MVA_prefetch",
973       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
974       .access = PL1_W, .type = ARM_CP_NOP },
975     /* We need to break the TB after ISB to execute self-modifying code
976      * correctly and also to take any pending interrupts immediately.
977      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
978      */
979     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
980       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
981     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
982       .access = PL0_W, .type = ARM_CP_NOP },
983     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
984       .access = PL0_W, .type = ARM_CP_NOP },
985     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
986       .access = PL1_RW,
987       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
988                              offsetof(CPUARMState, cp15.ifar_ns) },
989       .resetvalue = 0, },
990     /* Watchpoint Fault Address Register : should actually only be present
991      * for 1136, 1176, 11MPCore.
992      */
993     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
994       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
995     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
996       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
997       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
998       .resetfn = cpacr_reset, .writefn = cpacr_write },
999     REGINFO_SENTINEL
1000 };
1001
1002 /* Definitions for the PMU registers */
1003 #define PMCRN_MASK  0xf800
1004 #define PMCRN_SHIFT 11
1005 #define PMCRLC  0x40
1006 #define PMCRDP  0x10
1007 #define PMCRD   0x8
1008 #define PMCRC   0x4
1009 #define PMCRP   0x2
1010 #define PMCRE   0x1
1011
1012 #define PMXEVTYPER_P          0x80000000
1013 #define PMXEVTYPER_U          0x40000000
1014 #define PMXEVTYPER_NSK        0x20000000
1015 #define PMXEVTYPER_NSU        0x10000000
1016 #define PMXEVTYPER_NSH        0x08000000
1017 #define PMXEVTYPER_M          0x04000000
1018 #define PMXEVTYPER_MT         0x02000000
1019 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1020 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1021                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1022                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1023                                PMXEVTYPER_EVTCOUNT)
1024
1025 #define PMCCFILTR             0xf8000000
1026 #define PMCCFILTR_M           PMXEVTYPER_M
1027 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1028
1029 static inline uint32_t pmu_num_counters(CPUARMState *env)
1030 {
1031   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1032 }
1033
1034 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1035 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1036 {
1037   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1038 }
1039
1040 typedef struct pm_event {
1041     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1042     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1043     bool (*supported)(CPUARMState *);
1044     /*
1045      * Retrieve the current count of the underlying event. The programmed
1046      * counters hold a difference from the return value from this function
1047      */
1048     uint64_t (*get_count)(CPUARMState *);
1049     /*
1050      * Return how many nanoseconds it will take (at a minimum) for count events
1051      * to occur. A negative value indicates the counter will never overflow, or
1052      * that the counter has otherwise arranged for the overflow bit to be set
1053      * and the PMU interrupt to be raised on overflow.
1054      */
1055     int64_t (*ns_per_count)(uint64_t);
1056 } pm_event;
1057
1058 static bool event_always_supported(CPUARMState *env)
1059 {
1060     return true;
1061 }
1062
1063 static uint64_t swinc_get_count(CPUARMState *env)
1064 {
1065     /*
1066      * SW_INCR events are written directly to the pmevcntr's by writes to
1067      * PMSWINC, so there is no underlying count maintained by the PMU itself
1068      */
1069     return 0;
1070 }
1071
1072 static int64_t swinc_ns_per(uint64_t ignored)
1073 {
1074     return -1;
1075 }
1076
1077 /*
1078  * Return the underlying cycle count for the PMU cycle counters. If we're in
1079  * usermode, simply return 0.
1080  */
1081 static uint64_t cycles_get_count(CPUARMState *env)
1082 {
1083 #ifndef CONFIG_USER_ONLY
1084     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1085                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1086 #else
1087     return cpu_get_host_ticks();
1088 #endif
1089 }
1090
1091 #ifndef CONFIG_USER_ONLY
1092 static int64_t cycles_ns_per(uint64_t cycles)
1093 {
1094     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1095 }
1096
1097 static bool instructions_supported(CPUARMState *env)
1098 {
1099     return use_icount == 1 /* Precise instruction counting */;
1100 }
1101
1102 static uint64_t instructions_get_count(CPUARMState *env)
1103 {
1104     return (uint64_t)cpu_get_icount_raw();
1105 }
1106
1107 static int64_t instructions_ns_per(uint64_t icount)
1108 {
1109     return cpu_icount_to_ns((int64_t)icount);
1110 }
1111 #endif
1112
1113 static const pm_event pm_events[] = {
1114     { .number = 0x000, /* SW_INCR */
1115       .supported = event_always_supported,
1116       .get_count = swinc_get_count,
1117       .ns_per_count = swinc_ns_per,
1118     },
1119 #ifndef CONFIG_USER_ONLY
1120     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1121       .supported = instructions_supported,
1122       .get_count = instructions_get_count,
1123       .ns_per_count = instructions_ns_per,
1124     },
1125     { .number = 0x011, /* CPU_CYCLES, Cycle */
1126       .supported = event_always_supported,
1127       .get_count = cycles_get_count,
1128       .ns_per_count = cycles_ns_per,
1129     }
1130 #endif
1131 };
1132
1133 /*
1134  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1135  * events (i.e. the statistical profiling extension), this implementation
1136  * should first be updated to something sparse instead of the current
1137  * supported_event_map[] array.
1138  */
1139 #define MAX_EVENT_ID 0x11
1140 #define UNSUPPORTED_EVENT UINT16_MAX
1141 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1142
1143 /*
1144  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1145  * of ARM event numbers to indices in our pm_events array.
1146  *
1147  * Note: Events in the 0x40XX range are not currently supported.
1148  */
1149 void pmu_init(ARMCPU *cpu)
1150 {
1151     unsigned int i;
1152
1153     /*
1154      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1155      * events to them
1156      */
1157     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1158         supported_event_map[i] = UNSUPPORTED_EVENT;
1159     }
1160     cpu->pmceid0 = 0;
1161     cpu->pmceid1 = 0;
1162
1163     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1164         const pm_event *cnt = &pm_events[i];
1165         assert(cnt->number <= MAX_EVENT_ID);
1166         /* We do not currently support events in the 0x40xx range */
1167         assert(cnt->number <= 0x3f);
1168
1169         if (cnt->supported(&cpu->env)) {
1170             supported_event_map[cnt->number] = i;
1171             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1172             if (cnt->number & 0x20) {
1173                 cpu->pmceid1 |= event_mask;
1174             } else {
1175                 cpu->pmceid0 |= event_mask;
1176             }
1177         }
1178     }
1179 }
1180
1181 /*
1182  * Check at runtime whether a PMU event is supported for the current machine
1183  */
1184 static bool event_supported(uint16_t number)
1185 {
1186     if (number > MAX_EVENT_ID) {
1187         return false;
1188     }
1189     return supported_event_map[number] != UNSUPPORTED_EVENT;
1190 }
1191
1192 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1193                                    bool isread)
1194 {
1195     /* Performance monitor registers user accessibility is controlled
1196      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1197      * trapping to EL2 or EL3 for other accesses.
1198      */
1199     int el = arm_current_el(env);
1200
1201     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1202         return CP_ACCESS_TRAP;
1203     }
1204     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
1205         && !arm_is_secure_below_el3(env)) {
1206         return CP_ACCESS_TRAP_EL2;
1207     }
1208     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1209         return CP_ACCESS_TRAP_EL3;
1210     }
1211
1212     return CP_ACCESS_OK;
1213 }
1214
1215 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1216                                            const ARMCPRegInfo *ri,
1217                                            bool isread)
1218 {
1219     /* ER: event counter read trap control */
1220     if (arm_feature(env, ARM_FEATURE_V8)
1221         && arm_current_el(env) == 0
1222         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1223         && isread) {
1224         return CP_ACCESS_OK;
1225     }
1226
1227     return pmreg_access(env, ri, isread);
1228 }
1229
1230 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1231                                          const ARMCPRegInfo *ri,
1232                                          bool isread)
1233 {
1234     /* SW: software increment write trap control */
1235     if (arm_feature(env, ARM_FEATURE_V8)
1236         && arm_current_el(env) == 0
1237         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1238         && !isread) {
1239         return CP_ACCESS_OK;
1240     }
1241
1242     return pmreg_access(env, ri, isread);
1243 }
1244
1245 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1246                                         const ARMCPRegInfo *ri,
1247                                         bool isread)
1248 {
1249     /* ER: event counter read trap control */
1250     if (arm_feature(env, ARM_FEATURE_V8)
1251         && arm_current_el(env) == 0
1252         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1253         return CP_ACCESS_OK;
1254     }
1255
1256     return pmreg_access(env, ri, isread);
1257 }
1258
1259 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1260                                          const ARMCPRegInfo *ri,
1261                                          bool isread)
1262 {
1263     /* CR: cycle counter read trap control */
1264     if (arm_feature(env, ARM_FEATURE_V8)
1265         && arm_current_el(env) == 0
1266         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1267         && isread) {
1268         return CP_ACCESS_OK;
1269     }
1270
1271     return pmreg_access(env, ri, isread);
1272 }
1273
1274 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1275  * the current EL, security state, and register configuration.
1276  */
1277 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1278 {
1279     uint64_t filter;
1280     bool e, p, u, nsk, nsu, nsh, m;
1281     bool enabled, prohibited, filtered;
1282     bool secure = arm_is_secure(env);
1283     int el = arm_current_el(env);
1284     uint8_t hpmn = env->cp15.mdcr_el2 & MDCR_HPMN;
1285
1286     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1287         return false;
1288     }
1289
1290     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1291             (counter < hpmn || counter == 31)) {
1292         e = env->cp15.c9_pmcr & PMCRE;
1293     } else {
1294         e = env->cp15.mdcr_el2 & MDCR_HPME;
1295     }
1296     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1297
1298     if (!secure) {
1299         if (el == 2 && (counter < hpmn || counter == 31)) {
1300             prohibited = env->cp15.mdcr_el2 & MDCR_HPMD;
1301         } else {
1302             prohibited = false;
1303         }
1304     } else {
1305         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1306            (env->cp15.mdcr_el3 & MDCR_SPME);
1307     }
1308
1309     if (prohibited && counter == 31) {
1310         prohibited = env->cp15.c9_pmcr & PMCRDP;
1311     }
1312
1313     if (counter == 31) {
1314         filter = env->cp15.pmccfiltr_el0;
1315     } else {
1316         filter = env->cp15.c14_pmevtyper[counter];
1317     }
1318
1319     p   = filter & PMXEVTYPER_P;
1320     u   = filter & PMXEVTYPER_U;
1321     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1322     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1323     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1324     m   = arm_el_is_aa64(env, 1) &&
1325               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1326
1327     if (el == 0) {
1328         filtered = secure ? u : u != nsu;
1329     } else if (el == 1) {
1330         filtered = secure ? p : p != nsk;
1331     } else if (el == 2) {
1332         filtered = !nsh;
1333     } else { /* EL3 */
1334         filtered = m != p;
1335     }
1336
1337     if (counter != 31) {
1338         /*
1339          * If not checking PMCCNTR, ensure the counter is setup to an event we
1340          * support
1341          */
1342         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1343         if (!event_supported(event)) {
1344             return false;
1345         }
1346     }
1347
1348     return enabled && !prohibited && !filtered;
1349 }
1350
1351 static void pmu_update_irq(CPUARMState *env)
1352 {
1353     ARMCPU *cpu = arm_env_get_cpu(env);
1354     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1355             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1356 }
1357
1358 /*
1359  * Ensure c15_ccnt is the guest-visible count so that operations such as
1360  * enabling/disabling the counter or filtering, modifying the count itself,
1361  * etc. can be done logically. This is essentially a no-op if the counter is
1362  * not enabled at the time of the call.
1363  */
1364 static void pmccntr_op_start(CPUARMState *env)
1365 {
1366     uint64_t cycles = cycles_get_count(env);
1367
1368     if (pmu_counter_enabled(env, 31)) {
1369         uint64_t eff_cycles = cycles;
1370         if (env->cp15.c9_pmcr & PMCRD) {
1371             /* Increment once every 64 processor clock cycles */
1372             eff_cycles /= 64;
1373         }
1374
1375         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1376
1377         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1378                                  1ull << 63 : 1ull << 31;
1379         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1380             env->cp15.c9_pmovsr |= (1 << 31);
1381             pmu_update_irq(env);
1382         }
1383
1384         env->cp15.c15_ccnt = new_pmccntr;
1385     }
1386     env->cp15.c15_ccnt_delta = cycles;
1387 }
1388
1389 /*
1390  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1391  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1392  * pmccntr_op_start.
1393  */
1394 static void pmccntr_op_finish(CPUARMState *env)
1395 {
1396     if (pmu_counter_enabled(env, 31)) {
1397 #ifndef CONFIG_USER_ONLY
1398         /* Calculate when the counter will next overflow */
1399         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1400         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1401             remaining_cycles = (uint32_t)remaining_cycles;
1402         }
1403         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1404
1405         if (overflow_in > 0) {
1406             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1407                 overflow_in;
1408             ARMCPU *cpu = arm_env_get_cpu(env);
1409             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1410         }
1411 #endif
1412
1413         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1414         if (env->cp15.c9_pmcr & PMCRD) {
1415             /* Increment once every 64 processor clock cycles */
1416             prev_cycles /= 64;
1417         }
1418         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1419     }
1420 }
1421
1422 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1423 {
1424
1425     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1426     uint64_t count = 0;
1427     if (event_supported(event)) {
1428         uint16_t event_idx = supported_event_map[event];
1429         count = pm_events[event_idx].get_count(env);
1430     }
1431
1432     if (pmu_counter_enabled(env, counter)) {
1433         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1434
1435         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1436             env->cp15.c9_pmovsr |= (1 << counter);
1437             pmu_update_irq(env);
1438         }
1439         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1440     }
1441     env->cp15.c14_pmevcntr_delta[counter] = count;
1442 }
1443
1444 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1445 {
1446     if (pmu_counter_enabled(env, counter)) {
1447 #ifndef CONFIG_USER_ONLY
1448         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1449         uint16_t event_idx = supported_event_map[event];
1450         uint64_t delta = UINT32_MAX -
1451             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1452         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1453
1454         if (overflow_in > 0) {
1455             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1456                 overflow_in;
1457             ARMCPU *cpu = arm_env_get_cpu(env);
1458             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1459         }
1460 #endif
1461
1462         env->cp15.c14_pmevcntr_delta[counter] -=
1463             env->cp15.c14_pmevcntr[counter];
1464     }
1465 }
1466
1467 void pmu_op_start(CPUARMState *env)
1468 {
1469     unsigned int i;
1470     pmccntr_op_start(env);
1471     for (i = 0; i < pmu_num_counters(env); i++) {
1472         pmevcntr_op_start(env, i);
1473     }
1474 }
1475
1476 void pmu_op_finish(CPUARMState *env)
1477 {
1478     unsigned int i;
1479     pmccntr_op_finish(env);
1480     for (i = 0; i < pmu_num_counters(env); i++) {
1481         pmevcntr_op_finish(env, i);
1482     }
1483 }
1484
1485 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1486 {
1487     pmu_op_start(&cpu->env);
1488 }
1489
1490 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1491 {
1492     pmu_op_finish(&cpu->env);
1493 }
1494
1495 void arm_pmu_timer_cb(void *opaque)
1496 {
1497     ARMCPU *cpu = opaque;
1498
1499     /*
1500      * Update all the counter values based on the current underlying counts,
1501      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1502      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1503      * counter may expire.
1504      */
1505     pmu_op_start(&cpu->env);
1506     pmu_op_finish(&cpu->env);
1507 }
1508
1509 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1510                        uint64_t value)
1511 {
1512     pmu_op_start(env);
1513
1514     if (value & PMCRC) {
1515         /* The counter has been reset */
1516         env->cp15.c15_ccnt = 0;
1517     }
1518
1519     if (value & PMCRP) {
1520         unsigned int i;
1521         for (i = 0; i < pmu_num_counters(env); i++) {
1522             env->cp15.c14_pmevcntr[i] = 0;
1523         }
1524     }
1525
1526     /* only the DP, X, D and E bits are writable */
1527     env->cp15.c9_pmcr &= ~0x39;
1528     env->cp15.c9_pmcr |= (value & 0x39);
1529
1530     pmu_op_finish(env);
1531 }
1532
1533 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1534                           uint64_t value)
1535 {
1536     unsigned int i;
1537     for (i = 0; i < pmu_num_counters(env); i++) {
1538         /* Increment a counter's count iff: */
1539         if ((value & (1 << i)) && /* counter's bit is set */
1540                 /* counter is enabled and not filtered */
1541                 pmu_counter_enabled(env, i) &&
1542                 /* counter is SW_INCR */
1543                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1544             pmevcntr_op_start(env, i);
1545
1546             /*
1547              * Detect if this write causes an overflow since we can't predict
1548              * PMSWINC overflows like we can for other events
1549              */
1550             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1551
1552             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1553                 env->cp15.c9_pmovsr |= (1 << i);
1554                 pmu_update_irq(env);
1555             }
1556
1557             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1558
1559             pmevcntr_op_finish(env, i);
1560         }
1561     }
1562 }
1563
1564 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1565 {
1566     uint64_t ret;
1567     pmccntr_op_start(env);
1568     ret = env->cp15.c15_ccnt;
1569     pmccntr_op_finish(env);
1570     return ret;
1571 }
1572
1573 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1574                          uint64_t value)
1575 {
1576     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1577      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1578      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1579      * accessed.
1580      */
1581     env->cp15.c9_pmselr = value & 0x1f;
1582 }
1583
1584 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1585                         uint64_t value)
1586 {
1587     pmccntr_op_start(env);
1588     env->cp15.c15_ccnt = value;
1589     pmccntr_op_finish(env);
1590 }
1591
1592 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1593                             uint64_t value)
1594 {
1595     uint64_t cur_val = pmccntr_read(env, NULL);
1596
1597     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1598 }
1599
1600 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1601                             uint64_t value)
1602 {
1603     pmccntr_op_start(env);
1604     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1605     pmccntr_op_finish(env);
1606 }
1607
1608 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1609                             uint64_t value)
1610 {
1611     pmccntr_op_start(env);
1612     /* M is not accessible from AArch32 */
1613     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1614         (value & PMCCFILTR);
1615     pmccntr_op_finish(env);
1616 }
1617
1618 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1619 {
1620     /* M is not visible in AArch32 */
1621     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1622 }
1623
1624 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1625                             uint64_t value)
1626 {
1627     value &= pmu_counter_mask(env);
1628     env->cp15.c9_pmcnten |= value;
1629 }
1630
1631 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1632                              uint64_t value)
1633 {
1634     value &= pmu_counter_mask(env);
1635     env->cp15.c9_pmcnten &= ~value;
1636 }
1637
1638 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1639                          uint64_t value)
1640 {
1641     value &= pmu_counter_mask(env);
1642     env->cp15.c9_pmovsr &= ~value;
1643     pmu_update_irq(env);
1644 }
1645
1646 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1647                          uint64_t value)
1648 {
1649     value &= pmu_counter_mask(env);
1650     env->cp15.c9_pmovsr |= value;
1651     pmu_update_irq(env);
1652 }
1653
1654 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1655                              uint64_t value, const uint8_t counter)
1656 {
1657     if (counter == 31) {
1658         pmccfiltr_write(env, ri, value);
1659     } else if (counter < pmu_num_counters(env)) {
1660         pmevcntr_op_start(env, counter);
1661
1662         /*
1663          * If this counter's event type is changing, store the current
1664          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1665          * pmevcntr_op_finish has the correct baseline when it converts back to
1666          * a delta.
1667          */
1668         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1669             PMXEVTYPER_EVTCOUNT;
1670         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1671         if (old_event != new_event) {
1672             uint64_t count = 0;
1673             if (event_supported(new_event)) {
1674                 uint16_t event_idx = supported_event_map[new_event];
1675                 count = pm_events[event_idx].get_count(env);
1676             }
1677             env->cp15.c14_pmevcntr_delta[counter] = count;
1678         }
1679
1680         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1681         pmevcntr_op_finish(env, counter);
1682     }
1683     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1684      * PMSELR value is equal to or greater than the number of implemented
1685      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1686      */
1687 }
1688
1689 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1690                                const uint8_t counter)
1691 {
1692     if (counter == 31) {
1693         return env->cp15.pmccfiltr_el0;
1694     } else if (counter < pmu_num_counters(env)) {
1695         return env->cp15.c14_pmevtyper[counter];
1696     } else {
1697       /*
1698        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1699        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1700        */
1701         return 0;
1702     }
1703 }
1704
1705 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1706                               uint64_t value)
1707 {
1708     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1709     pmevtyper_write(env, ri, value, counter);
1710 }
1711
1712 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1713                                uint64_t value)
1714 {
1715     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1716     env->cp15.c14_pmevtyper[counter] = value;
1717
1718     /*
1719      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1720      * pmu_op_finish calls when loading saved state for a migration. Because
1721      * we're potentially updating the type of event here, the value written to
1722      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1723      * different counter type. Therefore, we need to set this value to the
1724      * current count for the counter type we're writing so that pmu_op_finish
1725      * has the correct count for its calculation.
1726      */
1727     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1728     if (event_supported(event)) {
1729         uint16_t event_idx = supported_event_map[event];
1730         env->cp15.c14_pmevcntr_delta[counter] =
1731             pm_events[event_idx].get_count(env);
1732     }
1733 }
1734
1735 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1736 {
1737     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1738     return pmevtyper_read(env, ri, counter);
1739 }
1740
1741 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1742                              uint64_t value)
1743 {
1744     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1745 }
1746
1747 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1748 {
1749     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1750 }
1751
1752 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1753                              uint64_t value, uint8_t counter)
1754 {
1755     if (counter < pmu_num_counters(env)) {
1756         pmevcntr_op_start(env, counter);
1757         env->cp15.c14_pmevcntr[counter] = value;
1758         pmevcntr_op_finish(env, counter);
1759     }
1760     /*
1761      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1762      * are CONSTRAINED UNPREDICTABLE.
1763      */
1764 }
1765
1766 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1767                               uint8_t counter)
1768 {
1769     if (counter < pmu_num_counters(env)) {
1770         uint64_t ret;
1771         pmevcntr_op_start(env, counter);
1772         ret = env->cp15.c14_pmevcntr[counter];
1773         pmevcntr_op_finish(env, counter);
1774         return ret;
1775     } else {
1776       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1777        * are CONSTRAINED UNPREDICTABLE. */
1778         return 0;
1779     }
1780 }
1781
1782 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1783                              uint64_t value)
1784 {
1785     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1786     pmevcntr_write(env, ri, value, counter);
1787 }
1788
1789 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1790 {
1791     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1792     return pmevcntr_read(env, ri, counter);
1793 }
1794
1795 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1796                              uint64_t value)
1797 {
1798     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1799     assert(counter < pmu_num_counters(env));
1800     env->cp15.c14_pmevcntr[counter] = value;
1801     pmevcntr_write(env, ri, value, counter);
1802 }
1803
1804 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1805 {
1806     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1807     assert(counter < pmu_num_counters(env));
1808     return env->cp15.c14_pmevcntr[counter];
1809 }
1810
1811 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1812                              uint64_t value)
1813 {
1814     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1815 }
1816
1817 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1818 {
1819     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1820 }
1821
1822 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1823                             uint64_t value)
1824 {
1825     if (arm_feature(env, ARM_FEATURE_V8)) {
1826         env->cp15.c9_pmuserenr = value & 0xf;
1827     } else {
1828         env->cp15.c9_pmuserenr = value & 1;
1829     }
1830 }
1831
1832 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1833                              uint64_t value)
1834 {
1835     /* We have no event counters so only the C bit can be changed */
1836     value &= pmu_counter_mask(env);
1837     env->cp15.c9_pminten |= value;
1838     pmu_update_irq(env);
1839 }
1840
1841 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1842                              uint64_t value)
1843 {
1844     value &= pmu_counter_mask(env);
1845     env->cp15.c9_pminten &= ~value;
1846     pmu_update_irq(env);
1847 }
1848
1849 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1850                        uint64_t value)
1851 {
1852     /* Note that even though the AArch64 view of this register has bits
1853      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1854      * architectural requirements for bits which are RES0 only in some
1855      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1856      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1857      */
1858     raw_write(env, ri, value & ~0x1FULL);
1859 }
1860
1861 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1862 {
1863     /* Begin with base v8.0 state.  */
1864     uint32_t valid_mask = 0x3fff;
1865     ARMCPU *cpu = arm_env_get_cpu(env);
1866
1867     if (arm_el_is_aa64(env, 3)) {
1868         value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1869         valid_mask &= ~SCR_NET;
1870     } else {
1871         valid_mask &= ~(SCR_RW | SCR_ST);
1872     }
1873
1874     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1875         valid_mask &= ~SCR_HCE;
1876
1877         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1878          * supported if EL2 exists. The bit is UNK/SBZP when
1879          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1880          * when EL2 is unavailable.
1881          * On ARMv8, this bit is always available.
1882          */
1883         if (arm_feature(env, ARM_FEATURE_V7) &&
1884             !arm_feature(env, ARM_FEATURE_V8)) {
1885             valid_mask &= ~SCR_SMD;
1886         }
1887     }
1888     if (cpu_isar_feature(aa64_lor, cpu)) {
1889         valid_mask |= SCR_TLOR;
1890     }
1891     if (cpu_isar_feature(aa64_pauth, cpu)) {
1892         valid_mask |= SCR_API | SCR_APK;
1893     }
1894
1895     /* Clear all-context RES0 bits.  */
1896     value &= valid_mask;
1897     raw_write(env, ri, value);
1898 }
1899
1900 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1901 {
1902     ARMCPU *cpu = arm_env_get_cpu(env);
1903
1904     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1905      * bank
1906      */
1907     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1908                                         ri->secure & ARM_CP_SECSTATE_S);
1909
1910     return cpu->ccsidr[index];
1911 }
1912
1913 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1914                          uint64_t value)
1915 {
1916     raw_write(env, ri, value & 0xf);
1917 }
1918
1919 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1920 {
1921     CPUState *cs = ENV_GET_CPU(env);
1922     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
1923     uint64_t ret = 0;
1924
1925     if (hcr_el2 & HCR_IMO) {
1926         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1927             ret |= CPSR_I;
1928         }
1929     } else {
1930         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1931             ret |= CPSR_I;
1932         }
1933     }
1934
1935     if (hcr_el2 & HCR_FMO) {
1936         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1937             ret |= CPSR_F;
1938         }
1939     } else {
1940         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1941             ret |= CPSR_F;
1942         }
1943     }
1944
1945     /* External aborts are not possible in QEMU so A bit is always clear */
1946     return ret;
1947 }
1948
1949 static const ARMCPRegInfo v7_cp_reginfo[] = {
1950     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1951     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1952       .access = PL1_W, .type = ARM_CP_NOP },
1953     /* Performance monitors are implementation defined in v7,
1954      * but with an ARM recommended set of registers, which we
1955      * follow.
1956      *
1957      * Performance registers fall into three categories:
1958      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1959      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1960      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1961      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1962      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1963      */
1964     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1965       .access = PL0_RW, .type = ARM_CP_ALIAS,
1966       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1967       .writefn = pmcntenset_write,
1968       .accessfn = pmreg_access,
1969       .raw_writefn = raw_write },
1970     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1971       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1972       .access = PL0_RW, .accessfn = pmreg_access,
1973       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1974       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1975     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1976       .access = PL0_RW,
1977       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1978       .accessfn = pmreg_access,
1979       .writefn = pmcntenclr_write,
1980       .type = ARM_CP_ALIAS },
1981     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1982       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1983       .access = PL0_RW, .accessfn = pmreg_access,
1984       .type = ARM_CP_ALIAS,
1985       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1986       .writefn = pmcntenclr_write },
1987     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1988       .access = PL0_RW, .type = ARM_CP_IO,
1989       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1990       .accessfn = pmreg_access,
1991       .writefn = pmovsr_write,
1992       .raw_writefn = raw_write },
1993     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1994       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1995       .access = PL0_RW, .accessfn = pmreg_access,
1996       .type = ARM_CP_ALIAS | ARM_CP_IO,
1997       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1998       .writefn = pmovsr_write,
1999       .raw_writefn = raw_write },
2000     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2001       .access = PL0_W, .accessfn = pmreg_access_swinc,
2002       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2003       .writefn = pmswinc_write },
2004     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2005       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2006       .access = PL0_W, .accessfn = pmreg_access_swinc,
2007       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2008       .writefn = pmswinc_write },
2009     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2010       .access = PL0_RW, .type = ARM_CP_ALIAS,
2011       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2012       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2013       .raw_writefn = raw_write},
2014     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2015       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2016       .access = PL0_RW, .accessfn = pmreg_access_selr,
2017       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2018       .writefn = pmselr_write, .raw_writefn = raw_write, },
2019     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2020       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2021       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2022       .accessfn = pmreg_access_ccntr },
2023     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2024       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2025       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2026       .type = ARM_CP_IO,
2027       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2028       .readfn = pmccntr_read, .writefn = pmccntr_write,
2029       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2030     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2031       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2032       .access = PL0_RW, .accessfn = pmreg_access,
2033       .type = ARM_CP_ALIAS | ARM_CP_IO,
2034       .resetvalue = 0, },
2035     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2036       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2037       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2038       .access = PL0_RW, .accessfn = pmreg_access,
2039       .type = ARM_CP_IO,
2040       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2041       .resetvalue = 0, },
2042     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2043       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2044       .accessfn = pmreg_access,
2045       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2046     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2047       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2048       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2049       .accessfn = pmreg_access,
2050       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2051     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2052       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2053       .accessfn = pmreg_access_xevcntr,
2054       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2055     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2056       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2057       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2058       .accessfn = pmreg_access_xevcntr,
2059       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2060     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2061       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2062       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2063       .resetvalue = 0,
2064       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2065     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2066       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2067       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2068       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2069       .resetvalue = 0,
2070       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2071     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2072       .access = PL1_RW, .accessfn = access_tpm,
2073       .type = ARM_CP_ALIAS | ARM_CP_IO,
2074       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2075       .resetvalue = 0,
2076       .writefn = pmintenset_write, .raw_writefn = raw_write },
2077     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2078       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2079       .access = PL1_RW, .accessfn = access_tpm,
2080       .type = ARM_CP_IO,
2081       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2082       .writefn = pmintenset_write, .raw_writefn = raw_write,
2083       .resetvalue = 0x0 },
2084     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2085       .access = PL1_RW, .accessfn = access_tpm,
2086       .type = ARM_CP_ALIAS | ARM_CP_IO,
2087       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2088       .writefn = pmintenclr_write, },
2089     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2090       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2091       .access = PL1_RW, .accessfn = access_tpm,
2092       .type = ARM_CP_ALIAS | ARM_CP_IO,
2093       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2094       .writefn = pmintenclr_write },
2095     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2096       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2097       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2098     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2099       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2100       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
2101       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2102                              offsetof(CPUARMState, cp15.csselr_ns) } },
2103     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2104      * just RAZ for all cores:
2105      */
2106     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2107       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2108       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2109     /* Auxiliary fault status registers: these also are IMPDEF, and we
2110      * choose to RAZ/WI for all cores.
2111      */
2112     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2113       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2114       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2115     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2116       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2117       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2118     /* MAIR can just read-as-written because we don't implement caches
2119      * and so don't need to care about memory attributes.
2120      */
2121     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2122       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2123       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2124       .resetvalue = 0 },
2125     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2126       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2127       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2128       .resetvalue = 0 },
2129     /* For non-long-descriptor page tables these are PRRR and NMRR;
2130      * regardless they still act as reads-as-written for QEMU.
2131      */
2132      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2133       * allows them to assign the correct fieldoffset based on the endianness
2134       * handled in the field definitions.
2135       */
2136     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2137       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
2138       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2139                              offsetof(CPUARMState, cp15.mair0_ns) },
2140       .resetfn = arm_cp_reset_ignore },
2141     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2142       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
2143       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2144                              offsetof(CPUARMState, cp15.mair1_ns) },
2145       .resetfn = arm_cp_reset_ignore },
2146     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2147       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2148       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2149     /* 32 bit ITLB invalidates */
2150     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2151       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2152     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2153       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2154     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2155       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2156     /* 32 bit DTLB invalidates */
2157     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2158       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2159     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2160       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2161     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2162       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2163     /* 32 bit TLB invalidates */
2164     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2165       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2166     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2167       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2168     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2169       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2170     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2171       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
2172     REGINFO_SENTINEL
2173 };
2174
2175 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2176     /* 32 bit TLB invalidates, Inner Shareable */
2177     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2178       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
2179     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2180       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
2181     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2182       .type = ARM_CP_NO_RAW, .access = PL1_W,
2183       .writefn = tlbiasid_is_write },
2184     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2185       .type = ARM_CP_NO_RAW, .access = PL1_W,
2186       .writefn = tlbimvaa_is_write },
2187     REGINFO_SENTINEL
2188 };
2189
2190 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2191     /* PMOVSSET is not implemented in v7 before v7ve */
2192     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2193       .access = PL0_RW, .accessfn = pmreg_access,
2194       .type = ARM_CP_ALIAS | ARM_CP_IO,
2195       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2196       .writefn = pmovsset_write,
2197       .raw_writefn = raw_write },
2198     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2199       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2200       .access = PL0_RW, .accessfn = pmreg_access,
2201       .type = ARM_CP_ALIAS | ARM_CP_IO,
2202       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2203       .writefn = pmovsset_write,
2204       .raw_writefn = raw_write },
2205     REGINFO_SENTINEL
2206 };
2207
2208 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2209                         uint64_t value)
2210 {
2211     value &= 1;
2212     env->teecr = value;
2213 }
2214
2215 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2216                                     bool isread)
2217 {
2218     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2219         return CP_ACCESS_TRAP;
2220     }
2221     return CP_ACCESS_OK;
2222 }
2223
2224 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2225     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2226       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2227       .resetvalue = 0,
2228       .writefn = teecr_write },
2229     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2230       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2231       .accessfn = teehbr_access, .resetvalue = 0 },
2232     REGINFO_SENTINEL
2233 };
2234
2235 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2236     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2237       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2238       .access = PL0_RW,
2239       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2240     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2241       .access = PL0_RW,
2242       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2243                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2244       .resetfn = arm_cp_reset_ignore },
2245     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2246       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2247       .access = PL0_R|PL1_W,
2248       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2249       .resetvalue = 0},
2250     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2251       .access = PL0_R|PL1_W,
2252       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2253                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2254       .resetfn = arm_cp_reset_ignore },
2255     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2256       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2257       .access = PL1_RW,
2258       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2259     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2260       .access = PL1_RW,
2261       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2262                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2263       .resetvalue = 0 },
2264     REGINFO_SENTINEL
2265 };
2266
2267 #ifndef CONFIG_USER_ONLY
2268
2269 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2270                                        bool isread)
2271 {
2272     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2273      * Writable only at the highest implemented exception level.
2274      */
2275     int el = arm_current_el(env);
2276
2277     switch (el) {
2278     case 0:
2279         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
2280             return CP_ACCESS_TRAP;
2281         }
2282         break;
2283     case 1:
2284         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2285             arm_is_secure_below_el3(env)) {
2286             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2287             return CP_ACCESS_TRAP_UNCATEGORIZED;
2288         }
2289         break;
2290     case 2:
2291     case 3:
2292         break;
2293     }
2294
2295     if (!isread && el < arm_highest_el(env)) {
2296         return CP_ACCESS_TRAP_UNCATEGORIZED;
2297     }
2298
2299     return CP_ACCESS_OK;
2300 }
2301
2302 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2303                                         bool isread)
2304 {
2305     unsigned int cur_el = arm_current_el(env);
2306     bool secure = arm_is_secure(env);
2307
2308     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
2309     if (cur_el == 0 &&
2310         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2311         return CP_ACCESS_TRAP;
2312     }
2313
2314     if (arm_feature(env, ARM_FEATURE_EL2) &&
2315         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2316         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
2317         return CP_ACCESS_TRAP_EL2;
2318     }
2319     return CP_ACCESS_OK;
2320 }
2321
2322 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2323                                       bool isread)
2324 {
2325     unsigned int cur_el = arm_current_el(env);
2326     bool secure = arm_is_secure(env);
2327
2328     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
2329      * EL0[PV]TEN is zero.
2330      */
2331     if (cur_el == 0 &&
2332         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2333         return CP_ACCESS_TRAP;
2334     }
2335
2336     if (arm_feature(env, ARM_FEATURE_EL2) &&
2337         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2338         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2339         return CP_ACCESS_TRAP_EL2;
2340     }
2341     return CP_ACCESS_OK;
2342 }
2343
2344 static CPAccessResult gt_pct_access(CPUARMState *env,
2345                                     const ARMCPRegInfo *ri,
2346                                     bool isread)
2347 {
2348     return gt_counter_access(env, GTIMER_PHYS, isread);
2349 }
2350
2351 static CPAccessResult gt_vct_access(CPUARMState *env,
2352                                     const ARMCPRegInfo *ri,
2353                                     bool isread)
2354 {
2355     return gt_counter_access(env, GTIMER_VIRT, isread);
2356 }
2357
2358 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2359                                        bool isread)
2360 {
2361     return gt_timer_access(env, GTIMER_PHYS, isread);
2362 }
2363
2364 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2365                                        bool isread)
2366 {
2367     return gt_timer_access(env, GTIMER_VIRT, isread);
2368 }
2369
2370 static CPAccessResult gt_stimer_access(CPUARMState *env,
2371                                        const ARMCPRegInfo *ri,
2372                                        bool isread)
2373 {
2374     /* The AArch64 register view of the secure physical timer is
2375      * always accessible from EL3, and configurably accessible from
2376      * Secure EL1.
2377      */
2378     switch (arm_current_el(env)) {
2379     case 1:
2380         if (!arm_is_secure(env)) {
2381             return CP_ACCESS_TRAP;
2382         }
2383         if (!(env->cp15.scr_el3 & SCR_ST)) {
2384             return CP_ACCESS_TRAP_EL3;
2385         }
2386         return CP_ACCESS_OK;
2387     case 0:
2388     case 2:
2389         return CP_ACCESS_TRAP;
2390     case 3:
2391         return CP_ACCESS_OK;
2392     default:
2393         g_assert_not_reached();
2394     }
2395 }
2396
2397 static uint64_t gt_get_countervalue(CPUARMState *env)
2398 {
2399     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
2400 }
2401
2402 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2403 {
2404     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2405
2406     if (gt->ctl & 1) {
2407         /* Timer enabled: calculate and set current ISTATUS, irq, and
2408          * reset timer to when ISTATUS next has to change
2409          */
2410         uint64_t offset = timeridx == GTIMER_VIRT ?
2411                                       cpu->env.cp15.cntvoff_el2 : 0;
2412         uint64_t count = gt_get_countervalue(&cpu->env);
2413         /* Note that this must be unsigned 64 bit arithmetic: */
2414         int istatus = count - offset >= gt->cval;
2415         uint64_t nexttick;
2416         int irqstate;
2417
2418         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2419
2420         irqstate = (istatus && !(gt->ctl & 2));
2421         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2422
2423         if (istatus) {
2424             /* Next transition is when count rolls back over to zero */
2425             nexttick = UINT64_MAX;
2426         } else {
2427             /* Next transition is when we hit cval */
2428             nexttick = gt->cval + offset;
2429         }
2430         /* Note that the desired next expiry time might be beyond the
2431          * signed-64-bit range of a QEMUTimer -- in this case we just
2432          * set the timer for as far in the future as possible. When the
2433          * timer expires we will reset the timer for any remaining period.
2434          */
2435         if (nexttick > INT64_MAX / GTIMER_SCALE) {
2436             nexttick = INT64_MAX / GTIMER_SCALE;
2437         }
2438         timer_mod(cpu->gt_timer[timeridx], nexttick);
2439         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2440     } else {
2441         /* Timer disabled: ISTATUS and timer output always clear */
2442         gt->ctl &= ~4;
2443         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2444         timer_del(cpu->gt_timer[timeridx]);
2445         trace_arm_gt_recalc_disabled(timeridx);
2446     }
2447 }
2448
2449 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2450                            int timeridx)
2451 {
2452     ARMCPU *cpu = arm_env_get_cpu(env);
2453
2454     timer_del(cpu->gt_timer[timeridx]);
2455 }
2456
2457 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2458 {
2459     return gt_get_countervalue(env);
2460 }
2461
2462 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2463 {
2464     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
2465 }
2466
2467 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2468                           int timeridx,
2469                           uint64_t value)
2470 {
2471     trace_arm_gt_cval_write(timeridx, value);
2472     env->cp15.c14_timer[timeridx].cval = value;
2473     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
2474 }
2475
2476 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2477                              int timeridx)
2478 {
2479     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2480
2481     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2482                       (gt_get_countervalue(env) - offset));
2483 }
2484
2485 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2486                           int timeridx,
2487                           uint64_t value)
2488 {
2489     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2490
2491     trace_arm_gt_tval_write(timeridx, value);
2492     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2493                                          sextract64(value, 0, 32);
2494     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
2495 }
2496
2497 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2498                          int timeridx,
2499                          uint64_t value)
2500 {
2501     ARMCPU *cpu = arm_env_get_cpu(env);
2502     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2503
2504     trace_arm_gt_ctl_write(timeridx, value);
2505     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2506     if ((oldval ^ value) & 1) {
2507         /* Enable toggled */
2508         gt_recalc_timer(cpu, timeridx);
2509     } else if ((oldval ^ value) & 2) {
2510         /* IMASK toggled: don't need to recalculate,
2511          * just set the interrupt line based on ISTATUS
2512          */
2513         int irqstate = (oldval & 4) && !(value & 2);
2514
2515         trace_arm_gt_imask_toggle(timeridx, irqstate);
2516         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2517     }
2518 }
2519
2520 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2521 {
2522     gt_timer_reset(env, ri, GTIMER_PHYS);
2523 }
2524
2525 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2526                                uint64_t value)
2527 {
2528     gt_cval_write(env, ri, GTIMER_PHYS, value);
2529 }
2530
2531 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2532 {
2533     return gt_tval_read(env, ri, GTIMER_PHYS);
2534 }
2535
2536 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2537                                uint64_t value)
2538 {
2539     gt_tval_write(env, ri, GTIMER_PHYS, value);
2540 }
2541
2542 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2543                               uint64_t value)
2544 {
2545     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2546 }
2547
2548 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2549 {
2550     gt_timer_reset(env, ri, GTIMER_VIRT);
2551 }
2552
2553 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2554                                uint64_t value)
2555 {
2556     gt_cval_write(env, ri, GTIMER_VIRT, value);
2557 }
2558
2559 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2560 {
2561     return gt_tval_read(env, ri, GTIMER_VIRT);
2562 }
2563
2564 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2565                                uint64_t value)
2566 {
2567     gt_tval_write(env, ri, GTIMER_VIRT, value);
2568 }
2569
2570 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2571                               uint64_t value)
2572 {
2573     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2574 }
2575
2576 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2577                               uint64_t value)
2578 {
2579     ARMCPU *cpu = arm_env_get_cpu(env);
2580
2581     trace_arm_gt_cntvoff_write(value);
2582     raw_write(env, ri, value);
2583     gt_recalc_timer(cpu, GTIMER_VIRT);
2584 }
2585
2586 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2587 {
2588     gt_timer_reset(env, ri, GTIMER_HYP);
2589 }
2590
2591 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2592                               uint64_t value)
2593 {
2594     gt_cval_write(env, ri, GTIMER_HYP, value);
2595 }
2596
2597 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2598 {
2599     return gt_tval_read(env, ri, GTIMER_HYP);
2600 }
2601
2602 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2603                               uint64_t value)
2604 {
2605     gt_tval_write(env, ri, GTIMER_HYP, value);
2606 }
2607
2608 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2609                               uint64_t value)
2610 {
2611     gt_ctl_write(env, ri, GTIMER_HYP, value);
2612 }
2613
2614 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2615 {
2616     gt_timer_reset(env, ri, GTIMER_SEC);
2617 }
2618
2619 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2620                               uint64_t value)
2621 {
2622     gt_cval_write(env, ri, GTIMER_SEC, value);
2623 }
2624
2625 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2626 {
2627     return gt_tval_read(env, ri, GTIMER_SEC);
2628 }
2629
2630 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2631                               uint64_t value)
2632 {
2633     gt_tval_write(env, ri, GTIMER_SEC, value);
2634 }
2635
2636 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2637                               uint64_t value)
2638 {
2639     gt_ctl_write(env, ri, GTIMER_SEC, value);
2640 }
2641
2642 void arm_gt_ptimer_cb(void *opaque)
2643 {
2644     ARMCPU *cpu = opaque;
2645
2646     gt_recalc_timer(cpu, GTIMER_PHYS);
2647 }
2648
2649 void arm_gt_vtimer_cb(void *opaque)
2650 {
2651     ARMCPU *cpu = opaque;
2652
2653     gt_recalc_timer(cpu, GTIMER_VIRT);
2654 }
2655
2656 void arm_gt_htimer_cb(void *opaque)
2657 {
2658     ARMCPU *cpu = opaque;
2659
2660     gt_recalc_timer(cpu, GTIMER_HYP);
2661 }
2662
2663 void arm_gt_stimer_cb(void *opaque)
2664 {
2665     ARMCPU *cpu = opaque;
2666
2667     gt_recalc_timer(cpu, GTIMER_SEC);
2668 }
2669
2670 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2671     /* Note that CNTFRQ is purely reads-as-written for the benefit
2672      * of software; writing it doesn't actually change the timer frequency.
2673      * Our reset value matches the fixed frequency we implement the timer at.
2674      */
2675     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2676       .type = ARM_CP_ALIAS,
2677       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2678       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2679     },
2680     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2681       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2682       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2683       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2684       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
2685     },
2686     /* overall control: mostly access permissions */
2687     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2688       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2689       .access = PL1_RW,
2690       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2691       .resetvalue = 0,
2692     },
2693     /* per-timer control */
2694     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2695       .secure = ARM_CP_SECSTATE_NS,
2696       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2697       .accessfn = gt_ptimer_access,
2698       .fieldoffset = offsetoflow32(CPUARMState,
2699                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2700       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2701     },
2702     { .name = "CNTP_CTL_S",
2703       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2704       .secure = ARM_CP_SECSTATE_S,
2705       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2706       .accessfn = gt_ptimer_access,
2707       .fieldoffset = offsetoflow32(CPUARMState,
2708                                    cp15.c14_timer[GTIMER_SEC].ctl),
2709       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2710     },
2711     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2712       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2713       .type = ARM_CP_IO, .access = PL0_RW,
2714       .accessfn = gt_ptimer_access,
2715       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2716       .resetvalue = 0,
2717       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2718     },
2719     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2720       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2721       .accessfn = gt_vtimer_access,
2722       .fieldoffset = offsetoflow32(CPUARMState,
2723                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2724       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2725     },
2726     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2727       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2728       .type = ARM_CP_IO, .access = PL0_RW,
2729       .accessfn = gt_vtimer_access,
2730       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2731       .resetvalue = 0,
2732       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2733     },
2734     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2735     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2736       .secure = ARM_CP_SECSTATE_NS,
2737       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2738       .accessfn = gt_ptimer_access,
2739       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2740     },
2741     { .name = "CNTP_TVAL_S",
2742       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2743       .secure = ARM_CP_SECSTATE_S,
2744       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2745       .accessfn = gt_ptimer_access,
2746       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2747     },
2748     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2749       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2750       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2751       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2752       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2753     },
2754     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2755       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2756       .accessfn = gt_vtimer_access,
2757       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2758     },
2759     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2760       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2761       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2762       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2763       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2764     },
2765     /* The counter itself */
2766     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2767       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2768       .accessfn = gt_pct_access,
2769       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2770     },
2771     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2772       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2773       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2774       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2775     },
2776     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2777       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2778       .accessfn = gt_vct_access,
2779       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2780     },
2781     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2782       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2783       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2784       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2785     },
2786     /* Comparison value, indicating when the timer goes off */
2787     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2788       .secure = ARM_CP_SECSTATE_NS,
2789       .access = PL0_RW,
2790       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2791       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2792       .accessfn = gt_ptimer_access,
2793       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2794     },
2795     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
2796       .secure = ARM_CP_SECSTATE_S,
2797       .access = PL0_RW,
2798       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2799       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2800       .accessfn = gt_ptimer_access,
2801       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2802     },
2803     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2804       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2805       .access = PL0_RW,
2806       .type = ARM_CP_IO,
2807       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2808       .resetvalue = 0, .accessfn = gt_ptimer_access,
2809       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2810     },
2811     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2812       .access = PL0_RW,
2813       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2814       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2815       .accessfn = gt_vtimer_access,
2816       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2817     },
2818     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2819       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2820       .access = PL0_RW,
2821       .type = ARM_CP_IO,
2822       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2823       .resetvalue = 0, .accessfn = gt_vtimer_access,
2824       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2825     },
2826     /* Secure timer -- this is actually restricted to only EL3
2827      * and configurably Secure-EL1 via the accessfn.
2828      */
2829     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2830       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2831       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2832       .accessfn = gt_stimer_access,
2833       .readfn = gt_sec_tval_read,
2834       .writefn = gt_sec_tval_write,
2835       .resetfn = gt_sec_timer_reset,
2836     },
2837     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2838       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2839       .type = ARM_CP_IO, .access = PL1_RW,
2840       .accessfn = gt_stimer_access,
2841       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2842       .resetvalue = 0,
2843       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2844     },
2845     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2846       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2847       .type = ARM_CP_IO, .access = PL1_RW,
2848       .accessfn = gt_stimer_access,
2849       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2850       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2851     },
2852     REGINFO_SENTINEL
2853 };
2854
2855 #else
2856
2857 /* In user-mode most of the generic timer registers are inaccessible
2858  * however modern kernels (4.12+) allow access to cntvct_el0
2859  */
2860
2861 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2862 {
2863     /* Currently we have no support for QEMUTimer in linux-user so we
2864      * can't call gt_get_countervalue(env), instead we directly
2865      * call the lower level functions.
2866      */
2867     return cpu_get_clock() / GTIMER_SCALE;
2868 }
2869
2870 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2871     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2872       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2873       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
2874       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2875       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
2876     },
2877     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2878       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2879       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2880       .readfn = gt_virt_cnt_read,
2881     },
2882     REGINFO_SENTINEL
2883 };
2884
2885 #endif
2886
2887 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2888 {
2889     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2890         raw_write(env, ri, value);
2891     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2892         raw_write(env, ri, value & 0xfffff6ff);
2893     } else {
2894         raw_write(env, ri, value & 0xfffff1ff);
2895     }
2896 }
2897
2898 #ifndef CONFIG_USER_ONLY
2899 /* get_phys_addr() isn't present for user-mode-only targets */
2900
2901 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2902                                  bool isread)
2903 {
2904     if (ri->opc2 & 4) {
2905         /* The ATS12NSO* operations must trap to EL3 if executed in
2906          * Secure EL1 (which can only happen if EL3 is AArch64).
2907          * They are simply UNDEF if executed from NS EL1.
2908          * They function normally from EL2 or EL3.
2909          */
2910         if (arm_current_el(env) == 1) {
2911             if (arm_is_secure_below_el3(env)) {
2912                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2913             }
2914             return CP_ACCESS_TRAP_UNCATEGORIZED;
2915         }
2916     }
2917     return CP_ACCESS_OK;
2918 }
2919
2920 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2921                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2922 {
2923     hwaddr phys_addr;
2924     target_ulong page_size;
2925     int prot;
2926     bool ret;
2927     uint64_t par64;
2928     bool format64 = false;
2929     MemTxAttrs attrs = {};
2930     ARMMMUFaultInfo fi = {};
2931     ARMCacheAttrs cacheattrs = {};
2932
2933     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2934                         &prot, &page_size, &fi, &cacheattrs);
2935
2936     if (is_a64(env)) {
2937         format64 = true;
2938     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
2939         /*
2940          * ATS1Cxx:
2941          * * TTBCR.EAE determines whether the result is returned using the
2942          *   32-bit or the 64-bit PAR format
2943          * * Instructions executed in Hyp mode always use the 64bit format
2944          *
2945          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
2946          * * The Non-secure TTBCR.EAE bit is set to 1
2947          * * The implementation includes EL2, and the value of HCR.VM is 1
2948          *
2949          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
2950          *
2951          * ATS1Hx always uses the 64bit format.
2952          */
2953         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
2954
2955         if (arm_feature(env, ARM_FEATURE_EL2)) {
2956             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
2957                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
2958             } else {
2959                 format64 |= arm_current_el(env) == 2;
2960             }
2961         }
2962     }
2963
2964     if (format64) {
2965         /* Create a 64-bit PAR */
2966         par64 = (1 << 11); /* LPAE bit always set */
2967         if (!ret) {
2968             par64 |= phys_addr & ~0xfffULL;
2969             if (!attrs.secure) {
2970                 par64 |= (1 << 9); /* NS */
2971             }
2972             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
2973             par64 |= cacheattrs.shareability << 7; /* SH */
2974         } else {
2975             uint32_t fsr = arm_fi_to_lfsc(&fi);
2976
2977             par64 |= 1; /* F */
2978             par64 |= (fsr & 0x3f) << 1; /* FS */
2979             if (fi.stage2) {
2980                 par64 |= (1 << 9); /* S */
2981             }
2982             if (fi.s1ptw) {
2983                 par64 |= (1 << 8); /* PTW */
2984             }
2985         }
2986     } else {
2987         /* fsr is a DFSR/IFSR value for the short descriptor
2988          * translation table format (with WnR always clear).
2989          * Convert it to a 32-bit PAR.
2990          */
2991         if (!ret) {
2992             /* We do not set any attribute bits in the PAR */
2993             if (page_size == (1 << 24)
2994                 && arm_feature(env, ARM_FEATURE_V7)) {
2995                 par64 = (phys_addr & 0xff000000) | (1 << 1);
2996             } else {
2997                 par64 = phys_addr & 0xfffff000;
2998             }
2999             if (!attrs.secure) {
3000                 par64 |= (1 << 9); /* NS */
3001             }
3002         } else {
3003             uint32_t fsr = arm_fi_to_sfsc(&fi);
3004
3005             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3006                     ((fsr & 0xf) << 1) | 1;
3007         }
3008     }
3009     return par64;
3010 }
3011
3012 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3013 {
3014     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3015     uint64_t par64;
3016     ARMMMUIdx mmu_idx;
3017     int el = arm_current_el(env);
3018     bool secure = arm_is_secure_below_el3(env);
3019
3020     switch (ri->opc2 & 6) {
3021     case 0:
3022         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
3023         switch (el) {
3024         case 3:
3025             mmu_idx = ARMMMUIdx_S1E3;
3026             break;
3027         case 2:
3028             mmu_idx = ARMMMUIdx_S1NSE1;
3029             break;
3030         case 1:
3031             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3032             break;
3033         default:
3034             g_assert_not_reached();
3035         }
3036         break;
3037     case 2:
3038         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3039         switch (el) {
3040         case 3:
3041             mmu_idx = ARMMMUIdx_S1SE0;
3042             break;
3043         case 2:
3044             mmu_idx = ARMMMUIdx_S1NSE0;
3045             break;
3046         case 1:
3047             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3048             break;
3049         default:
3050             g_assert_not_reached();
3051         }
3052         break;
3053     case 4:
3054         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3055         mmu_idx = ARMMMUIdx_S12NSE1;
3056         break;
3057     case 6:
3058         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3059         mmu_idx = ARMMMUIdx_S12NSE0;
3060         break;
3061     default:
3062         g_assert_not_reached();
3063     }
3064
3065     par64 = do_ats_write(env, value, access_type, mmu_idx);
3066
3067     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3068 }
3069
3070 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3071                         uint64_t value)
3072 {
3073     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3074     uint64_t par64;
3075
3076     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S1E2);
3077
3078     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3079 }
3080
3081 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3082                                      bool isread)
3083 {
3084     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
3085         return CP_ACCESS_TRAP;
3086     }
3087     return CP_ACCESS_OK;
3088 }
3089
3090 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3091                         uint64_t value)
3092 {
3093     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3094     ARMMMUIdx mmu_idx;
3095     int secure = arm_is_secure_below_el3(env);
3096
3097     switch (ri->opc2 & 6) {
3098     case 0:
3099         switch (ri->opc1) {
3100         case 0: /* AT S1E1R, AT S1E1W */
3101             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3102             break;
3103         case 4: /* AT S1E2R, AT S1E2W */
3104             mmu_idx = ARMMMUIdx_S1E2;
3105             break;
3106         case 6: /* AT S1E3R, AT S1E3W */
3107             mmu_idx = ARMMMUIdx_S1E3;
3108             break;
3109         default:
3110             g_assert_not_reached();
3111         }
3112         break;
3113     case 2: /* AT S1E0R, AT S1E0W */
3114         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3115         break;
3116     case 4: /* AT S12E1R, AT S12E1W */
3117         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
3118         break;
3119     case 6: /* AT S12E0R, AT S12E0W */
3120         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
3121         break;
3122     default:
3123         g_assert_not_reached();
3124     }
3125
3126     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3127 }
3128 #endif
3129
3130 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3131     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3132       .access = PL1_RW, .resetvalue = 0,
3133       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3134                              offsetoflow32(CPUARMState, cp15.par_ns) },
3135       .writefn = par_write },
3136 #ifndef CONFIG_USER_ONLY
3137     /* This underdecoding is safe because the reginfo is NO_RAW. */
3138     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3139       .access = PL1_W, .accessfn = ats_access,
3140       .writefn = ats_write, .type = ARM_CP_NO_RAW },
3141 #endif
3142     REGINFO_SENTINEL
3143 };
3144
3145 /* Return basic MPU access permission bits.  */
3146 static uint32_t simple_mpu_ap_bits(uint32_t val)
3147 {
3148     uint32_t ret;
3149     uint32_t mask;
3150     int i;
3151     ret = 0;
3152     mask = 3;
3153     for (i = 0; i < 16; i += 2) {
3154         ret |= (val >> i) & mask;
3155         mask <<= 2;
3156     }
3157     return ret;
3158 }
3159
3160 /* Pad basic MPU access permission bits to extended format.  */
3161 static uint32_t extended_mpu_ap_bits(uint32_t val)
3162 {
3163     uint32_t ret;
3164     uint32_t mask;
3165     int i;
3166     ret = 0;
3167     mask = 3;
3168     for (i = 0; i < 16; i += 2) {
3169         ret |= (val & mask) << i;
3170         mask <<= 2;
3171     }
3172     return ret;
3173 }
3174
3175 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3176                                  uint64_t value)
3177 {
3178     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3179 }
3180
3181 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3182 {
3183     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3184 }
3185
3186 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3187                                  uint64_t value)
3188 {
3189     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3190 }
3191
3192 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3193 {
3194     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3195 }
3196
3197 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3198 {
3199     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3200
3201     if (!u32p) {
3202         return 0;
3203     }
3204
3205     u32p += env->pmsav7.rnr[M_REG_NS];
3206     return *u32p;
3207 }
3208
3209 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3210                          uint64_t value)
3211 {
3212     ARMCPU *cpu = arm_env_get_cpu(env);
3213     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3214
3215     if (!u32p) {
3216         return;
3217     }
3218
3219     u32p += env->pmsav7.rnr[M_REG_NS];
3220     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3221     *u32p = value;
3222 }
3223
3224 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3225                               uint64_t value)
3226 {
3227     ARMCPU *cpu = arm_env_get_cpu(env);
3228     uint32_t nrgs = cpu->pmsav7_dregion;
3229
3230     if (value >= nrgs) {
3231         qemu_log_mask(LOG_GUEST_ERROR,
3232                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3233                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3234         return;
3235     }
3236
3237     raw_write(env, ri, value);
3238 }
3239
3240 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3241     /* Reset for all these registers is handled in arm_cpu_reset(),
3242      * because the PMSAv7 is also used by M-profile CPUs, which do
3243      * not register cpregs but still need the state to be reset.
3244      */
3245     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3246       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3247       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3248       .readfn = pmsav7_read, .writefn = pmsav7_write,
3249       .resetfn = arm_cp_reset_ignore },
3250     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3251       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3252       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3253       .readfn = pmsav7_read, .writefn = pmsav7_write,
3254       .resetfn = arm_cp_reset_ignore },
3255     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3256       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3257       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3258       .readfn = pmsav7_read, .writefn = pmsav7_write,
3259       .resetfn = arm_cp_reset_ignore },
3260     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3261       .access = PL1_RW,
3262       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3263       .writefn = pmsav7_rgnr_write,
3264       .resetfn = arm_cp_reset_ignore },
3265     REGINFO_SENTINEL
3266 };
3267
3268 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3269     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3270       .access = PL1_RW, .type = ARM_CP_ALIAS,
3271       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3272       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3273     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3274       .access = PL1_RW, .type = ARM_CP_ALIAS,
3275       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3276       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3277     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3278       .access = PL1_RW,
3279       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3280       .resetvalue = 0, },
3281     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3282       .access = PL1_RW,
3283       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3284       .resetvalue = 0, },
3285     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3286       .access = PL1_RW,
3287       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3288     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3289       .access = PL1_RW,
3290       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3291     /* Protection region base and size registers */
3292     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3293       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3294       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3295     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3296       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3297       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3298     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3299       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3300       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3301     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3302       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3303       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3304     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3305       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3306       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3307     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3308       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3309       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3310     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3311       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3312       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3313     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3314       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3315       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3316     REGINFO_SENTINEL
3317 };
3318
3319 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3320                                  uint64_t value)
3321 {
3322     TCR *tcr = raw_ptr(env, ri);
3323     int maskshift = extract32(value, 0, 3);
3324
3325     if (!arm_feature(env, ARM_FEATURE_V8)) {
3326         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3327             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3328              * using Long-desciptor translation table format */
3329             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3330         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3331             /* In an implementation that includes the Security Extensions
3332              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3333              * Short-descriptor translation table format.
3334              */
3335             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3336         } else {
3337             value &= TTBCR_N;
3338         }
3339     }
3340
3341     /* Update the masks corresponding to the TCR bank being written
3342      * Note that we always calculate mask and base_mask, but
3343      * they are only used for short-descriptor tables (ie if EAE is 0);
3344      * for long-descriptor tables the TCR fields are used differently
3345      * and the mask and base_mask values are meaningless.
3346      */
3347     tcr->raw_tcr = value;
3348     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3349     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3350 }
3351
3352 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3353                              uint64_t value)
3354 {
3355     ARMCPU *cpu = arm_env_get_cpu(env);
3356     TCR *tcr = raw_ptr(env, ri);
3357
3358     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3359         /* With LPAE the TTBCR could result in a change of ASID
3360          * via the TTBCR.A1 bit, so do a TLB flush.
3361          */
3362         tlb_flush(CPU(cpu));
3363     }
3364     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3365     value = deposit64(tcr->raw_tcr, 0, 32, value);
3366     vmsa_ttbcr_raw_write(env, ri, value);
3367 }
3368
3369 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3370 {
3371     TCR *tcr = raw_ptr(env, ri);
3372
3373     /* Reset both the TCR as well as the masks corresponding to the bank of
3374      * the TCR being reset.
3375      */
3376     tcr->raw_tcr = 0;
3377     tcr->mask = 0;
3378     tcr->base_mask = 0xffffc000u;
3379 }
3380
3381 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3382                                uint64_t value)
3383 {
3384     ARMCPU *cpu = arm_env_get_cpu(env);
3385     TCR *tcr = raw_ptr(env, ri);
3386
3387     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3388     tlb_flush(CPU(cpu));
3389     tcr->raw_tcr = value;
3390 }
3391
3392 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3393                             uint64_t value)
3394 {
3395     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3396     if (cpreg_field_is_64bit(ri) &&
3397         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3398         ARMCPU *cpu = arm_env_get_cpu(env);
3399         tlb_flush(CPU(cpu));
3400     }
3401     raw_write(env, ri, value);
3402 }
3403
3404 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3405                         uint64_t value)
3406 {
3407     ARMCPU *cpu = arm_env_get_cpu(env);
3408     CPUState *cs = CPU(cpu);
3409
3410     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
3411     if (raw_read(env, ri) != value) {
3412         tlb_flush_by_mmuidx(cs,
3413                             ARMMMUIdxBit_S12NSE1 |
3414                             ARMMMUIdxBit_S12NSE0 |
3415                             ARMMMUIdxBit_S2NS);
3416         raw_write(env, ri, value);
3417     }
3418 }
3419
3420 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3421     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3422       .access = PL1_RW, .type = ARM_CP_ALIAS,
3423       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3424                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3425     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3426       .access = PL1_RW, .resetvalue = 0,
3427       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3428                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3429     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3430       .access = PL1_RW, .resetvalue = 0,
3431       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3432                              offsetof(CPUARMState, cp15.dfar_ns) } },
3433     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3434       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3435       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3436       .resetvalue = 0, },
3437     REGINFO_SENTINEL
3438 };
3439
3440 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3441     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3442       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3443       .access = PL1_RW,
3444       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3445     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3446       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3447       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3448       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3449                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3450     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3451       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3452       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3453       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3454                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3455     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3456       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3457       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
3458       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3459       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3460     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3461       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3462       .raw_writefn = vmsa_ttbcr_raw_write,
3463       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
3464                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
3465     REGINFO_SENTINEL
3466 };
3467
3468 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3469  * qemu tlbs nor adjusting cached masks.
3470  */
3471 static const ARMCPRegInfo ttbcr2_reginfo = {
3472     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3473     .access = PL1_RW, .type = ARM_CP_ALIAS,
3474     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
3475                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
3476 };
3477
3478 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3479                                 uint64_t value)
3480 {
3481     env->cp15.c15_ticonfig = value & 0xe7;
3482     /* The OS_TYPE bit in this register changes the reported CPUID! */
3483     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3484         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3485 }
3486
3487 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3488                                 uint64_t value)
3489 {
3490     env->cp15.c15_threadid = value & 0xffff;
3491 }
3492
3493 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3494                            uint64_t value)
3495 {
3496     /* Wait-for-interrupt (deprecated) */
3497     cpu_interrupt(CPU(arm_env_get_cpu(env)), CPU_INTERRUPT_HALT);
3498 }
3499
3500 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3501                                   uint64_t value)
3502 {
3503     /* On OMAP there are registers indicating the max/min index of dcache lines
3504      * containing a dirty line; cache flush operations have to reset these.
3505      */
3506     env->cp15.c15_i_max = 0x000;
3507     env->cp15.c15_i_min = 0xff0;
3508 }
3509
3510 static const ARMCPRegInfo omap_cp_reginfo[] = {
3511     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3512       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3513       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3514       .resetvalue = 0, },
3515     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3516       .access = PL1_RW, .type = ARM_CP_NOP },
3517     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3518       .access = PL1_RW,
3519       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3520       .writefn = omap_ticonfig_write },
3521     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3522       .access = PL1_RW,
3523       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3524     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3525       .access = PL1_RW, .resetvalue = 0xff0,
3526       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3527     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3528       .access = PL1_RW,
3529       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3530       .writefn = omap_threadid_write },
3531     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3532       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3533       .type = ARM_CP_NO_RAW,
3534       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3535     /* TODO: Peripheral port remap register:
3536      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3537      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3538      * when MMU is off.
3539      */
3540     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3541       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3542       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3543       .writefn = omap_cachemaint_write },
3544     { .name = "C9", .cp = 15, .crn = 9,
3545       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3546       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3547     REGINFO_SENTINEL
3548 };
3549
3550 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3551                               uint64_t value)
3552 {
3553     env->cp15.c15_cpar = value & 0x3fff;
3554 }
3555
3556 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3557     { .name = "XSCALE_CPAR",
3558       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3559       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3560       .writefn = xscale_cpar_write, },
3561     { .name = "XSCALE_AUXCR",
3562       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3563       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3564       .resetvalue = 0, },
3565     /* XScale specific cache-lockdown: since we have no cache we NOP these
3566      * and hope the guest does not really rely on cache behaviour.
3567      */
3568     { .name = "XSCALE_LOCK_ICACHE_LINE",
3569       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3570       .access = PL1_W, .type = ARM_CP_NOP },
3571     { .name = "XSCALE_UNLOCK_ICACHE",
3572       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3573       .access = PL1_W, .type = ARM_CP_NOP },
3574     { .name = "XSCALE_DCACHE_LOCK",
3575       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3576       .access = PL1_RW, .type = ARM_CP_NOP },
3577     { .name = "XSCALE_UNLOCK_DCACHE",
3578       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3579       .access = PL1_W, .type = ARM_CP_NOP },
3580     REGINFO_SENTINEL
3581 };
3582
3583 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3584     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3585      * implementation of this implementation-defined space.
3586      * Ideally this should eventually disappear in favour of actually
3587      * implementing the correct behaviour for all cores.
3588      */
3589     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3590       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3591       .access = PL1_RW,
3592       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3593       .resetvalue = 0 },
3594     REGINFO_SENTINEL
3595 };
3596
3597 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3598     /* Cache status: RAZ because we have no cache so it's always clean */
3599     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3600       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3601       .resetvalue = 0 },
3602     REGINFO_SENTINEL
3603 };
3604
3605 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
3606     /* We never have a a block transfer operation in progress */
3607     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
3608       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3609       .resetvalue = 0 },
3610     /* The cache ops themselves: these all NOP for QEMU */
3611     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
3612       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3613     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
3614       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3615     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
3616       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3617     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
3618       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3619     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
3620       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3621     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
3622       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3623     REGINFO_SENTINEL
3624 };
3625
3626 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
3627     /* The cache test-and-clean instructions always return (1 << 30)
3628      * to indicate that there are no dirty cache lines.
3629      */
3630     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
3631       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3632       .resetvalue = (1 << 30) },
3633     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
3634       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3635       .resetvalue = (1 << 30) },
3636     REGINFO_SENTINEL
3637 };
3638
3639 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
3640     /* Ignore ReadBuffer accesses */
3641     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
3642       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3643       .access = PL1_RW, .resetvalue = 0,
3644       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
3645     REGINFO_SENTINEL
3646 };
3647
3648 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3649 {
3650     ARMCPU *cpu = arm_env_get_cpu(env);
3651     unsigned int cur_el = arm_current_el(env);
3652     bool secure = arm_is_secure(env);
3653
3654     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3655         return env->cp15.vpidr_el2;
3656     }
3657     return raw_read(env, ri);
3658 }
3659
3660 static uint64_t mpidr_read_val(CPUARMState *env)
3661 {
3662     ARMCPU *cpu = ARM_CPU(arm_env_get_cpu(env));
3663     uint64_t mpidr = cpu->mp_affinity;
3664
3665     if (arm_feature(env, ARM_FEATURE_V7MP)) {
3666         mpidr |= (1U << 31);
3667         /* Cores which are uniprocessor (non-coherent)
3668          * but still implement the MP extensions set
3669          * bit 30. (For instance, Cortex-R5).
3670          */
3671         if (cpu->mp_is_up) {
3672             mpidr |= (1u << 30);
3673         }
3674     }
3675     return mpidr;
3676 }
3677
3678 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3679 {
3680     unsigned int cur_el = arm_current_el(env);
3681     bool secure = arm_is_secure(env);
3682
3683     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3684         return env->cp15.vmpidr_el2;
3685     }
3686     return mpidr_read_val(env);
3687 }
3688
3689 static const ARMCPRegInfo lpae_cp_reginfo[] = {
3690     /* NOP AMAIR0/1 */
3691     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
3692       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
3693       .access = PL1_RW, .type = ARM_CP_CONST,
3694       .resetvalue = 0 },
3695     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
3696     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
3697       .access = PL1_RW, .type = ARM_CP_CONST,
3698       .resetvalue = 0 },
3699     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
3700       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
3701       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
3702                              offsetof(CPUARMState, cp15.par_ns)} },
3703     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
3704       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3705       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3706                              offsetof(CPUARMState, cp15.ttbr0_ns) },
3707       .writefn = vmsa_ttbr_write, },
3708     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
3709       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3710       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3711                              offsetof(CPUARMState, cp15.ttbr1_ns) },
3712       .writefn = vmsa_ttbr_write, },
3713     REGINFO_SENTINEL
3714 };
3715
3716 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3717 {
3718     return vfp_get_fpcr(env);
3719 }
3720
3721 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3722                             uint64_t value)
3723 {
3724     vfp_set_fpcr(env, value);
3725 }
3726
3727 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3728 {
3729     return vfp_get_fpsr(env);
3730 }
3731
3732 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3733                             uint64_t value)
3734 {
3735     vfp_set_fpsr(env, value);
3736 }
3737
3738 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
3739                                        bool isread)
3740 {
3741     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
3742         return CP_ACCESS_TRAP;
3743     }
3744     return CP_ACCESS_OK;
3745 }
3746
3747 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3748                             uint64_t value)
3749 {
3750     env->daif = value & PSTATE_DAIF;
3751 }
3752
3753 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3754                                           const ARMCPRegInfo *ri,
3755                                           bool isread)
3756 {
3757     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3758      * SCTLR_EL1.UCI is set.
3759      */
3760     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3761         return CP_ACCESS_TRAP;
3762     }
3763     return CP_ACCESS_OK;
3764 }
3765
3766 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3767  * Page D4-1736 (DDI0487A.b)
3768  */
3769
3770 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3771                                       uint64_t value)
3772 {
3773     CPUState *cs = ENV_GET_CPU(env);
3774     bool sec = arm_is_secure_below_el3(env);
3775
3776     if (sec) {
3777         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3778                                             ARMMMUIdxBit_S1SE1 |
3779                                             ARMMMUIdxBit_S1SE0);
3780     } else {
3781         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3782                                             ARMMMUIdxBit_S12NSE1 |
3783                                             ARMMMUIdxBit_S12NSE0);
3784     }
3785 }
3786
3787 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3788                                     uint64_t value)
3789 {
3790     CPUState *cs = ENV_GET_CPU(env);
3791
3792     if (tlb_force_broadcast(env)) {
3793         tlbi_aa64_vmalle1is_write(env, NULL, value);
3794         return;
3795     }
3796
3797     if (arm_is_secure_below_el3(env)) {
3798         tlb_flush_by_mmuidx(cs,
3799                             ARMMMUIdxBit_S1SE1 |
3800                             ARMMMUIdxBit_S1SE0);
3801     } else {
3802         tlb_flush_by_mmuidx(cs,
3803                             ARMMMUIdxBit_S12NSE1 |
3804                             ARMMMUIdxBit_S12NSE0);
3805     }
3806 }
3807
3808 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3809                                   uint64_t value)
3810 {
3811     /* Note that the 'ALL' scope must invalidate both stage 1 and
3812      * stage 2 translations, whereas most other scopes only invalidate
3813      * stage 1 translations.
3814      */
3815     ARMCPU *cpu = arm_env_get_cpu(env);
3816     CPUState *cs = CPU(cpu);
3817
3818     if (arm_is_secure_below_el3(env)) {
3819         tlb_flush_by_mmuidx(cs,
3820                             ARMMMUIdxBit_S1SE1 |
3821                             ARMMMUIdxBit_S1SE0);
3822     } else {
3823         if (arm_feature(env, ARM_FEATURE_EL2)) {
3824             tlb_flush_by_mmuidx(cs,
3825                                 ARMMMUIdxBit_S12NSE1 |
3826                                 ARMMMUIdxBit_S12NSE0 |
3827                                 ARMMMUIdxBit_S2NS);
3828         } else {
3829             tlb_flush_by_mmuidx(cs,
3830                                 ARMMMUIdxBit_S12NSE1 |
3831                                 ARMMMUIdxBit_S12NSE0);
3832         }
3833     }
3834 }
3835
3836 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3837                                   uint64_t value)
3838 {
3839     ARMCPU *cpu = arm_env_get_cpu(env);
3840     CPUState *cs = CPU(cpu);
3841
3842     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3843 }
3844
3845 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3846                                   uint64_t value)
3847 {
3848     ARMCPU *cpu = arm_env_get_cpu(env);
3849     CPUState *cs = CPU(cpu);
3850
3851     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3852 }
3853
3854 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3855                                     uint64_t value)
3856 {
3857     /* Note that the 'ALL' scope must invalidate both stage 1 and
3858      * stage 2 translations, whereas most other scopes only invalidate
3859      * stage 1 translations.
3860      */
3861     CPUState *cs = ENV_GET_CPU(env);
3862     bool sec = arm_is_secure_below_el3(env);
3863     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3864
3865     if (sec) {
3866         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3867                                             ARMMMUIdxBit_S1SE1 |
3868                                             ARMMMUIdxBit_S1SE0);
3869     } else if (has_el2) {
3870         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3871                                             ARMMMUIdxBit_S12NSE1 |
3872                                             ARMMMUIdxBit_S12NSE0 |
3873                                             ARMMMUIdxBit_S2NS);
3874     } else {
3875           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3876                                               ARMMMUIdxBit_S12NSE1 |
3877                                               ARMMMUIdxBit_S12NSE0);
3878     }
3879 }
3880
3881 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3882                                     uint64_t value)
3883 {
3884     CPUState *cs = ENV_GET_CPU(env);
3885
3886     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3887 }
3888
3889 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3890                                     uint64_t value)
3891 {
3892     CPUState *cs = ENV_GET_CPU(env);
3893
3894     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3895 }
3896
3897 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3898                                  uint64_t value)
3899 {
3900     /* Invalidate by VA, EL2
3901      * Currently handles both VAE2 and VALE2, since we don't support
3902      * flush-last-level-only.
3903      */
3904     ARMCPU *cpu = arm_env_get_cpu(env);
3905     CPUState *cs = CPU(cpu);
3906     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3907
3908     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3909 }
3910
3911 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3912                                  uint64_t value)
3913 {
3914     /* Invalidate by VA, EL3
3915      * Currently handles both VAE3 and VALE3, since we don't support
3916      * flush-last-level-only.
3917      */
3918     ARMCPU *cpu = arm_env_get_cpu(env);
3919     CPUState *cs = CPU(cpu);
3920     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3921
3922     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
3923 }
3924
3925 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3926                                    uint64_t value)
3927 {
3928     ARMCPU *cpu = arm_env_get_cpu(env);
3929     CPUState *cs = CPU(cpu);
3930     bool sec = arm_is_secure_below_el3(env);
3931     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3932
3933     if (sec) {
3934         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3935                                                  ARMMMUIdxBit_S1SE1 |
3936                                                  ARMMMUIdxBit_S1SE0);
3937     } else {
3938         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3939                                                  ARMMMUIdxBit_S12NSE1 |
3940                                                  ARMMMUIdxBit_S12NSE0);
3941     }
3942 }
3943
3944 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3945                                  uint64_t value)
3946 {
3947     /* Invalidate by VA, EL1&0 (AArch64 version).
3948      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3949      * since we don't support flush-for-specific-ASID-only or
3950      * flush-last-level-only.
3951      */
3952     ARMCPU *cpu = arm_env_get_cpu(env);
3953     CPUState *cs = CPU(cpu);
3954     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3955
3956     if (tlb_force_broadcast(env)) {
3957         tlbi_aa64_vae1is_write(env, NULL, value);
3958         return;
3959     }
3960
3961     if (arm_is_secure_below_el3(env)) {
3962         tlb_flush_page_by_mmuidx(cs, pageaddr,
3963                                  ARMMMUIdxBit_S1SE1 |
3964                                  ARMMMUIdxBit_S1SE0);
3965     } else {
3966         tlb_flush_page_by_mmuidx(cs, pageaddr,
3967                                  ARMMMUIdxBit_S12NSE1 |
3968                                  ARMMMUIdxBit_S12NSE0);
3969     }
3970 }
3971
3972 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3973                                    uint64_t value)
3974 {
3975     CPUState *cs = ENV_GET_CPU(env);
3976     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3977
3978     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3979                                              ARMMMUIdxBit_S1E2);
3980 }
3981
3982 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3983                                    uint64_t value)
3984 {
3985     CPUState *cs = ENV_GET_CPU(env);
3986     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3987
3988     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3989                                              ARMMMUIdxBit_S1E3);
3990 }
3991
3992 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3993                                     uint64_t value)
3994 {
3995     /* Invalidate by IPA. This has to invalidate any structures that
3996      * contain only stage 2 translation information, but does not need
3997      * to apply to structures that contain combined stage 1 and stage 2
3998      * translation information.
3999      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
4000      */
4001     ARMCPU *cpu = arm_env_get_cpu(env);
4002     CPUState *cs = CPU(cpu);
4003     uint64_t pageaddr;
4004
4005     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4006         return;
4007     }
4008
4009     pageaddr = sextract64(value << 12, 0, 48);
4010
4011     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
4012 }
4013
4014 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4015                                       uint64_t value)
4016 {
4017     CPUState *cs = ENV_GET_CPU(env);
4018     uint64_t pageaddr;
4019
4020     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4021         return;
4022     }
4023
4024     pageaddr = sextract64(value << 12, 0, 48);
4025
4026     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4027                                              ARMMMUIdxBit_S2NS);
4028 }
4029
4030 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4031                                       bool isread)
4032 {
4033     /* We don't implement EL2, so the only control on DC ZVA is the
4034      * bit in the SCTLR which can prohibit access for EL0.
4035      */
4036     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4037         return CP_ACCESS_TRAP;
4038     }
4039     return CP_ACCESS_OK;
4040 }
4041
4042 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4043 {
4044     ARMCPU *cpu = arm_env_get_cpu(env);
4045     int dzp_bit = 1 << 4;
4046
4047     /* DZP indicates whether DC ZVA access is allowed */
4048     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4049         dzp_bit = 0;
4050     }
4051     return cpu->dcz_blocksize | dzp_bit;
4052 }
4053
4054 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4055                                     bool isread)
4056 {
4057     if (!(env->pstate & PSTATE_SP)) {
4058         /* Access to SP_EL0 is undefined if it's being used as
4059          * the stack pointer.
4060          */
4061         return CP_ACCESS_TRAP_UNCATEGORIZED;
4062     }
4063     return CP_ACCESS_OK;
4064 }
4065
4066 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4067 {
4068     return env->pstate & PSTATE_SP;
4069 }
4070
4071 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4072 {
4073     update_spsel(env, val);
4074 }
4075
4076 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4077                         uint64_t value)
4078 {
4079     ARMCPU *cpu = arm_env_get_cpu(env);
4080
4081     if (raw_read(env, ri) == value) {
4082         /* Skip the TLB flush if nothing actually changed; Linux likes
4083          * to do a lot of pointless SCTLR writes.
4084          */
4085         return;
4086     }
4087
4088     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4089         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4090         value &= ~SCTLR_M;
4091     }
4092
4093     raw_write(env, ri, value);
4094     /* ??? Lots of these bits are not implemented.  */
4095     /* This may enable/disable the MMU, so do a TLB flush.  */
4096     tlb_flush(CPU(cpu));
4097 }
4098
4099 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4100                                      bool isread)
4101 {
4102     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4103         return CP_ACCESS_TRAP_FP_EL2;
4104     }
4105     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4106         return CP_ACCESS_TRAP_FP_EL3;
4107     }
4108     return CP_ACCESS_OK;
4109 }
4110
4111 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4112                        uint64_t value)
4113 {
4114     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4115 }
4116
4117 static const ARMCPRegInfo v8_cp_reginfo[] = {
4118     /* Minimal set of EL0-visible registers. This will need to be expanded
4119      * significantly for system emulation of AArch64 CPUs.
4120      */
4121     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4122       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4123       .access = PL0_RW, .type = ARM_CP_NZCV },
4124     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4125       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4126       .type = ARM_CP_NO_RAW,
4127       .access = PL0_RW, .accessfn = aa64_daif_access,
4128       .fieldoffset = offsetof(CPUARMState, daif),
4129       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4130     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4131       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4132       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4133       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4134     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4135       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4136       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4137       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4138     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4139       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4140       .access = PL0_R, .type = ARM_CP_NO_RAW,
4141       .readfn = aa64_dczid_read },
4142     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4143       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4144       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4145 #ifndef CONFIG_USER_ONLY
4146       /* Avoid overhead of an access check that always passes in user-mode */
4147       .accessfn = aa64_zva_access,
4148 #endif
4149     },
4150     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4151       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4152       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4153     /* Cache ops: all NOPs since we don't emulate caches */
4154     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4155       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4156       .access = PL1_W, .type = ARM_CP_NOP },
4157     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4158       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4159       .access = PL1_W, .type = ARM_CP_NOP },
4160     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4161       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4162       .access = PL0_W, .type = ARM_CP_NOP,
4163       .accessfn = aa64_cacheop_access },
4164     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4165       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4166       .access = PL1_W, .type = ARM_CP_NOP },
4167     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4168       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4169       .access = PL1_W, .type = ARM_CP_NOP },
4170     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4171       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4172       .access = PL0_W, .type = ARM_CP_NOP,
4173       .accessfn = aa64_cacheop_access },
4174     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4175       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4176       .access = PL1_W, .type = ARM_CP_NOP },
4177     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4178       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4179       .access = PL0_W, .type = ARM_CP_NOP,
4180       .accessfn = aa64_cacheop_access },
4181     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4182       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4183       .access = PL0_W, .type = ARM_CP_NOP,
4184       .accessfn = aa64_cacheop_access },
4185     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4186       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4187       .access = PL1_W, .type = ARM_CP_NOP },
4188     /* TLBI operations */
4189     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4190       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4191       .access = PL1_W, .type = ARM_CP_NO_RAW,
4192       .writefn = tlbi_aa64_vmalle1is_write },
4193     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4194       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4195       .access = PL1_W, .type = ARM_CP_NO_RAW,
4196       .writefn = tlbi_aa64_vae1is_write },
4197     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4198       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4199       .access = PL1_W, .type = ARM_CP_NO_RAW,
4200       .writefn = tlbi_aa64_vmalle1is_write },
4201     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4202       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4203       .access = PL1_W, .type = ARM_CP_NO_RAW,
4204       .writefn = tlbi_aa64_vae1is_write },
4205     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4206       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4207       .access = PL1_W, .type = ARM_CP_NO_RAW,
4208       .writefn = tlbi_aa64_vae1is_write },
4209     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4210       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4211       .access = PL1_W, .type = ARM_CP_NO_RAW,
4212       .writefn = tlbi_aa64_vae1is_write },
4213     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4214       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4215       .access = PL1_W, .type = ARM_CP_NO_RAW,
4216       .writefn = tlbi_aa64_vmalle1_write },
4217     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4218       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4219       .access = PL1_W, .type = ARM_CP_NO_RAW,
4220       .writefn = tlbi_aa64_vae1_write },
4221     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4222       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4223       .access = PL1_W, .type = ARM_CP_NO_RAW,
4224       .writefn = tlbi_aa64_vmalle1_write },
4225     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4226       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4227       .access = PL1_W, .type = ARM_CP_NO_RAW,
4228       .writefn = tlbi_aa64_vae1_write },
4229     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4230       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4231       .access = PL1_W, .type = ARM_CP_NO_RAW,
4232       .writefn = tlbi_aa64_vae1_write },
4233     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4234       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4235       .access = PL1_W, .type = ARM_CP_NO_RAW,
4236       .writefn = tlbi_aa64_vae1_write },
4237     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4238       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4239       .access = PL2_W, .type = ARM_CP_NO_RAW,
4240       .writefn = tlbi_aa64_ipas2e1is_write },
4241     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4242       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4243       .access = PL2_W, .type = ARM_CP_NO_RAW,
4244       .writefn = tlbi_aa64_ipas2e1is_write },
4245     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4246       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4247       .access = PL2_W, .type = ARM_CP_NO_RAW,
4248       .writefn = tlbi_aa64_alle1is_write },
4249     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4250       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4251       .access = PL2_W, .type = ARM_CP_NO_RAW,
4252       .writefn = tlbi_aa64_alle1is_write },
4253     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4254       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4255       .access = PL2_W, .type = ARM_CP_NO_RAW,
4256       .writefn = tlbi_aa64_ipas2e1_write },
4257     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4258       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4259       .access = PL2_W, .type = ARM_CP_NO_RAW,
4260       .writefn = tlbi_aa64_ipas2e1_write },
4261     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4262       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4263       .access = PL2_W, .type = ARM_CP_NO_RAW,
4264       .writefn = tlbi_aa64_alle1_write },
4265     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4266       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4267       .access = PL2_W, .type = ARM_CP_NO_RAW,
4268       .writefn = tlbi_aa64_alle1is_write },
4269 #ifndef CONFIG_USER_ONLY
4270     /* 64 bit address translation operations */
4271     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4272       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4273       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4274     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4275       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4276       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4277     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4278       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4279       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4280     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4281       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4282       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4283     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4284       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4285       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4286     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4287       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4288       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4289     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4290       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4291       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4292     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4293       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4294       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4295     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4296     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4297       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4298       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4299     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4300       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4301       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4302     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4303       .type = ARM_CP_ALIAS,
4304       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4305       .access = PL1_RW, .resetvalue = 0,
4306       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4307       .writefn = par_write },
4308 #endif
4309     /* TLB invalidate last level of translation table walk */
4310     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4311       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
4312     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4313       .type = ARM_CP_NO_RAW, .access = PL1_W,
4314       .writefn = tlbimvaa_is_write },
4315     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4316       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
4317     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4318       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
4319     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4320       .type = ARM_CP_NO_RAW, .access = PL2_W,
4321       .writefn = tlbimva_hyp_write },
4322     { .name = "TLBIMVALHIS",
4323       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4324       .type = ARM_CP_NO_RAW, .access = PL2_W,
4325       .writefn = tlbimva_hyp_is_write },
4326     { .name = "TLBIIPAS2",
4327       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4328       .type = ARM_CP_NO_RAW, .access = PL2_W,
4329       .writefn = tlbiipas2_write },
4330     { .name = "TLBIIPAS2IS",
4331       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4332       .type = ARM_CP_NO_RAW, .access = PL2_W,
4333       .writefn = tlbiipas2_is_write },
4334     { .name = "TLBIIPAS2L",
4335       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4336       .type = ARM_CP_NO_RAW, .access = PL2_W,
4337       .writefn = tlbiipas2_write },
4338     { .name = "TLBIIPAS2LIS",
4339       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4340       .type = ARM_CP_NO_RAW, .access = PL2_W,
4341       .writefn = tlbiipas2_is_write },
4342     /* 32 bit cache operations */
4343     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4344       .type = ARM_CP_NOP, .access = PL1_W },
4345     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
4346       .type = ARM_CP_NOP, .access = PL1_W },
4347     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4348       .type = ARM_CP_NOP, .access = PL1_W },
4349     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
4350       .type = ARM_CP_NOP, .access = PL1_W },
4351     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
4352       .type = ARM_CP_NOP, .access = PL1_W },
4353     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
4354       .type = ARM_CP_NOP, .access = PL1_W },
4355     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4356       .type = ARM_CP_NOP, .access = PL1_W },
4357     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4358       .type = ARM_CP_NOP, .access = PL1_W },
4359     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
4360       .type = ARM_CP_NOP, .access = PL1_W },
4361     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4362       .type = ARM_CP_NOP, .access = PL1_W },
4363     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
4364       .type = ARM_CP_NOP, .access = PL1_W },
4365     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
4366       .type = ARM_CP_NOP, .access = PL1_W },
4367     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4368       .type = ARM_CP_NOP, .access = PL1_W },
4369     /* MMU Domain access control / MPU write buffer control */
4370     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
4371       .access = PL1_RW, .resetvalue = 0,
4372       .writefn = dacr_write, .raw_writefn = raw_write,
4373       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
4374                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
4375     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
4376       .type = ARM_CP_ALIAS,
4377       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
4378       .access = PL1_RW,
4379       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
4380     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
4381       .type = ARM_CP_ALIAS,
4382       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
4383       .access = PL1_RW,
4384       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
4385     /* We rely on the access checks not allowing the guest to write to the
4386      * state field when SPSel indicates that it's being used as the stack
4387      * pointer.
4388      */
4389     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
4390       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
4391       .access = PL1_RW, .accessfn = sp_el0_access,
4392       .type = ARM_CP_ALIAS,
4393       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
4394     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
4395       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
4396       .access = PL2_RW, .type = ARM_CP_ALIAS,
4397       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
4398     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
4399       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
4400       .type = ARM_CP_NO_RAW,
4401       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
4402     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
4403       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
4404       .type = ARM_CP_ALIAS,
4405       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
4406       .access = PL2_RW, .accessfn = fpexc32_access },
4407     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
4408       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
4409       .access = PL2_RW, .resetvalue = 0,
4410       .writefn = dacr_write, .raw_writefn = raw_write,
4411       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
4412     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
4413       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
4414       .access = PL2_RW, .resetvalue = 0,
4415       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
4416     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
4417       .type = ARM_CP_ALIAS,
4418       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
4419       .access = PL2_RW,
4420       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
4421     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
4422       .type = ARM_CP_ALIAS,
4423       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
4424       .access = PL2_RW,
4425       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
4426     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
4427       .type = ARM_CP_ALIAS,
4428       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
4429       .access = PL2_RW,
4430       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
4431     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
4432       .type = ARM_CP_ALIAS,
4433       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
4434       .access = PL2_RW,
4435       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
4436     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
4437       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
4438       .resetvalue = 0,
4439       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
4440     { .name = "SDCR", .type = ARM_CP_ALIAS,
4441       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
4442       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4443       .writefn = sdcr_write,
4444       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
4445     REGINFO_SENTINEL
4446 };
4447
4448 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
4449 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
4450     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4451       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4452       .access = PL2_RW,
4453       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
4454     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
4455       .type = ARM_CP_NO_RAW,
4456       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4457       .access = PL2_RW,
4458       .type = ARM_CP_CONST, .resetvalue = 0 },
4459     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4460       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4461       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4462     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4463       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4464       .access = PL2_RW,
4465       .type = ARM_CP_CONST, .resetvalue = 0 },
4466     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4467       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4468       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4469     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4470       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4471       .access = PL2_RW, .type = ARM_CP_CONST,
4472       .resetvalue = 0 },
4473     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4474       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4475       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4476     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4477       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4478       .access = PL2_RW, .type = ARM_CP_CONST,
4479       .resetvalue = 0 },
4480     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4481       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4482       .access = PL2_RW, .type = ARM_CP_CONST,
4483       .resetvalue = 0 },
4484     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4485       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4486       .access = PL2_RW, .type = ARM_CP_CONST,
4487       .resetvalue = 0 },
4488     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4489       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4490       .access = PL2_RW, .type = ARM_CP_CONST,
4491       .resetvalue = 0 },
4492     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4493       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4494       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4495     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
4496       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4497       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4498       .type = ARM_CP_CONST, .resetvalue = 0 },
4499     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4500       .cp = 15, .opc1 = 6, .crm = 2,
4501       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4502       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
4503     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4504       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4505       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4506     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4507       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4508       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4509     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4510       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4511       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4512     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4513       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4514       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4515     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4516       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4517       .resetvalue = 0 },
4518     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4519       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4520       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4521     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4522       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4523       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4524     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4525       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4526       .resetvalue = 0 },
4527     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4528       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4529       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4530     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4531       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4532       .resetvalue = 0 },
4533     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4534       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4535       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4536     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4537       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4538       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4539     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4540       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4541       .access = PL2_RW, .accessfn = access_tda,
4542       .type = ARM_CP_CONST, .resetvalue = 0 },
4543     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
4544       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4545       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4546       .type = ARM_CP_CONST, .resetvalue = 0 },
4547     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4548       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4549       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4550     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4551       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4552       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4553     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4554       .type = ARM_CP_CONST,
4555       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4556       .access = PL2_RW, .resetvalue = 0 },
4557     REGINFO_SENTINEL
4558 };
4559
4560 /* Ditto, but for registers which exist in ARMv8 but not v7 */
4561 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
4562     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4563       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4564       .access = PL2_RW,
4565       .type = ARM_CP_CONST, .resetvalue = 0 },
4566     REGINFO_SENTINEL
4567 };
4568
4569 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
4570 {
4571     ARMCPU *cpu = arm_env_get_cpu(env);
4572     uint64_t valid_mask = HCR_MASK;
4573
4574     if (arm_feature(env, ARM_FEATURE_EL3)) {
4575         valid_mask &= ~HCR_HCD;
4576     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
4577         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
4578          * However, if we're using the SMC PSCI conduit then QEMU is
4579          * effectively acting like EL3 firmware and so the guest at
4580          * EL2 should retain the ability to prevent EL1 from being
4581          * able to make SMC calls into the ersatz firmware, so in
4582          * that case HCR.TSC should be read/write.
4583          */
4584         valid_mask &= ~HCR_TSC;
4585     }
4586     if (cpu_isar_feature(aa64_lor, cpu)) {
4587         valid_mask |= HCR_TLOR;
4588     }
4589     if (cpu_isar_feature(aa64_pauth, cpu)) {
4590         valid_mask |= HCR_API | HCR_APK;
4591     }
4592
4593     /* Clear RES0 bits.  */
4594     value &= valid_mask;
4595
4596     /* These bits change the MMU setup:
4597      * HCR_VM enables stage 2 translation
4598      * HCR_PTW forbids certain page-table setups
4599      * HCR_DC Disables stage1 and enables stage2 translation
4600      */
4601     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
4602         tlb_flush(CPU(cpu));
4603     }
4604     env->cp15.hcr_el2 = value;
4605
4606     /*
4607      * Updates to VI and VF require us to update the status of
4608      * virtual interrupts, which are the logical OR of these bits
4609      * and the state of the input lines from the GIC. (This requires
4610      * that we have the iothread lock, which is done by marking the
4611      * reginfo structs as ARM_CP_IO.)
4612      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
4613      * possible for it to be taken immediately, because VIRQ and
4614      * VFIQ are masked unless running at EL0 or EL1, and HCR
4615      * can only be written at EL2.
4616      */
4617     g_assert(qemu_mutex_iothread_locked());
4618     arm_cpu_update_virq(cpu);
4619     arm_cpu_update_vfiq(cpu);
4620 }
4621
4622 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
4623                           uint64_t value)
4624 {
4625     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
4626     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
4627     hcr_write(env, NULL, value);
4628 }
4629
4630 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
4631                          uint64_t value)
4632 {
4633     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
4634     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
4635     hcr_write(env, NULL, value);
4636 }
4637
4638 /*
4639  * Return the effective value of HCR_EL2.
4640  * Bits that are not included here:
4641  * RW       (read from SCR_EL3.RW as needed)
4642  */
4643 uint64_t arm_hcr_el2_eff(CPUARMState *env)
4644 {
4645     uint64_t ret = env->cp15.hcr_el2;
4646
4647     if (arm_is_secure_below_el3(env)) {
4648         /*
4649          * "This register has no effect if EL2 is not enabled in the
4650          * current Security state".  This is ARMv8.4-SecEL2 speak for
4651          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
4652          *
4653          * Prior to that, the language was "In an implementation that
4654          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
4655          * as if this field is 0 for all purposes other than a direct
4656          * read or write access of HCR_EL2".  With lots of enumeration
4657          * on a per-field basis.  In current QEMU, this is condition
4658          * is arm_is_secure_below_el3.
4659          *
4660          * Since the v8.4 language applies to the entire register, and
4661          * appears to be backward compatible, use that.
4662          */
4663         ret = 0;
4664     } else if (ret & HCR_TGE) {
4665         /* These bits are up-to-date as of ARMv8.4.  */
4666         if (ret & HCR_E2H) {
4667             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
4668                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
4669                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
4670                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE);
4671         } else {
4672             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
4673         }
4674         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
4675                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
4676                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
4677                  HCR_TLOR);
4678     }
4679
4680     return ret;
4681 }
4682
4683 static const ARMCPRegInfo el2_cp_reginfo[] = {
4684     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
4685       .type = ARM_CP_IO,
4686       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4687       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4688       .writefn = hcr_write },
4689     { .name = "HCR", .state = ARM_CP_STATE_AA32,
4690       .type = ARM_CP_ALIAS | ARM_CP_IO,
4691       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4692       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4693       .writefn = hcr_writelow },
4694     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4695       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4696       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4697     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
4698       .type = ARM_CP_ALIAS,
4699       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
4700       .access = PL2_RW,
4701       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
4702     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4703       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4704       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
4705     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4706       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4707       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
4708     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4709       .type = ARM_CP_ALIAS,
4710       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4711       .access = PL2_RW,
4712       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
4713     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
4714       .type = ARM_CP_ALIAS,
4715       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
4716       .access = PL2_RW,
4717       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
4718     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4719       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4720       .access = PL2_RW, .writefn = vbar_write,
4721       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
4722       .resetvalue = 0 },
4723     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
4724       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
4725       .access = PL3_RW, .type = ARM_CP_ALIAS,
4726       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
4727     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4728       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4729       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
4730       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]) },
4731     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4732       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4733       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
4734       .resetvalue = 0 },
4735     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4736       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4737       .access = PL2_RW, .type = ARM_CP_ALIAS,
4738       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
4739     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4740       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4741       .access = PL2_RW, .type = ARM_CP_CONST,
4742       .resetvalue = 0 },
4743     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
4744     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4745       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4746       .access = PL2_RW, .type = ARM_CP_CONST,
4747       .resetvalue = 0 },
4748     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4749       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4750       .access = PL2_RW, .type = ARM_CP_CONST,
4751       .resetvalue = 0 },
4752     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4753       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4754       .access = PL2_RW, .type = ARM_CP_CONST,
4755       .resetvalue = 0 },
4756     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4757       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4758       .access = PL2_RW,
4759       /* no .writefn needed as this can't cause an ASID change;
4760        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4761        */
4762       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
4763     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
4764       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4765       .type = ARM_CP_ALIAS,
4766       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4767       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4768     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
4769       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4770       .access = PL2_RW,
4771       /* no .writefn needed as this can't cause an ASID change;
4772        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4773        */
4774       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4775     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4776       .cp = 15, .opc1 = 6, .crm = 2,
4777       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4778       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4779       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
4780       .writefn = vttbr_write },
4781     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4782       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4783       .access = PL2_RW, .writefn = vttbr_write,
4784       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
4785     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4786       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4787       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
4788       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
4789     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4790       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4791       .access = PL2_RW, .resetvalue = 0,
4792       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
4793     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4794       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4795       .access = PL2_RW, .resetvalue = 0,
4796       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4797     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4798       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4799       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4800     { .name = "TLBIALLNSNH",
4801       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4802       .type = ARM_CP_NO_RAW, .access = PL2_W,
4803       .writefn = tlbiall_nsnh_write },
4804     { .name = "TLBIALLNSNHIS",
4805       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4806       .type = ARM_CP_NO_RAW, .access = PL2_W,
4807       .writefn = tlbiall_nsnh_is_write },
4808     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4809       .type = ARM_CP_NO_RAW, .access = PL2_W,
4810       .writefn = tlbiall_hyp_write },
4811     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4812       .type = ARM_CP_NO_RAW, .access = PL2_W,
4813       .writefn = tlbiall_hyp_is_write },
4814     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4815       .type = ARM_CP_NO_RAW, .access = PL2_W,
4816       .writefn = tlbimva_hyp_write },
4817     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4818       .type = ARM_CP_NO_RAW, .access = PL2_W,
4819       .writefn = tlbimva_hyp_is_write },
4820     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
4821       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4822       .type = ARM_CP_NO_RAW, .access = PL2_W,
4823       .writefn = tlbi_aa64_alle2_write },
4824     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
4825       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4826       .type = ARM_CP_NO_RAW, .access = PL2_W,
4827       .writefn = tlbi_aa64_vae2_write },
4828     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
4829       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4830       .access = PL2_W, .type = ARM_CP_NO_RAW,
4831       .writefn = tlbi_aa64_vae2_write },
4832     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
4833       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4834       .access = PL2_W, .type = ARM_CP_NO_RAW,
4835       .writefn = tlbi_aa64_alle2is_write },
4836     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
4837       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4838       .type = ARM_CP_NO_RAW, .access = PL2_W,
4839       .writefn = tlbi_aa64_vae2is_write },
4840     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
4841       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4842       .access = PL2_W, .type = ARM_CP_NO_RAW,
4843       .writefn = tlbi_aa64_vae2is_write },
4844 #ifndef CONFIG_USER_ONLY
4845     /* Unlike the other EL2-related AT operations, these must
4846      * UNDEF from EL3 if EL2 is not implemented, which is why we
4847      * define them here rather than with the rest of the AT ops.
4848      */
4849     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
4850       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4851       .access = PL2_W, .accessfn = at_s1e2_access,
4852       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4853     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
4854       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4855       .access = PL2_W, .accessfn = at_s1e2_access,
4856       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4857     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
4858      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
4859      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
4860      * to behave as if SCR.NS was 1.
4861      */
4862     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4863       .access = PL2_W,
4864       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4865     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4866       .access = PL2_W,
4867       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4868     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4869       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4870       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
4871        * reset values as IMPDEF. We choose to reset to 3 to comply with
4872        * both ARMv7 and ARMv8.
4873        */
4874       .access = PL2_RW, .resetvalue = 3,
4875       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
4876     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4877       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4878       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
4879       .writefn = gt_cntvoff_write,
4880       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4881     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4882       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
4883       .writefn = gt_cntvoff_write,
4884       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4885     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4886       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4887       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4888       .type = ARM_CP_IO, .access = PL2_RW,
4889       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4890     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4891       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4892       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
4893       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4894     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4895       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4896       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
4897       .resetfn = gt_hyp_timer_reset,
4898       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
4899     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4900       .type = ARM_CP_IO,
4901       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4902       .access = PL2_RW,
4903       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
4904       .resetvalue = 0,
4905       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
4906 #endif
4907     /* The only field of MDCR_EL2 that has a defined architectural reset value
4908      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
4909      * don't implement any PMU event counters, so using zero as a reset
4910      * value for MDCR_EL2 is okay
4911      */
4912     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4913       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4914       .access = PL2_RW, .resetvalue = 0,
4915       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
4916     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
4917       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4918       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4919       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4920     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
4921       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4922       .access = PL2_RW,
4923       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4924     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4925       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4926       .access = PL2_RW,
4927       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
4928     REGINFO_SENTINEL
4929 };
4930
4931 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
4932     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4933       .type = ARM_CP_ALIAS | ARM_CP_IO,
4934       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4935       .access = PL2_RW,
4936       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
4937       .writefn = hcr_writehigh },
4938     REGINFO_SENTINEL
4939 };
4940
4941 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
4942                                    bool isread)
4943 {
4944     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
4945      * At Secure EL1 it traps to EL3.
4946      */
4947     if (arm_current_el(env) == 3) {
4948         return CP_ACCESS_OK;
4949     }
4950     if (arm_is_secure_below_el3(env)) {
4951         return CP_ACCESS_TRAP_EL3;
4952     }
4953     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
4954     if (isread) {
4955         return CP_ACCESS_OK;
4956     }
4957     return CP_ACCESS_TRAP_UNCATEGORIZED;
4958 }
4959
4960 static const ARMCPRegInfo el3_cp_reginfo[] = {
4961     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
4962       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
4963       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
4964       .resetvalue = 0, .writefn = scr_write },
4965     { .name = "SCR",  .type = ARM_CP_ALIAS,
4966       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
4967       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4968       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
4969       .writefn = scr_write },
4970     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
4971       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
4972       .access = PL3_RW, .resetvalue = 0,
4973       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
4974     { .name = "SDER",
4975       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
4976       .access = PL3_RW, .resetvalue = 0,
4977       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
4978     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
4979       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4980       .writefn = vbar_write, .resetvalue = 0,
4981       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
4982     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
4983       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
4984       .access = PL3_RW, .resetvalue = 0,
4985       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
4986     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
4987       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
4988       .access = PL3_RW,
4989       /* no .writefn needed as this can't cause an ASID change;
4990        * we must provide a .raw_writefn and .resetfn because we handle
4991        * reset and migration for the AArch32 TTBCR(S), which might be
4992        * using mask and base_mask.
4993        */
4994       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
4995       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
4996     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
4997       .type = ARM_CP_ALIAS,
4998       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
4999       .access = PL3_RW,
5000       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5001     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5002       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5003       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5004     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5005       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5006       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5007     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5008       .type = ARM_CP_ALIAS,
5009       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5010       .access = PL3_RW,
5011       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5012     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5013       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5014       .access = PL3_RW, .writefn = vbar_write,
5015       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5016       .resetvalue = 0 },
5017     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5018       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5019       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5020       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5021     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5022       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5023       .access = PL3_RW, .resetvalue = 0,
5024       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5025     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5026       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5027       .access = PL3_RW, .type = ARM_CP_CONST,
5028       .resetvalue = 0 },
5029     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5030       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5031       .access = PL3_RW, .type = ARM_CP_CONST,
5032       .resetvalue = 0 },
5033     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5034       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5035       .access = PL3_RW, .type = ARM_CP_CONST,
5036       .resetvalue = 0 },
5037     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5038       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5039       .access = PL3_W, .type = ARM_CP_NO_RAW,
5040       .writefn = tlbi_aa64_alle3is_write },
5041     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5042       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5043       .access = PL3_W, .type = ARM_CP_NO_RAW,
5044       .writefn = tlbi_aa64_vae3is_write },
5045     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5046       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5047       .access = PL3_W, .type = ARM_CP_NO_RAW,
5048       .writefn = tlbi_aa64_vae3is_write },
5049     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5050       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5051       .access = PL3_W, .type = ARM_CP_NO_RAW,
5052       .writefn = tlbi_aa64_alle3_write },
5053     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5054       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5055       .access = PL3_W, .type = ARM_CP_NO_RAW,
5056       .writefn = tlbi_aa64_vae3_write },
5057     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5058       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5059       .access = PL3_W, .type = ARM_CP_NO_RAW,
5060       .writefn = tlbi_aa64_vae3_write },
5061     REGINFO_SENTINEL
5062 };
5063
5064 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5065                                      bool isread)
5066 {
5067     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
5068      * but the AArch32 CTR has its own reginfo struct)
5069      */
5070     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5071         return CP_ACCESS_TRAP;
5072     }
5073     return CP_ACCESS_OK;
5074 }
5075
5076 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5077                         uint64_t value)
5078 {
5079     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5080      * read via a bit in OSLSR_EL1.
5081      */
5082     int oslock;
5083
5084     if (ri->state == ARM_CP_STATE_AA32) {
5085         oslock = (value == 0xC5ACCE55);
5086     } else {
5087         oslock = value & 1;
5088     }
5089
5090     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5091 }
5092
5093 static const ARMCPRegInfo debug_cp_reginfo[] = {
5094     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5095      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5096      * unlike DBGDRAR it is never accessible from EL0.
5097      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5098      * accessor.
5099      */
5100     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5101       .access = PL0_R, .accessfn = access_tdra,
5102       .type = ARM_CP_CONST, .resetvalue = 0 },
5103     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5104       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5105       .access = PL1_R, .accessfn = access_tdra,
5106       .type = ARM_CP_CONST, .resetvalue = 0 },
5107     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5108       .access = PL0_R, .accessfn = access_tdra,
5109       .type = ARM_CP_CONST, .resetvalue = 0 },
5110     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5111     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5112       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5113       .access = PL1_RW, .accessfn = access_tda,
5114       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5115       .resetvalue = 0 },
5116     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
5117      * We don't implement the configurable EL0 access.
5118      */
5119     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
5120       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5121       .type = ARM_CP_ALIAS,
5122       .access = PL1_R, .accessfn = access_tda,
5123       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
5124     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
5125       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
5126       .access = PL1_W, .type = ARM_CP_NO_RAW,
5127       .accessfn = access_tdosa,
5128       .writefn = oslar_write },
5129     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
5130       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
5131       .access = PL1_R, .resetvalue = 10,
5132       .accessfn = access_tdosa,
5133       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
5134     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
5135     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
5136       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
5137       .access = PL1_RW, .accessfn = access_tdosa,
5138       .type = ARM_CP_NOP },
5139     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
5140      * implement vector catch debug events yet.
5141      */
5142     { .name = "DBGVCR",
5143       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5144       .access = PL1_RW, .accessfn = access_tda,
5145       .type = ARM_CP_NOP },
5146     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
5147      * to save and restore a 32-bit guest's DBGVCR)
5148      */
5149     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
5150       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
5151       .access = PL2_RW, .accessfn = access_tda,
5152       .type = ARM_CP_NOP },
5153     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
5154      * Channel but Linux may try to access this register. The 32-bit
5155      * alias is DBGDCCINT.
5156      */
5157     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
5158       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5159       .access = PL1_RW, .accessfn = access_tda,
5160       .type = ARM_CP_NOP },
5161     REGINFO_SENTINEL
5162 };
5163
5164 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
5165     /* 64 bit access versions of the (dummy) debug registers */
5166     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
5167       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5168     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
5169       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5170     REGINFO_SENTINEL
5171 };
5172
5173 /* Return the exception level to which exceptions should be taken
5174  * via SVEAccessTrap.  If an exception should be routed through
5175  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
5176  * take care of raising that exception.
5177  * C.f. the ARM pseudocode function CheckSVEEnabled.
5178  */
5179 int sve_exception_el(CPUARMState *env, int el)
5180 {
5181 #ifndef CONFIG_USER_ONLY
5182     if (el <= 1) {
5183         bool disabled = false;
5184
5185         /* The CPACR.ZEN controls traps to EL1:
5186          * 0, 2 : trap EL0 and EL1 accesses
5187          * 1    : trap only EL0 accesses
5188          * 3    : trap no accesses
5189          */
5190         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
5191             disabled = true;
5192         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
5193             disabled = el == 0;
5194         }
5195         if (disabled) {
5196             /* route_to_el2 */
5197             return (arm_feature(env, ARM_FEATURE_EL2)
5198                     && (arm_hcr_el2_eff(env) & HCR_TGE) ? 2 : 1);
5199         }
5200
5201         /* Check CPACR.FPEN.  */
5202         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
5203             disabled = true;
5204         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
5205             disabled = el == 0;
5206         }
5207         if (disabled) {
5208             return 0;
5209         }
5210     }
5211
5212     /* CPTR_EL2.  Since TZ and TFP are positive,
5213      * they will be zero when EL2 is not present.
5214      */
5215     if (el <= 2 && !arm_is_secure_below_el3(env)) {
5216         if (env->cp15.cptr_el[2] & CPTR_TZ) {
5217             return 2;
5218         }
5219         if (env->cp15.cptr_el[2] & CPTR_TFP) {
5220             return 0;
5221         }
5222     }
5223
5224     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
5225     if (arm_feature(env, ARM_FEATURE_EL3)
5226         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
5227         return 3;
5228     }
5229 #endif
5230     return 0;
5231 }
5232
5233 /*
5234  * Given that SVE is enabled, return the vector length for EL.
5235  */
5236 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
5237 {
5238     ARMCPU *cpu = arm_env_get_cpu(env);
5239     uint32_t zcr_len = cpu->sve_max_vq - 1;
5240
5241     if (el <= 1) {
5242         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
5243     }
5244     if (el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
5245         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
5246     }
5247     if (el < 3 && arm_feature(env, ARM_FEATURE_EL3)) {
5248         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
5249     }
5250     return zcr_len;
5251 }
5252
5253 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5254                       uint64_t value)
5255 {
5256     int cur_el = arm_current_el(env);
5257     int old_len = sve_zcr_len_for_el(env, cur_el);
5258     int new_len;
5259
5260     /* Bits other than [3:0] are RAZ/WI.  */
5261     raw_write(env, ri, value & 0xf);
5262
5263     /*
5264      * Because we arrived here, we know both FP and SVE are enabled;
5265      * otherwise we would have trapped access to the ZCR_ELn register.
5266      */
5267     new_len = sve_zcr_len_for_el(env, cur_el);
5268     if (new_len < old_len) {
5269         aarch64_sve_narrow_vq(env, new_len + 1);
5270     }
5271 }
5272
5273 static const ARMCPRegInfo zcr_el1_reginfo = {
5274     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
5275     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
5276     .access = PL1_RW, .type = ARM_CP_SVE,
5277     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
5278     .writefn = zcr_write, .raw_writefn = raw_write
5279 };
5280
5281 static const ARMCPRegInfo zcr_el2_reginfo = {
5282     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5283     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5284     .access = PL2_RW, .type = ARM_CP_SVE,
5285     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
5286     .writefn = zcr_write, .raw_writefn = raw_write
5287 };
5288
5289 static const ARMCPRegInfo zcr_no_el2_reginfo = {
5290     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5291     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5292     .access = PL2_RW, .type = ARM_CP_SVE,
5293     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
5294 };
5295
5296 static const ARMCPRegInfo zcr_el3_reginfo = {
5297     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
5298     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
5299     .access = PL3_RW, .type = ARM_CP_SVE,
5300     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
5301     .writefn = zcr_write, .raw_writefn = raw_write
5302 };
5303
5304 void hw_watchpoint_update(ARMCPU *cpu, int n)
5305 {
5306     CPUARMState *env = &cpu->env;
5307     vaddr len = 0;
5308     vaddr wvr = env->cp15.dbgwvr[n];
5309     uint64_t wcr = env->cp15.dbgwcr[n];
5310     int mask;
5311     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
5312
5313     if (env->cpu_watchpoint[n]) {
5314         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
5315         env->cpu_watchpoint[n] = NULL;
5316     }
5317
5318     if (!extract64(wcr, 0, 1)) {
5319         /* E bit clear : watchpoint disabled */
5320         return;
5321     }
5322
5323     switch (extract64(wcr, 3, 2)) {
5324     case 0:
5325         /* LSC 00 is reserved and must behave as if the wp is disabled */
5326         return;
5327     case 1:
5328         flags |= BP_MEM_READ;
5329         break;
5330     case 2:
5331         flags |= BP_MEM_WRITE;
5332         break;
5333     case 3:
5334         flags |= BP_MEM_ACCESS;
5335         break;
5336     }
5337
5338     /* Attempts to use both MASK and BAS fields simultaneously are
5339      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
5340      * thus generating a watchpoint for every byte in the masked region.
5341      */
5342     mask = extract64(wcr, 24, 4);
5343     if (mask == 1 || mask == 2) {
5344         /* Reserved values of MASK; we must act as if the mask value was
5345          * some non-reserved value, or as if the watchpoint were disabled.
5346          * We choose the latter.
5347          */
5348         return;
5349     } else if (mask) {
5350         /* Watchpoint covers an aligned area up to 2GB in size */
5351         len = 1ULL << mask;
5352         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
5353          * whether the watchpoint fires when the unmasked bits match; we opt
5354          * to generate the exceptions.
5355          */
5356         wvr &= ~(len - 1);
5357     } else {
5358         /* Watchpoint covers bytes defined by the byte address select bits */
5359         int bas = extract64(wcr, 5, 8);
5360         int basstart;
5361
5362         if (bas == 0) {
5363             /* This must act as if the watchpoint is disabled */
5364             return;
5365         }
5366
5367         if (extract64(wvr, 2, 1)) {
5368             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
5369              * ignored, and BAS[3:0] define which bytes to watch.
5370              */
5371             bas &= 0xf;
5372         }
5373         /* The BAS bits are supposed to be programmed to indicate a contiguous
5374          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
5375          * we fire for each byte in the word/doubleword addressed by the WVR.
5376          * We choose to ignore any non-zero bits after the first range of 1s.
5377          */
5378         basstart = ctz32(bas);
5379         len = cto32(bas >> basstart);
5380         wvr += basstart;
5381     }
5382
5383     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
5384                           &env->cpu_watchpoint[n]);
5385 }
5386
5387 void hw_watchpoint_update_all(ARMCPU *cpu)
5388 {
5389     int i;
5390     CPUARMState *env = &cpu->env;
5391
5392     /* Completely clear out existing QEMU watchpoints and our array, to
5393      * avoid possible stale entries following migration load.
5394      */
5395     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
5396     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
5397
5398     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
5399         hw_watchpoint_update(cpu, i);
5400     }
5401 }
5402
5403 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5404                          uint64_t value)
5405 {
5406     ARMCPU *cpu = arm_env_get_cpu(env);
5407     int i = ri->crm;
5408
5409     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
5410      * register reads and behaves as if values written are sign extended.
5411      * Bits [1:0] are RES0.
5412      */
5413     value = sextract64(value, 0, 49) & ~3ULL;
5414
5415     raw_write(env, ri, value);
5416     hw_watchpoint_update(cpu, i);
5417 }
5418
5419 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5420                          uint64_t value)
5421 {
5422     ARMCPU *cpu = arm_env_get_cpu(env);
5423     int i = ri->crm;
5424
5425     raw_write(env, ri, value);
5426     hw_watchpoint_update(cpu, i);
5427 }
5428
5429 void hw_breakpoint_update(ARMCPU *cpu, int n)
5430 {
5431     CPUARMState *env = &cpu->env;
5432     uint64_t bvr = env->cp15.dbgbvr[n];
5433     uint64_t bcr = env->cp15.dbgbcr[n];
5434     vaddr addr;
5435     int bt;
5436     int flags = BP_CPU;
5437
5438     if (env->cpu_breakpoint[n]) {
5439         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
5440         env->cpu_breakpoint[n] = NULL;
5441     }
5442
5443     if (!extract64(bcr, 0, 1)) {
5444         /* E bit clear : watchpoint disabled */
5445         return;
5446     }
5447
5448     bt = extract64(bcr, 20, 4);
5449
5450     switch (bt) {
5451     case 4: /* unlinked address mismatch (reserved if AArch64) */
5452     case 5: /* linked address mismatch (reserved if AArch64) */
5453         qemu_log_mask(LOG_UNIMP,
5454                       "arm: address mismatch breakpoint types not implemented\n");
5455         return;
5456     case 0: /* unlinked address match */
5457     case 1: /* linked address match */
5458     {
5459         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
5460          * we behave as if the register was sign extended. Bits [1:0] are
5461          * RES0. The BAS field is used to allow setting breakpoints on 16
5462          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
5463          * a bp will fire if the addresses covered by the bp and the addresses
5464          * covered by the insn overlap but the insn doesn't start at the
5465          * start of the bp address range. We choose to require the insn and
5466          * the bp to have the same address. The constraints on writing to
5467          * BAS enforced in dbgbcr_write mean we have only four cases:
5468          *  0b0000  => no breakpoint
5469          *  0b0011  => breakpoint on addr
5470          *  0b1100  => breakpoint on addr + 2
5471          *  0b1111  => breakpoint on addr
5472          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
5473          */
5474         int bas = extract64(bcr, 5, 4);
5475         addr = sextract64(bvr, 0, 49) & ~3ULL;
5476         if (bas == 0) {
5477             return;
5478         }
5479         if (bas == 0xc) {
5480             addr += 2;
5481         }
5482         break;
5483     }
5484     case 2: /* unlinked context ID match */
5485     case 8: /* unlinked VMID match (reserved if no EL2) */
5486     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
5487         qemu_log_mask(LOG_UNIMP,
5488                       "arm: unlinked context breakpoint types not implemented\n");
5489         return;
5490     case 9: /* linked VMID match (reserved if no EL2) */
5491     case 11: /* linked context ID and VMID match (reserved if no EL2) */
5492     case 3: /* linked context ID match */
5493     default:
5494         /* We must generate no events for Linked context matches (unless
5495          * they are linked to by some other bp/wp, which is handled in
5496          * updates for the linking bp/wp). We choose to also generate no events
5497          * for reserved values.
5498          */
5499         return;
5500     }
5501
5502     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
5503 }
5504
5505 void hw_breakpoint_update_all(ARMCPU *cpu)
5506 {
5507     int i;
5508     CPUARMState *env = &cpu->env;
5509
5510     /* Completely clear out existing QEMU breakpoints and our array, to
5511      * avoid possible stale entries following migration load.
5512      */
5513     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
5514     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
5515
5516     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
5517         hw_breakpoint_update(cpu, i);
5518     }
5519 }
5520
5521 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5522                          uint64_t value)
5523 {
5524     ARMCPU *cpu = arm_env_get_cpu(env);
5525     int i = ri->crm;
5526
5527     raw_write(env, ri, value);
5528     hw_breakpoint_update(cpu, i);
5529 }
5530
5531 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5532                          uint64_t value)
5533 {
5534     ARMCPU *cpu = arm_env_get_cpu(env);
5535     int i = ri->crm;
5536
5537     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
5538      * copy of BAS[0].
5539      */
5540     value = deposit64(value, 6, 1, extract64(value, 5, 1));
5541     value = deposit64(value, 8, 1, extract64(value, 7, 1));
5542
5543     raw_write(env, ri, value);
5544     hw_breakpoint_update(cpu, i);
5545 }
5546
5547 static void define_debug_regs(ARMCPU *cpu)
5548 {
5549     /* Define v7 and v8 architectural debug registers.
5550      * These are just dummy implementations for now.
5551      */
5552     int i;
5553     int wrps, brps, ctx_cmps;
5554     ARMCPRegInfo dbgdidr = {
5555         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
5556         .access = PL0_R, .accessfn = access_tda,
5557         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
5558     };
5559
5560     /* Note that all these register fields hold "number of Xs minus 1". */
5561     brps = extract32(cpu->dbgdidr, 24, 4);
5562     wrps = extract32(cpu->dbgdidr, 28, 4);
5563     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
5564
5565     assert(ctx_cmps <= brps);
5566
5567     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
5568      * of the debug registers such as number of breakpoints;
5569      * check that if they both exist then they agree.
5570      */
5571     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
5572         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
5573         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
5574         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
5575     }
5576
5577     define_one_arm_cp_reg(cpu, &dbgdidr);
5578     define_arm_cp_regs(cpu, debug_cp_reginfo);
5579
5580     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
5581         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
5582     }
5583
5584     for (i = 0; i < brps + 1; i++) {
5585         ARMCPRegInfo dbgregs[] = {
5586             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
5587               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
5588               .access = PL1_RW, .accessfn = access_tda,
5589               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
5590               .writefn = dbgbvr_write, .raw_writefn = raw_write
5591             },
5592             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
5593               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
5594               .access = PL1_RW, .accessfn = access_tda,
5595               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
5596               .writefn = dbgbcr_write, .raw_writefn = raw_write
5597             },
5598             REGINFO_SENTINEL
5599         };
5600         define_arm_cp_regs(cpu, dbgregs);
5601     }
5602
5603     for (i = 0; i < wrps + 1; i++) {
5604         ARMCPRegInfo dbgregs[] = {
5605             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
5606               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
5607               .access = PL1_RW, .accessfn = access_tda,
5608               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
5609               .writefn = dbgwvr_write, .raw_writefn = raw_write
5610             },
5611             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
5612               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
5613               .access = PL1_RW, .accessfn = access_tda,
5614               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
5615               .writefn = dbgwcr_write, .raw_writefn = raw_write
5616             },
5617             REGINFO_SENTINEL
5618         };
5619         define_arm_cp_regs(cpu, dbgregs);
5620     }
5621 }
5622
5623 /* We don't know until after realize whether there's a GICv3
5624  * attached, and that is what registers the gicv3 sysregs.
5625  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
5626  * at runtime.
5627  */
5628 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
5629 {
5630     ARMCPU *cpu = arm_env_get_cpu(env);
5631     uint64_t pfr1 = cpu->id_pfr1;
5632
5633     if (env->gicv3state) {
5634         pfr1 |= 1 << 28;
5635     }
5636     return pfr1;
5637 }
5638
5639 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
5640 {
5641     ARMCPU *cpu = arm_env_get_cpu(env);
5642     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
5643
5644     if (env->gicv3state) {
5645         pfr0 |= 1 << 24;
5646     }
5647     return pfr0;
5648 }
5649
5650 /* Shared logic between LORID and the rest of the LOR* registers.
5651  * Secure state has already been delt with.
5652  */
5653 static CPAccessResult access_lor_ns(CPUARMState *env)
5654 {
5655     int el = arm_current_el(env);
5656
5657     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
5658         return CP_ACCESS_TRAP_EL2;
5659     }
5660     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
5661         return CP_ACCESS_TRAP_EL3;
5662     }
5663     return CP_ACCESS_OK;
5664 }
5665
5666 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
5667                                    bool isread)
5668 {
5669     if (arm_is_secure_below_el3(env)) {
5670         /* Access ok in secure mode.  */
5671         return CP_ACCESS_OK;
5672     }
5673     return access_lor_ns(env);
5674 }
5675
5676 static CPAccessResult access_lor_other(CPUARMState *env,
5677                                        const ARMCPRegInfo *ri, bool isread)
5678 {
5679     if (arm_is_secure_below_el3(env)) {
5680         /* Access denied in secure mode.  */
5681         return CP_ACCESS_TRAP;
5682     }
5683     return access_lor_ns(env);
5684 }
5685
5686 #ifdef TARGET_AARCH64
5687 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
5688                                    bool isread)
5689 {
5690     int el = arm_current_el(env);
5691
5692     if (el < 2 &&
5693         arm_feature(env, ARM_FEATURE_EL2) &&
5694         !(arm_hcr_el2_eff(env) & HCR_APK)) {
5695         return CP_ACCESS_TRAP_EL2;
5696     }
5697     if (el < 3 &&
5698         arm_feature(env, ARM_FEATURE_EL3) &&
5699         !(env->cp15.scr_el3 & SCR_APK)) {
5700         return CP_ACCESS_TRAP_EL3;
5701     }
5702     return CP_ACCESS_OK;
5703 }
5704
5705 static const ARMCPRegInfo pauth_reginfo[] = {
5706     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5707       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
5708       .access = PL1_RW, .accessfn = access_pauth,
5709       .fieldoffset = offsetof(CPUARMState, apda_key.lo) },
5710     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5711       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
5712       .access = PL1_RW, .accessfn = access_pauth,
5713       .fieldoffset = offsetof(CPUARMState, apda_key.hi) },
5714     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5715       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
5716       .access = PL1_RW, .accessfn = access_pauth,
5717       .fieldoffset = offsetof(CPUARMState, apdb_key.lo) },
5718     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5719       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
5720       .access = PL1_RW, .accessfn = access_pauth,
5721       .fieldoffset = offsetof(CPUARMState, apdb_key.hi) },
5722     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5723       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
5724       .access = PL1_RW, .accessfn = access_pauth,
5725       .fieldoffset = offsetof(CPUARMState, apga_key.lo) },
5726     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5727       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
5728       .access = PL1_RW, .accessfn = access_pauth,
5729       .fieldoffset = offsetof(CPUARMState, apga_key.hi) },
5730     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5731       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
5732       .access = PL1_RW, .accessfn = access_pauth,
5733       .fieldoffset = offsetof(CPUARMState, apia_key.lo) },
5734     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5735       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
5736       .access = PL1_RW, .accessfn = access_pauth,
5737       .fieldoffset = offsetof(CPUARMState, apia_key.hi) },
5738     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5739       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
5740       .access = PL1_RW, .accessfn = access_pauth,
5741       .fieldoffset = offsetof(CPUARMState, apib_key.lo) },
5742     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5743       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
5744       .access = PL1_RW, .accessfn = access_pauth,
5745       .fieldoffset = offsetof(CPUARMState, apib_key.hi) },
5746     REGINFO_SENTINEL
5747 };
5748 #endif
5749
5750 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
5751                                      bool isread)
5752 {
5753     int el = arm_current_el(env);
5754
5755     if (el == 0) {
5756         uint64_t sctlr = arm_sctlr(env, el);
5757         if (!(sctlr & SCTLR_EnRCTX)) {
5758             return CP_ACCESS_TRAP;
5759         }
5760     } else if (el == 1) {
5761         uint64_t hcr = arm_hcr_el2_eff(env);
5762         if (hcr & HCR_NV) {
5763             return CP_ACCESS_TRAP_EL2;
5764         }
5765     }
5766     return CP_ACCESS_OK;
5767 }
5768
5769 static const ARMCPRegInfo predinv_reginfo[] = {
5770     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
5771       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
5772       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5773     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
5774       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
5775       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5776     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
5777       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
5778       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5779     /*
5780      * Note the AArch32 opcodes have a different OPC1.
5781      */
5782     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
5783       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
5784       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5785     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
5786       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
5787       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5788     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
5789       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
5790       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5791     REGINFO_SENTINEL
5792 };
5793
5794 void register_cp_regs_for_features(ARMCPU *cpu)
5795 {
5796     /* Register all the coprocessor registers based on feature bits */
5797     CPUARMState *env = &cpu->env;
5798     if (arm_feature(env, ARM_FEATURE_M)) {
5799         /* M profile has no coprocessor registers */
5800         return;
5801     }
5802
5803     define_arm_cp_regs(cpu, cp_reginfo);
5804     if (!arm_feature(env, ARM_FEATURE_V8)) {
5805         /* Must go early as it is full of wildcards that may be
5806          * overridden by later definitions.
5807          */
5808         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
5809     }
5810
5811     if (arm_feature(env, ARM_FEATURE_V6)) {
5812         /* The ID registers all have impdef reset values */
5813         ARMCPRegInfo v6_idregs[] = {
5814             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
5815               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5816               .access = PL1_R, .type = ARM_CP_CONST,
5817               .resetvalue = cpu->id_pfr0 },
5818             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
5819              * the value of the GIC field until after we define these regs.
5820              */
5821             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
5822               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
5823               .access = PL1_R, .type = ARM_CP_NO_RAW,
5824               .readfn = id_pfr1_read,
5825               .writefn = arm_cp_write_ignore },
5826             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
5827               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
5828               .access = PL1_R, .type = ARM_CP_CONST,
5829               .resetvalue = cpu->id_dfr0 },
5830             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
5831               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
5832               .access = PL1_R, .type = ARM_CP_CONST,
5833               .resetvalue = cpu->id_afr0 },
5834             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
5835               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
5836               .access = PL1_R, .type = ARM_CP_CONST,
5837               .resetvalue = cpu->id_mmfr0 },
5838             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
5839               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
5840               .access = PL1_R, .type = ARM_CP_CONST,
5841               .resetvalue = cpu->id_mmfr1 },
5842             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
5843               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
5844               .access = PL1_R, .type = ARM_CP_CONST,
5845               .resetvalue = cpu->id_mmfr2 },
5846             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
5847               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
5848               .access = PL1_R, .type = ARM_CP_CONST,
5849               .resetvalue = cpu->id_mmfr3 },
5850             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
5851               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5852               .access = PL1_R, .type = ARM_CP_CONST,
5853               .resetvalue = cpu->isar.id_isar0 },
5854             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
5855               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
5856               .access = PL1_R, .type = ARM_CP_CONST,
5857               .resetvalue = cpu->isar.id_isar1 },
5858             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
5859               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5860               .access = PL1_R, .type = ARM_CP_CONST,
5861               .resetvalue = cpu->isar.id_isar2 },
5862             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
5863               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
5864               .access = PL1_R, .type = ARM_CP_CONST,
5865               .resetvalue = cpu->isar.id_isar3 },
5866             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
5867               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
5868               .access = PL1_R, .type = ARM_CP_CONST,
5869               .resetvalue = cpu->isar.id_isar4 },
5870             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
5871               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
5872               .access = PL1_R, .type = ARM_CP_CONST,
5873               .resetvalue = cpu->isar.id_isar5 },
5874             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
5875               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
5876               .access = PL1_R, .type = ARM_CP_CONST,
5877               .resetvalue = cpu->id_mmfr4 },
5878             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
5879               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
5880               .access = PL1_R, .type = ARM_CP_CONST,
5881               .resetvalue = cpu->isar.id_isar6 },
5882             REGINFO_SENTINEL
5883         };
5884         define_arm_cp_regs(cpu, v6_idregs);
5885         define_arm_cp_regs(cpu, v6_cp_reginfo);
5886     } else {
5887         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
5888     }
5889     if (arm_feature(env, ARM_FEATURE_V6K)) {
5890         define_arm_cp_regs(cpu, v6k_cp_reginfo);
5891     }
5892     if (arm_feature(env, ARM_FEATURE_V7MP) &&
5893         !arm_feature(env, ARM_FEATURE_PMSA)) {
5894         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
5895     }
5896     if (arm_feature(env, ARM_FEATURE_V7VE)) {
5897         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
5898     }
5899     if (arm_feature(env, ARM_FEATURE_V7)) {
5900         /* v7 performance monitor control register: same implementor
5901          * field as main ID register, and we implement four counters in
5902          * addition to the cycle count register.
5903          */
5904         unsigned int i, pmcrn = 4;
5905         ARMCPRegInfo pmcr = {
5906             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
5907             .access = PL0_RW,
5908             .type = ARM_CP_IO | ARM_CP_ALIAS,
5909             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
5910             .accessfn = pmreg_access, .writefn = pmcr_write,
5911             .raw_writefn = raw_write,
5912         };
5913         ARMCPRegInfo pmcr64 = {
5914             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
5915             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
5916             .access = PL0_RW, .accessfn = pmreg_access,
5917             .type = ARM_CP_IO,
5918             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
5919             .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT),
5920             .writefn = pmcr_write, .raw_writefn = raw_write,
5921         };
5922         define_one_arm_cp_reg(cpu, &pmcr);
5923         define_one_arm_cp_reg(cpu, &pmcr64);
5924         for (i = 0; i < pmcrn; i++) {
5925             char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
5926             char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
5927             char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
5928             char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
5929             ARMCPRegInfo pmev_regs[] = {
5930                 { .name = pmevcntr_name, .cp = 15, .crn = 14,
5931                   .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
5932                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
5933                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
5934                   .accessfn = pmreg_access },
5935                 { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
5936                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
5937                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
5938                   .type = ARM_CP_IO,
5939                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
5940                   .raw_readfn = pmevcntr_rawread,
5941                   .raw_writefn = pmevcntr_rawwrite },
5942                 { .name = pmevtyper_name, .cp = 15, .crn = 14,
5943                   .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
5944                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
5945                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
5946                   .accessfn = pmreg_access },
5947                 { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
5948                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
5949                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
5950                   .type = ARM_CP_IO,
5951                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
5952                   .raw_writefn = pmevtyper_rawwrite },
5953                 REGINFO_SENTINEL
5954             };
5955             define_arm_cp_regs(cpu, pmev_regs);
5956             g_free(pmevcntr_name);
5957             g_free(pmevcntr_el0_name);
5958             g_free(pmevtyper_name);
5959             g_free(pmevtyper_el0_name);
5960         }
5961         ARMCPRegInfo clidr = {
5962             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
5963             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
5964             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
5965         };
5966         define_one_arm_cp_reg(cpu, &clidr);
5967         define_arm_cp_regs(cpu, v7_cp_reginfo);
5968         define_debug_regs(cpu);
5969     } else {
5970         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
5971     }
5972     if (FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) >= 4 &&
5973             FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) != 0xf) {
5974         ARMCPRegInfo v81_pmu_regs[] = {
5975             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
5976               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
5977               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5978               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
5979             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
5980               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
5981               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5982               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
5983             REGINFO_SENTINEL
5984         };
5985         define_arm_cp_regs(cpu, v81_pmu_regs);
5986     }
5987     if (arm_feature(env, ARM_FEATURE_V8)) {
5988         /* AArch64 ID registers, which all have impdef reset values.
5989          * Note that within the ID register ranges the unused slots
5990          * must all RAZ, not UNDEF; future architecture versions may
5991          * define new registers here.
5992          */
5993         ARMCPRegInfo v8_idregs[] = {
5994             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
5995              * know the right value for the GIC field until after we
5996              * define these regs.
5997              */
5998             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
5999               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
6000               .access = PL1_R, .type = ARM_CP_NO_RAW,
6001               .readfn = id_aa64pfr0_read,
6002               .writefn = arm_cp_write_ignore },
6003             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
6004               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
6005               .access = PL1_R, .type = ARM_CP_CONST,
6006               .resetvalue = cpu->isar.id_aa64pfr1},
6007             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6008               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
6009               .access = PL1_R, .type = ARM_CP_CONST,
6010               .resetvalue = 0 },
6011             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6012               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
6013               .access = PL1_R, .type = ARM_CP_CONST,
6014               .resetvalue = 0 },
6015             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
6016               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
6017               .access = PL1_R, .type = ARM_CP_CONST,
6018               /* At present, only SVEver == 0 is defined anyway.  */
6019               .resetvalue = 0 },
6020             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6021               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
6022               .access = PL1_R, .type = ARM_CP_CONST,
6023               .resetvalue = 0 },
6024             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6025               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
6026               .access = PL1_R, .type = ARM_CP_CONST,
6027               .resetvalue = 0 },
6028             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6029               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
6030               .access = PL1_R, .type = ARM_CP_CONST,
6031               .resetvalue = 0 },
6032             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
6033               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
6034               .access = PL1_R, .type = ARM_CP_CONST,
6035               .resetvalue = cpu->id_aa64dfr0 },
6036             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
6037               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
6038               .access = PL1_R, .type = ARM_CP_CONST,
6039               .resetvalue = cpu->id_aa64dfr1 },
6040             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6041               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
6042               .access = PL1_R, .type = ARM_CP_CONST,
6043               .resetvalue = 0 },
6044             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6045               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
6046               .access = PL1_R, .type = ARM_CP_CONST,
6047               .resetvalue = 0 },
6048             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
6049               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
6050               .access = PL1_R, .type = ARM_CP_CONST,
6051               .resetvalue = cpu->id_aa64afr0 },
6052             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
6053               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
6054               .access = PL1_R, .type = ARM_CP_CONST,
6055               .resetvalue = cpu->id_aa64afr1 },
6056             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6057               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
6058               .access = PL1_R, .type = ARM_CP_CONST,
6059               .resetvalue = 0 },
6060             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6061               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
6062               .access = PL1_R, .type = ARM_CP_CONST,
6063               .resetvalue = 0 },
6064             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
6065               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
6066               .access = PL1_R, .type = ARM_CP_CONST,
6067               .resetvalue = cpu->isar.id_aa64isar0 },
6068             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
6069               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
6070               .access = PL1_R, .type = ARM_CP_CONST,
6071               .resetvalue = cpu->isar.id_aa64isar1 },
6072             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6073               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
6074               .access = PL1_R, .type = ARM_CP_CONST,
6075               .resetvalue = 0 },
6076             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6077               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
6078               .access = PL1_R, .type = ARM_CP_CONST,
6079               .resetvalue = 0 },
6080             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6081               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
6082               .access = PL1_R, .type = ARM_CP_CONST,
6083               .resetvalue = 0 },
6084             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6085               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
6086               .access = PL1_R, .type = ARM_CP_CONST,
6087               .resetvalue = 0 },
6088             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6089               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
6090               .access = PL1_R, .type = ARM_CP_CONST,
6091               .resetvalue = 0 },
6092             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6093               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
6094               .access = PL1_R, .type = ARM_CP_CONST,
6095               .resetvalue = 0 },
6096             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
6097               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6098               .access = PL1_R, .type = ARM_CP_CONST,
6099               .resetvalue = cpu->isar.id_aa64mmfr0 },
6100             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
6101               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
6102               .access = PL1_R, .type = ARM_CP_CONST,
6103               .resetvalue = cpu->isar.id_aa64mmfr1 },
6104             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6105               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
6106               .access = PL1_R, .type = ARM_CP_CONST,
6107               .resetvalue = 0 },
6108             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6109               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
6110               .access = PL1_R, .type = ARM_CP_CONST,
6111               .resetvalue = 0 },
6112             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6113               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
6114               .access = PL1_R, .type = ARM_CP_CONST,
6115               .resetvalue = 0 },
6116             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6117               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
6118               .access = PL1_R, .type = ARM_CP_CONST,
6119               .resetvalue = 0 },
6120             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6121               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
6122               .access = PL1_R, .type = ARM_CP_CONST,
6123               .resetvalue = 0 },
6124             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6125               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
6126               .access = PL1_R, .type = ARM_CP_CONST,
6127               .resetvalue = 0 },
6128             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
6129               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
6130               .access = PL1_R, .type = ARM_CP_CONST,
6131               .resetvalue = cpu->isar.mvfr0 },
6132             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
6133               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
6134               .access = PL1_R, .type = ARM_CP_CONST,
6135               .resetvalue = cpu->isar.mvfr1 },
6136             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
6137               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
6138               .access = PL1_R, .type = ARM_CP_CONST,
6139               .resetvalue = cpu->isar.mvfr2 },
6140             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6141               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
6142               .access = PL1_R, .type = ARM_CP_CONST,
6143               .resetvalue = 0 },
6144             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6145               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
6146               .access = PL1_R, .type = ARM_CP_CONST,
6147               .resetvalue = 0 },
6148             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6149               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
6150               .access = PL1_R, .type = ARM_CP_CONST,
6151               .resetvalue = 0 },
6152             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6153               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
6154               .access = PL1_R, .type = ARM_CP_CONST,
6155               .resetvalue = 0 },
6156             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6157               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
6158               .access = PL1_R, .type = ARM_CP_CONST,
6159               .resetvalue = 0 },
6160             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
6161               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
6162               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6163               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
6164             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
6165               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
6166               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6167               .resetvalue = cpu->pmceid0 },
6168             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
6169               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
6170               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6171               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
6172             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
6173               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
6174               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6175               .resetvalue = cpu->pmceid1 },
6176             REGINFO_SENTINEL
6177         };
6178 #ifdef CONFIG_USER_ONLY
6179         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
6180             { .name = "ID_AA64PFR0_EL1",
6181               .exported_bits = 0x000f000f00ff0000,
6182               .fixed_bits    = 0x0000000000000011 },
6183             { .name = "ID_AA64PFR1_EL1",
6184               .exported_bits = 0x00000000000000f0 },
6185             { .name = "ID_AA64PFR*_EL1_RESERVED",
6186               .is_glob = true                     },
6187             { .name = "ID_AA64ZFR0_EL1"           },
6188             { .name = "ID_AA64MMFR0_EL1",
6189               .fixed_bits    = 0x00000000ff000000 },
6190             { .name = "ID_AA64MMFR1_EL1"          },
6191             { .name = "ID_AA64MMFR*_EL1_RESERVED",
6192               .is_glob = true                     },
6193             { .name = "ID_AA64DFR0_EL1",
6194               .fixed_bits    = 0x0000000000000006 },
6195             { .name = "ID_AA64DFR1_EL1"           },
6196             { .name = "ID_AA64DFR*_EL1_RESERVED",
6197               .is_glob = true                     },
6198             { .name = "ID_AA64AFR*",
6199               .is_glob = true                     },
6200             { .name = "ID_AA64ISAR0_EL1",
6201               .exported_bits = 0x00fffffff0fffff0 },
6202             { .name = "ID_AA64ISAR1_EL1",
6203               .exported_bits = 0x000000f0ffffffff },
6204             { .name = "ID_AA64ISAR*_EL1_RESERVED",
6205               .is_glob = true                     },
6206             REGUSERINFO_SENTINEL
6207         };
6208         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
6209 #endif
6210         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
6211         if (!arm_feature(env, ARM_FEATURE_EL3) &&
6212             !arm_feature(env, ARM_FEATURE_EL2)) {
6213             ARMCPRegInfo rvbar = {
6214                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
6215                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
6216                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
6217             };
6218             define_one_arm_cp_reg(cpu, &rvbar);
6219         }
6220         define_arm_cp_regs(cpu, v8_idregs);
6221         define_arm_cp_regs(cpu, v8_cp_reginfo);
6222     }
6223     if (arm_feature(env, ARM_FEATURE_EL2)) {
6224         uint64_t vmpidr_def = mpidr_read_val(env);
6225         ARMCPRegInfo vpidr_regs[] = {
6226             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
6227               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6228               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6229               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
6230               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
6231             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
6232               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6233               .access = PL2_RW, .resetvalue = cpu->midr,
6234               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6235             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
6236               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6237               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6238               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
6239               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
6240             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
6241               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6242               .access = PL2_RW,
6243               .resetvalue = vmpidr_def,
6244               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
6245             REGINFO_SENTINEL
6246         };
6247         define_arm_cp_regs(cpu, vpidr_regs);
6248         define_arm_cp_regs(cpu, el2_cp_reginfo);
6249         if (arm_feature(env, ARM_FEATURE_V8)) {
6250             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
6251         }
6252         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
6253         if (!arm_feature(env, ARM_FEATURE_EL3)) {
6254             ARMCPRegInfo rvbar = {
6255                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
6256                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
6257                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
6258             };
6259             define_one_arm_cp_reg(cpu, &rvbar);
6260         }
6261     } else {
6262         /* If EL2 is missing but higher ELs are enabled, we need to
6263          * register the no_el2 reginfos.
6264          */
6265         if (arm_feature(env, ARM_FEATURE_EL3)) {
6266             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
6267              * of MIDR_EL1 and MPIDR_EL1.
6268              */
6269             ARMCPRegInfo vpidr_regs[] = {
6270                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6271                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6272                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6273                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
6274                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6275                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6276                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6277                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6278                   .type = ARM_CP_NO_RAW,
6279                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
6280                 REGINFO_SENTINEL
6281             };
6282             define_arm_cp_regs(cpu, vpidr_regs);
6283             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
6284             if (arm_feature(env, ARM_FEATURE_V8)) {
6285                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
6286             }
6287         }
6288     }
6289     if (arm_feature(env, ARM_FEATURE_EL3)) {
6290         define_arm_cp_regs(cpu, el3_cp_reginfo);
6291         ARMCPRegInfo el3_regs[] = {
6292             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
6293               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
6294               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
6295             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
6296               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
6297               .access = PL3_RW,
6298               .raw_writefn = raw_write, .writefn = sctlr_write,
6299               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
6300               .resetvalue = cpu->reset_sctlr },
6301             REGINFO_SENTINEL
6302         };
6303
6304         define_arm_cp_regs(cpu, el3_regs);
6305     }
6306     /* The behaviour of NSACR is sufficiently various that we don't
6307      * try to describe it in a single reginfo:
6308      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
6309      *     reads as constant 0xc00 from NS EL1 and NS EL2
6310      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
6311      *  if v7 without EL3, register doesn't exist
6312      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
6313      */
6314     if (arm_feature(env, ARM_FEATURE_EL3)) {
6315         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6316             ARMCPRegInfo nsacr = {
6317                 .name = "NSACR", .type = ARM_CP_CONST,
6318                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6319                 .access = PL1_RW, .accessfn = nsacr_access,
6320                 .resetvalue = 0xc00
6321             };
6322             define_one_arm_cp_reg(cpu, &nsacr);
6323         } else {
6324             ARMCPRegInfo nsacr = {
6325                 .name = "NSACR",
6326                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6327                 .access = PL3_RW | PL1_R,
6328                 .resetvalue = 0,
6329                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
6330             };
6331             define_one_arm_cp_reg(cpu, &nsacr);
6332         }
6333     } else {
6334         if (arm_feature(env, ARM_FEATURE_V8)) {
6335             ARMCPRegInfo nsacr = {
6336                 .name = "NSACR", .type = ARM_CP_CONST,
6337                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6338                 .access = PL1_R,
6339                 .resetvalue = 0xc00
6340             };
6341             define_one_arm_cp_reg(cpu, &nsacr);
6342         }
6343     }
6344
6345     if (arm_feature(env, ARM_FEATURE_PMSA)) {
6346         if (arm_feature(env, ARM_FEATURE_V6)) {
6347             /* PMSAv6 not implemented */
6348             assert(arm_feature(env, ARM_FEATURE_V7));
6349             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6350             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
6351         } else {
6352             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
6353         }
6354     } else {
6355         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6356         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
6357         /* TTCBR2 is introduced with ARMv8.2-A32HPD.  */
6358         if (FIELD_EX32(cpu->id_mmfr4, ID_MMFR4, HPDS) != 0) {
6359             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
6360         }
6361     }
6362     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
6363         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
6364     }
6365     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
6366         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
6367     }
6368     if (arm_feature(env, ARM_FEATURE_VAPA)) {
6369         define_arm_cp_regs(cpu, vapa_cp_reginfo);
6370     }
6371     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
6372         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
6373     }
6374     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
6375         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
6376     }
6377     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
6378         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
6379     }
6380     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
6381         define_arm_cp_regs(cpu, omap_cp_reginfo);
6382     }
6383     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
6384         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
6385     }
6386     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6387         define_arm_cp_regs(cpu, xscale_cp_reginfo);
6388     }
6389     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
6390         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
6391     }
6392     if (arm_feature(env, ARM_FEATURE_LPAE)) {
6393         define_arm_cp_regs(cpu, lpae_cp_reginfo);
6394     }
6395     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
6396      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
6397      * be read-only (ie write causes UNDEF exception).
6398      */
6399     {
6400         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
6401             /* Pre-v8 MIDR space.
6402              * Note that the MIDR isn't a simple constant register because
6403              * of the TI925 behaviour where writes to another register can
6404              * cause the MIDR value to change.
6405              *
6406              * Unimplemented registers in the c15 0 0 0 space default to
6407              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
6408              * and friends override accordingly.
6409              */
6410             { .name = "MIDR",
6411               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
6412               .access = PL1_R, .resetvalue = cpu->midr,
6413               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
6414               .readfn = midr_read,
6415               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6416               .type = ARM_CP_OVERRIDE },
6417             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
6418             { .name = "DUMMY",
6419               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
6420               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6421             { .name = "DUMMY",
6422               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
6423               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6424             { .name = "DUMMY",
6425               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
6426               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6427             { .name = "DUMMY",
6428               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
6429               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6430             { .name = "DUMMY",
6431               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
6432               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6433             REGINFO_SENTINEL
6434         };
6435         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
6436             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
6437               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
6438               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
6439               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6440               .readfn = midr_read },
6441             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
6442             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6443               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6444               .access = PL1_R, .resetvalue = cpu->midr },
6445             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6446               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
6447               .access = PL1_R, .resetvalue = cpu->midr },
6448             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
6449               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
6450               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
6451             REGINFO_SENTINEL
6452         };
6453         ARMCPRegInfo id_cp_reginfo[] = {
6454             /* These are common to v8 and pre-v8 */
6455             { .name = "CTR",
6456               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
6457               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6458             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
6459               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
6460               .access = PL0_R, .accessfn = ctr_el0_access,
6461               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6462             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
6463             { .name = "TCMTR",
6464               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
6465               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6466             REGINFO_SENTINEL
6467         };
6468         /* TLBTR is specific to VMSA */
6469         ARMCPRegInfo id_tlbtr_reginfo = {
6470               .name = "TLBTR",
6471               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
6472               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
6473         };
6474         /* MPUIR is specific to PMSA V6+ */
6475         ARMCPRegInfo id_mpuir_reginfo = {
6476               .name = "MPUIR",
6477               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6478               .access = PL1_R, .type = ARM_CP_CONST,
6479               .resetvalue = cpu->pmsav7_dregion << 8
6480         };
6481         ARMCPRegInfo crn0_wi_reginfo = {
6482             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
6483             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
6484             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
6485         };
6486 #ifdef CONFIG_USER_ONLY
6487         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
6488             { .name = "MIDR_EL1",
6489               .exported_bits = 0x00000000ffffffff },
6490             { .name = "REVIDR_EL1"                },
6491             REGUSERINFO_SENTINEL
6492         };
6493         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
6494 #endif
6495         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
6496             arm_feature(env, ARM_FEATURE_STRONGARM)) {
6497             ARMCPRegInfo *r;
6498             /* Register the blanket "writes ignored" value first to cover the
6499              * whole space. Then update the specific ID registers to allow write
6500              * access, so that they ignore writes rather than causing them to
6501              * UNDEF.
6502              */
6503             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
6504             for (r = id_pre_v8_midr_cp_reginfo;
6505                  r->type != ARM_CP_SENTINEL; r++) {
6506                 r->access = PL1_RW;
6507             }
6508             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
6509                 r->access = PL1_RW;
6510             }
6511             id_mpuir_reginfo.access = PL1_RW;
6512             id_tlbtr_reginfo.access = PL1_RW;
6513         }
6514         if (arm_feature(env, ARM_FEATURE_V8)) {
6515             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
6516         } else {
6517             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
6518         }
6519         define_arm_cp_regs(cpu, id_cp_reginfo);
6520         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
6521             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
6522         } else if (arm_feature(env, ARM_FEATURE_V7)) {
6523             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
6524         }
6525     }
6526
6527     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
6528         ARMCPRegInfo mpidr_cp_reginfo[] = {
6529             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
6530               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
6531               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
6532             REGINFO_SENTINEL
6533         };
6534 #ifdef CONFIG_USER_ONLY
6535         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
6536             { .name = "MPIDR_EL1",
6537               .fixed_bits = 0x0000000080000000 },
6538             REGUSERINFO_SENTINEL
6539         };
6540         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
6541 #endif
6542         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
6543     }
6544
6545     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
6546         ARMCPRegInfo auxcr_reginfo[] = {
6547             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
6548               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
6549               .access = PL1_RW, .type = ARM_CP_CONST,
6550               .resetvalue = cpu->reset_auxcr },
6551             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
6552               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
6553               .access = PL2_RW, .type = ARM_CP_CONST,
6554               .resetvalue = 0 },
6555             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
6556               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
6557               .access = PL3_RW, .type = ARM_CP_CONST,
6558               .resetvalue = 0 },
6559             REGINFO_SENTINEL
6560         };
6561         define_arm_cp_regs(cpu, auxcr_reginfo);
6562         if (arm_feature(env, ARM_FEATURE_V8)) {
6563             /* HACTLR2 maps to ACTLR_EL2[63:32] and is not in ARMv7 */
6564             ARMCPRegInfo hactlr2_reginfo = {
6565                 .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
6566                 .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
6567                 .access = PL2_RW, .type = ARM_CP_CONST,
6568                 .resetvalue = 0
6569             };
6570             define_one_arm_cp_reg(cpu, &hactlr2_reginfo);
6571         }
6572     }
6573
6574     if (arm_feature(env, ARM_FEATURE_CBAR)) {
6575         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6576             /* 32 bit view is [31:18] 0...0 [43:32]. */
6577             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
6578                 | extract64(cpu->reset_cbar, 32, 12);
6579             ARMCPRegInfo cbar_reginfo[] = {
6580                 { .name = "CBAR",
6581                   .type = ARM_CP_CONST,
6582                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
6583                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
6584                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
6585                   .type = ARM_CP_CONST,
6586                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
6587                   .access = PL1_R, .resetvalue = cbar32 },
6588                 REGINFO_SENTINEL
6589             };
6590             /* We don't implement a r/w 64 bit CBAR currently */
6591             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
6592             define_arm_cp_regs(cpu, cbar_reginfo);
6593         } else {
6594             ARMCPRegInfo cbar = {
6595                 .name = "CBAR",
6596                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
6597                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
6598                 .fieldoffset = offsetof(CPUARMState,
6599                                         cp15.c15_config_base_address)
6600             };
6601             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
6602                 cbar.access = PL1_R;
6603                 cbar.fieldoffset = 0;
6604                 cbar.type = ARM_CP_CONST;
6605             }
6606             define_one_arm_cp_reg(cpu, &cbar);
6607         }
6608     }
6609
6610     if (arm_feature(env, ARM_FEATURE_VBAR)) {
6611         ARMCPRegInfo vbar_cp_reginfo[] = {
6612             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
6613               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
6614               .access = PL1_RW, .writefn = vbar_write,
6615               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
6616                                      offsetof(CPUARMState, cp15.vbar_ns) },
6617               .resetvalue = 0 },
6618             REGINFO_SENTINEL
6619         };
6620         define_arm_cp_regs(cpu, vbar_cp_reginfo);
6621     }
6622
6623     /* Generic registers whose values depend on the implementation */
6624     {
6625         ARMCPRegInfo sctlr = {
6626             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
6627             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6628             .access = PL1_RW,
6629             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
6630                                    offsetof(CPUARMState, cp15.sctlr_ns) },
6631             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
6632             .raw_writefn = raw_write,
6633         };
6634         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6635             /* Normally we would always end the TB on an SCTLR write, but Linux
6636              * arch/arm/mach-pxa/sleep.S expects two instructions following
6637              * an MMU enable to execute from cache.  Imitate this behaviour.
6638              */
6639             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
6640         }
6641         define_one_arm_cp_reg(cpu, &sctlr);
6642     }
6643
6644     if (cpu_isar_feature(aa64_lor, cpu)) {
6645         /*
6646          * A trivial implementation of ARMv8.1-LOR leaves all of these
6647          * registers fixed at 0, which indicates that there are zero
6648          * supported Limited Ordering regions.
6649          */
6650         static const ARMCPRegInfo lor_reginfo[] = {
6651             { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6652               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6653               .access = PL1_RW, .accessfn = access_lor_other,
6654               .type = ARM_CP_CONST, .resetvalue = 0 },
6655             { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6656               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6657               .access = PL1_RW, .accessfn = access_lor_other,
6658               .type = ARM_CP_CONST, .resetvalue = 0 },
6659             { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6660               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6661               .access = PL1_RW, .accessfn = access_lor_other,
6662               .type = ARM_CP_CONST, .resetvalue = 0 },
6663             { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6664               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6665               .access = PL1_RW, .accessfn = access_lor_other,
6666               .type = ARM_CP_CONST, .resetvalue = 0 },
6667             { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6668               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6669               .access = PL1_R, .accessfn = access_lorid,
6670               .type = ARM_CP_CONST, .resetvalue = 0 },
6671             REGINFO_SENTINEL
6672         };
6673         define_arm_cp_regs(cpu, lor_reginfo);
6674     }
6675
6676     if (cpu_isar_feature(aa64_sve, cpu)) {
6677         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
6678         if (arm_feature(env, ARM_FEATURE_EL2)) {
6679             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
6680         } else {
6681             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
6682         }
6683         if (arm_feature(env, ARM_FEATURE_EL3)) {
6684             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
6685         }
6686     }
6687
6688 #ifdef TARGET_AARCH64
6689     if (cpu_isar_feature(aa64_pauth, cpu)) {
6690         define_arm_cp_regs(cpu, pauth_reginfo);
6691     }
6692 #endif
6693
6694     /*
6695      * While all v8.0 cpus support aarch64, QEMU does have configurations
6696      * that do not set ID_AA64ISAR1, e.g. user-only qemu-arm -cpu max,
6697      * which will set ID_ISAR6.
6698      */
6699     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)
6700         ? cpu_isar_feature(aa64_predinv, cpu)
6701         : cpu_isar_feature(aa32_predinv, cpu)) {
6702         define_arm_cp_regs(cpu, predinv_reginfo);
6703     }
6704 }
6705
6706 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
6707 {
6708     CPUState *cs = CPU(cpu);
6709     CPUARMState *env = &cpu->env;
6710
6711     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6712         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
6713                                  aarch64_fpu_gdb_set_reg,
6714                                  34, "aarch64-fpu.xml", 0);
6715     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
6716         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6717                                  51, "arm-neon.xml", 0);
6718     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
6719         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6720                                  35, "arm-vfp3.xml", 0);
6721     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
6722         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6723                                  19, "arm-vfp.xml", 0);
6724     }
6725     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
6726                              arm_gen_dynamic_xml(cs),
6727                              "system-registers.xml", 0);
6728 }
6729
6730 /* Sort alphabetically by type name, except for "any". */
6731 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
6732 {
6733     ObjectClass *class_a = (ObjectClass *)a;
6734     ObjectClass *class_b = (ObjectClass *)b;
6735     const char *name_a, *name_b;
6736
6737     name_a = object_class_get_name(class_a);
6738     name_b = object_class_get_name(class_b);
6739     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
6740         return 1;
6741     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
6742         return -1;
6743     } else {
6744         return strcmp(name_a, name_b);
6745     }
6746 }
6747
6748 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
6749 {
6750     ObjectClass *oc = data;
6751     const char *typename;
6752     char *name;
6753
6754     typename = object_class_get_name(oc);
6755     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
6756     qemu_printf("  %s\n", name);
6757     g_free(name);
6758 }
6759
6760 void arm_cpu_list(void)
6761 {
6762     GSList *list;
6763
6764     list = object_class_get_list(TYPE_ARM_CPU, false);
6765     list = g_slist_sort(list, arm_cpu_list_compare);
6766     qemu_printf("Available CPUs:\n");
6767     g_slist_foreach(list, arm_cpu_list_entry, NULL);
6768     g_slist_free(list);
6769 }
6770
6771 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
6772 {
6773     ObjectClass *oc = data;
6774     CpuDefinitionInfoList **cpu_list = user_data;
6775     CpuDefinitionInfoList *entry;
6776     CpuDefinitionInfo *info;
6777     const char *typename;
6778
6779     typename = object_class_get_name(oc);
6780     info = g_malloc0(sizeof(*info));
6781     info->name = g_strndup(typename,
6782                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
6783     info->q_typename = g_strdup(typename);
6784
6785     entry = g_malloc0(sizeof(*entry));
6786     entry->value = info;
6787     entry->next = *cpu_list;
6788     *cpu_list = entry;
6789 }
6790
6791 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
6792 {
6793     CpuDefinitionInfoList *cpu_list = NULL;
6794     GSList *list;
6795
6796     list = object_class_get_list(TYPE_ARM_CPU, false);
6797     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
6798     g_slist_free(list);
6799
6800     return cpu_list;
6801 }
6802
6803 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
6804                                    void *opaque, int state, int secstate,
6805                                    int crm, int opc1, int opc2,
6806                                    const char *name)
6807 {
6808     /* Private utility function for define_one_arm_cp_reg_with_opaque():
6809      * add a single reginfo struct to the hash table.
6810      */
6811     uint32_t *key = g_new(uint32_t, 1);
6812     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
6813     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
6814     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
6815
6816     r2->name = g_strdup(name);
6817     /* Reset the secure state to the specific incoming state.  This is
6818      * necessary as the register may have been defined with both states.
6819      */
6820     r2->secure = secstate;
6821
6822     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
6823         /* Register is banked (using both entries in array).
6824          * Overwriting fieldoffset as the array is only used to define
6825          * banked registers but later only fieldoffset is used.
6826          */
6827         r2->fieldoffset = r->bank_fieldoffsets[ns];
6828     }
6829
6830     if (state == ARM_CP_STATE_AA32) {
6831         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
6832             /* If the register is banked then we don't need to migrate or
6833              * reset the 32-bit instance in certain cases:
6834              *
6835              * 1) If the register has both 32-bit and 64-bit instances then we
6836              *    can count on the 64-bit instance taking care of the
6837              *    non-secure bank.
6838              * 2) If ARMv8 is enabled then we can count on a 64-bit version
6839              *    taking care of the secure bank.  This requires that separate
6840              *    32 and 64-bit definitions are provided.
6841              */
6842             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
6843                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
6844                 r2->type |= ARM_CP_ALIAS;
6845             }
6846         } else if ((secstate != r->secure) && !ns) {
6847             /* The register is not banked so we only want to allow migration of
6848              * the non-secure instance.
6849              */
6850             r2->type |= ARM_CP_ALIAS;
6851         }
6852
6853         if (r->state == ARM_CP_STATE_BOTH) {
6854             /* We assume it is a cp15 register if the .cp field is left unset.
6855              */
6856             if (r2->cp == 0) {
6857                 r2->cp = 15;
6858             }
6859
6860 #ifdef HOST_WORDS_BIGENDIAN
6861             if (r2->fieldoffset) {
6862                 r2->fieldoffset += sizeof(uint32_t);
6863             }
6864 #endif
6865         }
6866     }
6867     if (state == ARM_CP_STATE_AA64) {
6868         /* To allow abbreviation of ARMCPRegInfo
6869          * definitions, we treat cp == 0 as equivalent to
6870          * the value for "standard guest-visible sysreg".
6871          * STATE_BOTH definitions are also always "standard
6872          * sysreg" in their AArch64 view (the .cp value may
6873          * be non-zero for the benefit of the AArch32 view).
6874          */
6875         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
6876             r2->cp = CP_REG_ARM64_SYSREG_CP;
6877         }
6878         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
6879                                   r2->opc0, opc1, opc2);
6880     } else {
6881         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
6882     }
6883     if (opaque) {
6884         r2->opaque = opaque;
6885     }
6886     /* reginfo passed to helpers is correct for the actual access,
6887      * and is never ARM_CP_STATE_BOTH:
6888      */
6889     r2->state = state;
6890     /* Make sure reginfo passed to helpers for wildcarded regs
6891      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
6892      */
6893     r2->crm = crm;
6894     r2->opc1 = opc1;
6895     r2->opc2 = opc2;
6896     /* By convention, for wildcarded registers only the first
6897      * entry is used for migration; the others are marked as
6898      * ALIAS so we don't try to transfer the register
6899      * multiple times. Special registers (ie NOP/WFI) are
6900      * never migratable and not even raw-accessible.
6901      */
6902     if ((r->type & ARM_CP_SPECIAL)) {
6903         r2->type |= ARM_CP_NO_RAW;
6904     }
6905     if (((r->crm == CP_ANY) && crm != 0) ||
6906         ((r->opc1 == CP_ANY) && opc1 != 0) ||
6907         ((r->opc2 == CP_ANY) && opc2 != 0)) {
6908         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
6909     }
6910
6911     /* Check that raw accesses are either forbidden or handled. Note that
6912      * we can't assert this earlier because the setup of fieldoffset for
6913      * banked registers has to be done first.
6914      */
6915     if (!(r2->type & ARM_CP_NO_RAW)) {
6916         assert(!raw_accessors_invalid(r2));
6917     }
6918
6919     /* Overriding of an existing definition must be explicitly
6920      * requested.
6921      */
6922     if (!(r->type & ARM_CP_OVERRIDE)) {
6923         ARMCPRegInfo *oldreg;
6924         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
6925         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
6926             fprintf(stderr, "Register redefined: cp=%d %d bit "
6927                     "crn=%d crm=%d opc1=%d opc2=%d, "
6928                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
6929                     r2->crn, r2->crm, r2->opc1, r2->opc2,
6930                     oldreg->name, r2->name);
6931             g_assert_not_reached();
6932         }
6933     }
6934     g_hash_table_insert(cpu->cp_regs, key, r2);
6935 }
6936
6937
6938 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
6939                                        const ARMCPRegInfo *r, void *opaque)
6940 {
6941     /* Define implementations of coprocessor registers.
6942      * We store these in a hashtable because typically
6943      * there are less than 150 registers in a space which
6944      * is 16*16*16*8*8 = 262144 in size.
6945      * Wildcarding is supported for the crm, opc1 and opc2 fields.
6946      * If a register is defined twice then the second definition is
6947      * used, so this can be used to define some generic registers and
6948      * then override them with implementation specific variations.
6949      * At least one of the original and the second definition should
6950      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
6951      * against accidental use.
6952      *
6953      * The state field defines whether the register is to be
6954      * visible in the AArch32 or AArch64 execution state. If the
6955      * state is set to ARM_CP_STATE_BOTH then we synthesise a
6956      * reginfo structure for the AArch32 view, which sees the lower
6957      * 32 bits of the 64 bit register.
6958      *
6959      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
6960      * be wildcarded. AArch64 registers are always considered to be 64
6961      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
6962      * the register, if any.
6963      */
6964     int crm, opc1, opc2, state;
6965     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
6966     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
6967     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
6968     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
6969     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
6970     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
6971     /* 64 bit registers have only CRm and Opc1 fields */
6972     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
6973     /* op0 only exists in the AArch64 encodings */
6974     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
6975     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
6976     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
6977     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
6978      * encodes a minimum access level for the register. We roll this
6979      * runtime check into our general permission check code, so check
6980      * here that the reginfo's specified permissions are strict enough
6981      * to encompass the generic architectural permission check.
6982      */
6983     if (r->state != ARM_CP_STATE_AA32) {
6984         int mask = 0;
6985         switch (r->opc1) {
6986         case 0:
6987             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
6988             mask = PL0U_R | PL1_RW;
6989             break;
6990         case 1: case 2:
6991             /* min_EL EL1 */
6992             mask = PL1_RW;
6993             break;
6994         case 3:
6995             /* min_EL EL0 */
6996             mask = PL0_RW;
6997             break;
6998         case 4:
6999             /* min_EL EL2 */
7000             mask = PL2_RW;
7001             break;
7002         case 5:
7003             /* unallocated encoding, so not possible */
7004             assert(false);
7005             break;
7006         case 6:
7007             /* min_EL EL3 */
7008             mask = PL3_RW;
7009             break;
7010         case 7:
7011             /* min_EL EL1, secure mode only (we don't check the latter) */
7012             mask = PL1_RW;
7013             break;
7014         default:
7015             /* broken reginfo with out-of-range opc1 */
7016             assert(false);
7017             break;
7018         }
7019         /* assert our permissions are not too lax (stricter is fine) */
7020         assert((r->access & ~mask) == 0);
7021     }
7022
7023     /* Check that the register definition has enough info to handle
7024      * reads and writes if they are permitted.
7025      */
7026     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
7027         if (r->access & PL3_R) {
7028             assert((r->fieldoffset ||
7029                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7030                    r->readfn);
7031         }
7032         if (r->access & PL3_W) {
7033             assert((r->fieldoffset ||
7034                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7035                    r->writefn);
7036         }
7037     }
7038     /* Bad type field probably means missing sentinel at end of reg list */
7039     assert(cptype_valid(r->type));
7040     for (crm = crmmin; crm <= crmmax; crm++) {
7041         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
7042             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
7043                 for (state = ARM_CP_STATE_AA32;
7044                      state <= ARM_CP_STATE_AA64; state++) {
7045                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
7046                         continue;
7047                     }
7048                     if (state == ARM_CP_STATE_AA32) {
7049                         /* Under AArch32 CP registers can be common
7050                          * (same for secure and non-secure world) or banked.
7051                          */
7052                         char *name;
7053
7054                         switch (r->secure) {
7055                         case ARM_CP_SECSTATE_S:
7056                         case ARM_CP_SECSTATE_NS:
7057                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7058                                                    r->secure, crm, opc1, opc2,
7059                                                    r->name);
7060                             break;
7061                         default:
7062                             name = g_strdup_printf("%s_S", r->name);
7063                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7064                                                    ARM_CP_SECSTATE_S,
7065                                                    crm, opc1, opc2, name);
7066                             g_free(name);
7067                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7068                                                    ARM_CP_SECSTATE_NS,
7069                                                    crm, opc1, opc2, r->name);
7070                             break;
7071                         }
7072                     } else {
7073                         /* AArch64 registers get mapped to non-secure instance
7074                          * of AArch32 */
7075                         add_cpreg_to_hashtable(cpu, r, opaque, state,
7076                                                ARM_CP_SECSTATE_NS,
7077                                                crm, opc1, opc2, r->name);
7078                     }
7079                 }
7080             }
7081         }
7082     }
7083 }
7084
7085 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
7086                                     const ARMCPRegInfo *regs, void *opaque)
7087 {
7088     /* Define a whole list of registers */
7089     const ARMCPRegInfo *r;
7090     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7091         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
7092     }
7093 }
7094
7095 /*
7096  * Modify ARMCPRegInfo for access from userspace.
7097  *
7098  * This is a data driven modification directed by
7099  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
7100  * user-space cannot alter any values and dynamic values pertaining to
7101  * execution state are hidden from user space view anyway.
7102  */
7103 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
7104 {
7105     const ARMCPRegUserSpaceInfo *m;
7106     ARMCPRegInfo *r;
7107
7108     for (m = mods; m->name; m++) {
7109         GPatternSpec *pat = NULL;
7110         if (m->is_glob) {
7111             pat = g_pattern_spec_new(m->name);
7112         }
7113         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7114             if (pat && g_pattern_match_string(pat, r->name)) {
7115                 r->type = ARM_CP_CONST;
7116                 r->access = PL0U_R;
7117                 r->resetvalue = 0;
7118                 /* continue */
7119             } else if (strcmp(r->name, m->name) == 0) {
7120                 r->type = ARM_CP_CONST;
7121                 r->access = PL0U_R;
7122                 r->resetvalue &= m->exported_bits;
7123                 r->resetvalue |= m->fixed_bits;
7124                 break;
7125             }
7126         }
7127         if (pat) {
7128             g_pattern_spec_free(pat);
7129         }
7130     }
7131 }
7132
7133 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
7134 {
7135     return g_hash_table_lookup(cpregs, &encoded_cp);
7136 }
7137
7138 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
7139                          uint64_t value)
7140 {
7141     /* Helper coprocessor write function for write-ignore registers */
7142 }
7143
7144 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
7145 {
7146     /* Helper coprocessor write function for read-as-zero registers */
7147     return 0;
7148 }
7149
7150 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
7151 {
7152     /* Helper coprocessor reset function for do-nothing-on-reset registers */
7153 }
7154
7155 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
7156 {
7157     /* Return true if it is not valid for us to switch to
7158      * this CPU mode (ie all the UNPREDICTABLE cases in
7159      * the ARM ARM CPSRWriteByInstr pseudocode).
7160      */
7161
7162     /* Changes to or from Hyp via MSR and CPS are illegal. */
7163     if (write_type == CPSRWriteByInstr &&
7164         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
7165          mode == ARM_CPU_MODE_HYP)) {
7166         return 1;
7167     }
7168
7169     switch (mode) {
7170     case ARM_CPU_MODE_USR:
7171         return 0;
7172     case ARM_CPU_MODE_SYS:
7173     case ARM_CPU_MODE_SVC:
7174     case ARM_CPU_MODE_ABT:
7175     case ARM_CPU_MODE_UND:
7176     case ARM_CPU_MODE_IRQ:
7177     case ARM_CPU_MODE_FIQ:
7178         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
7179          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
7180          */
7181         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
7182          * and CPS are treated as illegal mode changes.
7183          */
7184         if (write_type == CPSRWriteByInstr &&
7185             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
7186             (arm_hcr_el2_eff(env) & HCR_TGE)) {
7187             return 1;
7188         }
7189         return 0;
7190     case ARM_CPU_MODE_HYP:
7191         return !arm_feature(env, ARM_FEATURE_EL2)
7192             || arm_current_el(env) < 2 || arm_is_secure_below_el3(env);
7193     case ARM_CPU_MODE_MON:
7194         return arm_current_el(env) < 3;
7195     default:
7196         return 1;
7197     }
7198 }
7199
7200 uint32_t cpsr_read(CPUARMState *env)
7201 {
7202     int ZF;
7203     ZF = (env->ZF == 0);
7204     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
7205         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
7206         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
7207         | ((env->condexec_bits & 0xfc) << 8)
7208         | (env->GE << 16) | (env->daif & CPSR_AIF);
7209 }
7210
7211 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
7212                 CPSRWriteType write_type)
7213 {
7214     uint32_t changed_daif;
7215
7216     if (mask & CPSR_NZCV) {
7217         env->ZF = (~val) & CPSR_Z;
7218         env->NF = val;
7219         env->CF = (val >> 29) & 1;
7220         env->VF = (val << 3) & 0x80000000;
7221     }
7222     if (mask & CPSR_Q)
7223         env->QF = ((val & CPSR_Q) != 0);
7224     if (mask & CPSR_T)
7225         env->thumb = ((val & CPSR_T) != 0);
7226     if (mask & CPSR_IT_0_1) {
7227         env->condexec_bits &= ~3;
7228         env->condexec_bits |= (val >> 25) & 3;
7229     }
7230     if (mask & CPSR_IT_2_7) {
7231         env->condexec_bits &= 3;
7232         env->condexec_bits |= (val >> 8) & 0xfc;
7233     }
7234     if (mask & CPSR_GE) {
7235         env->GE = (val >> 16) & 0xf;
7236     }
7237
7238     /* In a V7 implementation that includes the security extensions but does
7239      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
7240      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
7241      * bits respectively.
7242      *
7243      * In a V8 implementation, it is permitted for privileged software to
7244      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
7245      */
7246     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
7247         arm_feature(env, ARM_FEATURE_EL3) &&
7248         !arm_feature(env, ARM_FEATURE_EL2) &&
7249         !arm_is_secure(env)) {
7250
7251         changed_daif = (env->daif ^ val) & mask;
7252
7253         if (changed_daif & CPSR_A) {
7254             /* Check to see if we are allowed to change the masking of async
7255              * abort exceptions from a non-secure state.
7256              */
7257             if (!(env->cp15.scr_el3 & SCR_AW)) {
7258                 qemu_log_mask(LOG_GUEST_ERROR,
7259                               "Ignoring attempt to switch CPSR_A flag from "
7260                               "non-secure world with SCR.AW bit clear\n");
7261                 mask &= ~CPSR_A;
7262             }
7263         }
7264
7265         if (changed_daif & CPSR_F) {
7266             /* Check to see if we are allowed to change the masking of FIQ
7267              * exceptions from a non-secure state.
7268              */
7269             if (!(env->cp15.scr_el3 & SCR_FW)) {
7270                 qemu_log_mask(LOG_GUEST_ERROR,
7271                               "Ignoring attempt to switch CPSR_F flag from "
7272                               "non-secure world with SCR.FW bit clear\n");
7273                 mask &= ~CPSR_F;
7274             }
7275
7276             /* Check whether non-maskable FIQ (NMFI) support is enabled.
7277              * If this bit is set software is not allowed to mask
7278              * FIQs, but is allowed to set CPSR_F to 0.
7279              */
7280             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
7281                 (val & CPSR_F)) {
7282                 qemu_log_mask(LOG_GUEST_ERROR,
7283                               "Ignoring attempt to enable CPSR_F flag "
7284                               "(non-maskable FIQ [NMFI] support enabled)\n");
7285                 mask &= ~CPSR_F;
7286             }
7287         }
7288     }
7289
7290     env->daif &= ~(CPSR_AIF & mask);
7291     env->daif |= val & CPSR_AIF & mask;
7292
7293     if (write_type != CPSRWriteRaw &&
7294         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
7295         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
7296             /* Note that we can only get here in USR mode if this is a
7297              * gdb stub write; for this case we follow the architectural
7298              * behaviour for guest writes in USR mode of ignoring an attempt
7299              * to switch mode. (Those are caught by translate.c for writes
7300              * triggered by guest instructions.)
7301              */
7302             mask &= ~CPSR_M;
7303         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
7304             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
7305              * v7, and has defined behaviour in v8:
7306              *  + leave CPSR.M untouched
7307              *  + allow changes to the other CPSR fields
7308              *  + set PSTATE.IL
7309              * For user changes via the GDB stub, we don't set PSTATE.IL,
7310              * as this would be unnecessarily harsh for a user error.
7311              */
7312             mask &= ~CPSR_M;
7313             if (write_type != CPSRWriteByGDBStub &&
7314                 arm_feature(env, ARM_FEATURE_V8)) {
7315                 mask |= CPSR_IL;
7316                 val |= CPSR_IL;
7317             }
7318             qemu_log_mask(LOG_GUEST_ERROR,
7319                           "Illegal AArch32 mode switch attempt from %s to %s\n",
7320                           aarch32_mode_name(env->uncached_cpsr),
7321                           aarch32_mode_name(val));
7322         } else {
7323             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
7324                           write_type == CPSRWriteExceptionReturn ?
7325                           "Exception return from AArch32" :
7326                           "AArch32 mode switch from",
7327                           aarch32_mode_name(env->uncached_cpsr),
7328                           aarch32_mode_name(val), env->regs[15]);
7329             switch_mode(env, val & CPSR_M);
7330         }
7331     }
7332     mask &= ~CACHED_CPSR_BITS;
7333     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
7334 }
7335
7336 /* Sign/zero extend */
7337 uint32_t HELPER(sxtb16)(uint32_t x)
7338 {
7339     uint32_t res;
7340     res = (uint16_t)(int8_t)x;
7341     res |= (uint32_t)(int8_t)(x >> 16) << 16;
7342     return res;
7343 }
7344
7345 uint32_t HELPER(uxtb16)(uint32_t x)
7346 {
7347     uint32_t res;
7348     res = (uint16_t)(uint8_t)x;
7349     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
7350     return res;
7351 }
7352
7353 int32_t HELPER(sdiv)(int32_t num, int32_t den)
7354 {
7355     if (den == 0)
7356       return 0;
7357     if (num == INT_MIN && den == -1)
7358       return INT_MIN;
7359     return num / den;
7360 }
7361
7362 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
7363 {
7364     if (den == 0)
7365       return 0;
7366     return num / den;
7367 }
7368
7369 uint32_t HELPER(rbit)(uint32_t x)
7370 {
7371     return revbit32(x);
7372 }
7373
7374 #ifdef CONFIG_USER_ONLY
7375
7376 /* These should probably raise undefined insn exceptions.  */
7377 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
7378 {
7379     ARMCPU *cpu = arm_env_get_cpu(env);
7380
7381     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
7382 }
7383
7384 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
7385 {
7386     ARMCPU *cpu = arm_env_get_cpu(env);
7387
7388     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
7389     return 0;
7390 }
7391
7392 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
7393 {
7394     /* translate.c should never generate calls here in user-only mode */
7395     g_assert_not_reached();
7396 }
7397
7398 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
7399 {
7400     /* translate.c should never generate calls here in user-only mode */
7401     g_assert_not_reached();
7402 }
7403
7404 void HELPER(v7m_preserve_fp_state)(CPUARMState *env)
7405 {
7406     /* translate.c should never generate calls here in user-only mode */
7407     g_assert_not_reached();
7408 }
7409
7410 void HELPER(v7m_vlstm)(CPUARMState *env, uint32_t fptr)
7411 {
7412     /* translate.c should never generate calls here in user-only mode */
7413     g_assert_not_reached();
7414 }
7415
7416 void HELPER(v7m_vlldm)(CPUARMState *env, uint32_t fptr)
7417 {
7418     /* translate.c should never generate calls here in user-only mode */
7419     g_assert_not_reached();
7420 }
7421
7422 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
7423 {
7424     /* The TT instructions can be used by unprivileged code, but in
7425      * user-only emulation we don't have the MPU.
7426      * Luckily since we know we are NonSecure unprivileged (and that in
7427      * turn means that the A flag wasn't specified), all the bits in the
7428      * register must be zero:
7429      *  IREGION: 0 because IRVALID is 0
7430      *  IRVALID: 0 because NS
7431      *  S: 0 because NS
7432      *  NSRW: 0 because NS
7433      *  NSR: 0 because NS
7434      *  RW: 0 because unpriv and A flag not set
7435      *  R: 0 because unpriv and A flag not set
7436      *  SRVALID: 0 because NS
7437      *  MRVALID: 0 because unpriv and A flag not set
7438      *  SREGION: 0 becaus SRVALID is 0
7439      *  MREGION: 0 because MRVALID is 0
7440      */
7441     return 0;
7442 }
7443
7444 static void switch_mode(CPUARMState *env, int mode)
7445 {
7446     ARMCPU *cpu = arm_env_get_cpu(env);
7447
7448     if (mode != ARM_CPU_MODE_USR) {
7449         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
7450     }
7451 }
7452
7453 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7454                                  uint32_t cur_el, bool secure)
7455 {
7456     return 1;
7457 }
7458
7459 void aarch64_sync_64_to_32(CPUARMState *env)
7460 {
7461     g_assert_not_reached();
7462 }
7463
7464 #else
7465
7466 static void switch_mode(CPUARMState *env, int mode)
7467 {
7468     int old_mode;
7469     int i;
7470
7471     old_mode = env->uncached_cpsr & CPSR_M;
7472     if (mode == old_mode)
7473         return;
7474
7475     if (old_mode == ARM_CPU_MODE_FIQ) {
7476         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
7477         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
7478     } else if (mode == ARM_CPU_MODE_FIQ) {
7479         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
7480         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
7481     }
7482
7483     i = bank_number(old_mode);
7484     env->banked_r13[i] = env->regs[13];
7485     env->banked_spsr[i] = env->spsr;
7486
7487     i = bank_number(mode);
7488     env->regs[13] = env->banked_r13[i];
7489     env->spsr = env->banked_spsr[i];
7490
7491     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
7492     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
7493 }
7494
7495 /* Physical Interrupt Target EL Lookup Table
7496  *
7497  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
7498  *
7499  * The below multi-dimensional table is used for looking up the target
7500  * exception level given numerous condition criteria.  Specifically, the
7501  * target EL is based on SCR and HCR routing controls as well as the
7502  * currently executing EL and secure state.
7503  *
7504  *    Dimensions:
7505  *    target_el_table[2][2][2][2][2][4]
7506  *                    |  |  |  |  |  +--- Current EL
7507  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
7508  *                    |  |  |  +--------- HCR mask override
7509  *                    |  |  +------------ SCR exec state control
7510  *                    |  +--------------- SCR mask override
7511  *                    +------------------ 32-bit(0)/64-bit(1) EL3
7512  *
7513  *    The table values are as such:
7514  *    0-3 = EL0-EL3
7515  *     -1 = Cannot occur
7516  *
7517  * The ARM ARM target EL table includes entries indicating that an "exception
7518  * is not taken".  The two cases where this is applicable are:
7519  *    1) An exception is taken from EL3 but the SCR does not have the exception
7520  *    routed to EL3.
7521  *    2) An exception is taken from EL2 but the HCR does not have the exception
7522  *    routed to EL2.
7523  * In these two cases, the below table contain a target of EL1.  This value is
7524  * returned as it is expected that the consumer of the table data will check
7525  * for "target EL >= current EL" to ensure the exception is not taken.
7526  *
7527  *            SCR     HCR
7528  *         64  EA     AMO                 From
7529  *        BIT IRQ     IMO      Non-secure         Secure
7530  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
7531  */
7532 static const int8_t target_el_table[2][2][2][2][2][4] = {
7533     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7534        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
7535       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7536        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
7537      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7538        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
7539       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7540        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
7541     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
7542        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
7543       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
7544        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
7545      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7546        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
7547       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7548        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
7549 };
7550
7551 /*
7552  * Determine the target EL for physical exceptions
7553  */
7554 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7555                                  uint32_t cur_el, bool secure)
7556 {
7557     CPUARMState *env = cs->env_ptr;
7558     bool rw;
7559     bool scr;
7560     bool hcr;
7561     int target_el;
7562     /* Is the highest EL AArch64? */
7563     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
7564     uint64_t hcr_el2;
7565
7566     if (arm_feature(env, ARM_FEATURE_EL3)) {
7567         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
7568     } else {
7569         /* Either EL2 is the highest EL (and so the EL2 register width
7570          * is given by is64); or there is no EL2 or EL3, in which case
7571          * the value of 'rw' does not affect the table lookup anyway.
7572          */
7573         rw = is64;
7574     }
7575
7576     hcr_el2 = arm_hcr_el2_eff(env);
7577     switch (excp_idx) {
7578     case EXCP_IRQ:
7579         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
7580         hcr = hcr_el2 & HCR_IMO;
7581         break;
7582     case EXCP_FIQ:
7583         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
7584         hcr = hcr_el2 & HCR_FMO;
7585         break;
7586     default:
7587         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
7588         hcr = hcr_el2 & HCR_AMO;
7589         break;
7590     };
7591
7592     /* Perform a table-lookup for the target EL given the current state */
7593     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
7594
7595     assert(target_el > 0);
7596
7597     return target_el;
7598 }
7599
7600 /*
7601  * Return true if the v7M CPACR permits access to the FPU for the specified
7602  * security state and privilege level.
7603  */
7604 static bool v7m_cpacr_pass(CPUARMState *env, bool is_secure, bool is_priv)
7605 {
7606     switch (extract32(env->v7m.cpacr[is_secure], 20, 2)) {
7607     case 0:
7608     case 2: /* UNPREDICTABLE: we treat like 0 */
7609         return false;
7610     case 1:
7611         return is_priv;
7612     case 3:
7613         return true;
7614     default:
7615         g_assert_not_reached();
7616     }
7617 }
7618
7619 /*
7620  * What kind of stack write are we doing? This affects how exceptions
7621  * generated during the stacking are treated.
7622  */
7623 typedef enum StackingMode {
7624     STACK_NORMAL,
7625     STACK_IGNFAULTS,
7626     STACK_LAZYFP,
7627 } StackingMode;
7628
7629 static bool v7m_stack_write(ARMCPU *cpu, uint32_t addr, uint32_t value,
7630                             ARMMMUIdx mmu_idx, StackingMode mode)
7631 {
7632     CPUState *cs = CPU(cpu);
7633     CPUARMState *env = &cpu->env;
7634     MemTxAttrs attrs = {};
7635     MemTxResult txres;
7636     target_ulong page_size;
7637     hwaddr physaddr;
7638     int prot;
7639     ARMMMUFaultInfo fi = {};
7640     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
7641     int exc;
7642     bool exc_secure;
7643
7644     if (get_phys_addr(env, addr, MMU_DATA_STORE, mmu_idx, &physaddr,
7645                       &attrs, &prot, &page_size, &fi, NULL)) {
7646         /* MPU/SAU lookup failed */
7647         if (fi.type == ARMFault_QEMU_SFault) {
7648             if (mode == STACK_LAZYFP) {
7649                 qemu_log_mask(CPU_LOG_INT,
7650                               "...SecureFault with SFSR.LSPERR "
7651                               "during lazy stacking\n");
7652                 env->v7m.sfsr |= R_V7M_SFSR_LSPERR_MASK;
7653             } else {
7654                 qemu_log_mask(CPU_LOG_INT,
7655                               "...SecureFault with SFSR.AUVIOL "
7656                               "during stacking\n");
7657                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
7658             }
7659             env->v7m.sfsr |= R_V7M_SFSR_SFARVALID_MASK;
7660             env->v7m.sfar = addr;
7661             exc = ARMV7M_EXCP_SECURE;
7662             exc_secure = false;
7663         } else {
7664             if (mode == STACK_LAZYFP) {
7665                 qemu_log_mask(CPU_LOG_INT,
7666                               "...MemManageFault with CFSR.MLSPERR\n");
7667                 env->v7m.cfsr[secure] |= R_V7M_CFSR_MLSPERR_MASK;
7668             } else {
7669                 qemu_log_mask(CPU_LOG_INT,
7670                               "...MemManageFault with CFSR.MSTKERR\n");
7671                 env->v7m.cfsr[secure] |= R_V7M_CFSR_MSTKERR_MASK;
7672             }
7673             exc = ARMV7M_EXCP_MEM;
7674             exc_secure = secure;
7675         }
7676         goto pend_fault;
7677     }
7678     address_space_stl_le(arm_addressspace(cs, attrs), physaddr, value,
7679                          attrs, &txres);
7680     if (txres != MEMTX_OK) {
7681         /* BusFault trying to write the data */
7682         if (mode == STACK_LAZYFP) {
7683             qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.LSPERR\n");
7684             env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_LSPERR_MASK;
7685         } else {
7686             qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.STKERR\n");
7687             env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_STKERR_MASK;
7688         }
7689         exc = ARMV7M_EXCP_BUS;
7690         exc_secure = false;
7691         goto pend_fault;
7692     }
7693     return true;
7694
7695 pend_fault:
7696     /* By pending the exception at this point we are making
7697      * the IMPDEF choice "overridden exceptions pended" (see the
7698      * MergeExcInfo() pseudocode). The other choice would be to not
7699      * pend them now and then make a choice about which to throw away
7700      * later if we have two derived exceptions.
7701      * The only case when we must not pend the exception but instead
7702      * throw it away is if we are doing the push of the callee registers
7703      * and we've already generated a derived exception (this is indicated
7704      * by the caller passing STACK_IGNFAULTS). Even in this case we will
7705      * still update the fault status registers.
7706      */
7707     switch (mode) {
7708     case STACK_NORMAL:
7709         armv7m_nvic_set_pending_derived(env->nvic, exc, exc_secure);
7710         break;
7711     case STACK_LAZYFP:
7712         armv7m_nvic_set_pending_lazyfp(env->nvic, exc, exc_secure);
7713         break;
7714     case STACK_IGNFAULTS:
7715         break;
7716     }
7717     return false;
7718 }
7719
7720 static bool v7m_stack_read(ARMCPU *cpu, uint32_t *dest, uint32_t addr,
7721                            ARMMMUIdx mmu_idx)
7722 {
7723     CPUState *cs = CPU(cpu);
7724     CPUARMState *env = &cpu->env;
7725     MemTxAttrs attrs = {};
7726     MemTxResult txres;
7727     target_ulong page_size;
7728     hwaddr physaddr;
7729     int prot;
7730     ARMMMUFaultInfo fi = {};
7731     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
7732     int exc;
7733     bool exc_secure;
7734     uint32_t value;
7735
7736     if (get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &physaddr,
7737                       &attrs, &prot, &page_size, &fi, NULL)) {
7738         /* MPU/SAU lookup failed */
7739         if (fi.type == ARMFault_QEMU_SFault) {
7740             qemu_log_mask(CPU_LOG_INT,
7741                           "...SecureFault with SFSR.AUVIOL during unstack\n");
7742             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
7743             env->v7m.sfar = addr;
7744             exc = ARMV7M_EXCP_SECURE;
7745             exc_secure = false;
7746         } else {
7747             qemu_log_mask(CPU_LOG_INT,
7748                           "...MemManageFault with CFSR.MUNSTKERR\n");
7749             env->v7m.cfsr[secure] |= R_V7M_CFSR_MUNSTKERR_MASK;
7750             exc = ARMV7M_EXCP_MEM;
7751             exc_secure = secure;
7752         }
7753         goto pend_fault;
7754     }
7755
7756     value = address_space_ldl(arm_addressspace(cs, attrs), physaddr,
7757                               attrs, &txres);
7758     if (txres != MEMTX_OK) {
7759         /* BusFault trying to read the data */
7760         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.UNSTKERR\n");
7761         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_UNSTKERR_MASK;
7762         exc = ARMV7M_EXCP_BUS;
7763         exc_secure = false;
7764         goto pend_fault;
7765     }
7766
7767     *dest = value;
7768     return true;
7769
7770 pend_fault:
7771     /* By pending the exception at this point we are making
7772      * the IMPDEF choice "overridden exceptions pended" (see the
7773      * MergeExcInfo() pseudocode). The other choice would be to not
7774      * pend them now and then make a choice about which to throw away
7775      * later if we have two derived exceptions.
7776      */
7777     armv7m_nvic_set_pending(env->nvic, exc, exc_secure);
7778     return false;
7779 }
7780
7781 void HELPER(v7m_preserve_fp_state)(CPUARMState *env)
7782 {
7783     /*
7784      * Preserve FP state (because LSPACT was set and we are about
7785      * to execute an FP instruction). This corresponds to the
7786      * PreserveFPState() pseudocode.
7787      * We may throw an exception if the stacking fails.
7788      */
7789     ARMCPU *cpu = arm_env_get_cpu(env);
7790     bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
7791     bool negpri = !(env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_HFRDY_MASK);
7792     bool is_priv = !(env->v7m.fpccr[is_secure] & R_V7M_FPCCR_USER_MASK);
7793     bool splimviol = env->v7m.fpccr[is_secure] & R_V7M_FPCCR_SPLIMVIOL_MASK;
7794     uint32_t fpcar = env->v7m.fpcar[is_secure];
7795     bool stacked_ok = true;
7796     bool ts = is_secure && (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK);
7797     bool take_exception;
7798
7799     /* Take the iothread lock as we are going to touch the NVIC */
7800     qemu_mutex_lock_iothread();
7801
7802     /* Check the background context had access to the FPU */
7803     if (!v7m_cpacr_pass(env, is_secure, is_priv)) {
7804         armv7m_nvic_set_pending_lazyfp(env->nvic, ARMV7M_EXCP_USAGE, is_secure);
7805         env->v7m.cfsr[is_secure] |= R_V7M_CFSR_NOCP_MASK;
7806         stacked_ok = false;
7807     } else if (!is_secure && !extract32(env->v7m.nsacr, 10, 1)) {
7808         armv7m_nvic_set_pending_lazyfp(env->nvic, ARMV7M_EXCP_USAGE, M_REG_S);
7809         env->v7m.cfsr[M_REG_S] |= R_V7M_CFSR_NOCP_MASK;
7810         stacked_ok = false;
7811     }
7812
7813     if (!splimviol && stacked_ok) {
7814         /* We only stack if the stack limit wasn't violated */
7815         int i;
7816         ARMMMUIdx mmu_idx;
7817
7818         mmu_idx = arm_v7m_mmu_idx_all(env, is_secure, is_priv, negpri);
7819         for (i = 0; i < (ts ? 32 : 16); i += 2) {
7820             uint64_t dn = *aa32_vfp_dreg(env, i / 2);
7821             uint32_t faddr = fpcar + 4 * i;
7822             uint32_t slo = extract64(dn, 0, 32);
7823             uint32_t shi = extract64(dn, 32, 32);
7824
7825             if (i >= 16) {
7826                 faddr += 8; /* skip the slot for the FPSCR */
7827             }
7828             stacked_ok = stacked_ok &&
7829                 v7m_stack_write(cpu, faddr, slo, mmu_idx, STACK_LAZYFP) &&
7830                 v7m_stack_write(cpu, faddr + 4, shi, mmu_idx, STACK_LAZYFP);
7831         }
7832
7833         stacked_ok = stacked_ok &&
7834             v7m_stack_write(cpu, fpcar + 0x40,
7835                             vfp_get_fpscr(env), mmu_idx, STACK_LAZYFP);
7836     }
7837
7838     /*
7839      * We definitely pended an exception, but it's possible that it
7840      * might not be able to be taken now. If its priority permits us
7841      * to take it now, then we must not update the LSPACT or FP regs,
7842      * but instead jump out to take the exception immediately.
7843      * If it's just pending and won't be taken until the current
7844      * handler exits, then we do update LSPACT and the FP regs.
7845      */
7846     take_exception = !stacked_ok &&
7847         armv7m_nvic_can_take_pending_exception(env->nvic);
7848
7849     qemu_mutex_unlock_iothread();
7850
7851     if (take_exception) {
7852         raise_exception_ra(env, EXCP_LAZYFP, 0, 1, GETPC());
7853     }
7854
7855     env->v7m.fpccr[is_secure] &= ~R_V7M_FPCCR_LSPACT_MASK;
7856
7857     if (ts) {
7858         /* Clear s0 to s31 and the FPSCR */
7859         int i;
7860
7861         for (i = 0; i < 32; i += 2) {
7862             *aa32_vfp_dreg(env, i / 2) = 0;
7863         }
7864         vfp_set_fpscr(env, 0);
7865     }
7866     /*
7867      * Otherwise s0 to s15 and FPSCR are UNKNOWN; we choose to leave them
7868      * unchanged.
7869      */
7870 }
7871
7872 /* Write to v7M CONTROL.SPSEL bit for the specified security bank.
7873  * This may change the current stack pointer between Main and Process
7874  * stack pointers if it is done for the CONTROL register for the current
7875  * security state.
7876  */
7877 static void write_v7m_control_spsel_for_secstate(CPUARMState *env,
7878                                                  bool new_spsel,
7879                                                  bool secstate)
7880 {
7881     bool old_is_psp = v7m_using_psp(env);
7882
7883     env->v7m.control[secstate] =
7884         deposit32(env->v7m.control[secstate],
7885                   R_V7M_CONTROL_SPSEL_SHIFT,
7886                   R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);
7887
7888     if (secstate == env->v7m.secure) {
7889         bool new_is_psp = v7m_using_psp(env);
7890         uint32_t tmp;
7891
7892         if (old_is_psp != new_is_psp) {
7893             tmp = env->v7m.other_sp;
7894             env->v7m.other_sp = env->regs[13];
7895             env->regs[13] = tmp;
7896         }
7897     }
7898 }
7899
7900 /* Write to v7M CONTROL.SPSEL bit. This may change the current
7901  * stack pointer between Main and Process stack pointers.
7902  */
7903 static void write_v7m_control_spsel(CPUARMState *env, bool new_spsel)
7904 {
7905     write_v7m_control_spsel_for_secstate(env, new_spsel, env->v7m.secure);
7906 }
7907
7908 void write_v7m_exception(CPUARMState *env, uint32_t new_exc)
7909 {
7910     /* Write a new value to v7m.exception, thus transitioning into or out
7911      * of Handler mode; this may result in a change of active stack pointer.
7912      */
7913     bool new_is_psp, old_is_psp = v7m_using_psp(env);
7914     uint32_t tmp;
7915
7916     env->v7m.exception = new_exc;
7917
7918     new_is_psp = v7m_using_psp(env);
7919
7920     if (old_is_psp != new_is_psp) {
7921         tmp = env->v7m.other_sp;
7922         env->v7m.other_sp = env->regs[13];
7923         env->regs[13] = tmp;
7924     }
7925 }
7926
7927 /* Switch M profile security state between NS and S */
7928 static void switch_v7m_security_state(CPUARMState *env, bool new_secstate)
7929 {
7930     uint32_t new_ss_msp, new_ss_psp;
7931
7932     if (env->v7m.secure == new_secstate) {
7933         return;
7934     }
7935
7936     /* All the banked state is accessed by looking at env->v7m.secure
7937      * except for the stack pointer; rearrange the SP appropriately.
7938      */
7939     new_ss_msp = env->v7m.other_ss_msp;
7940     new_ss_psp = env->v7m.other_ss_psp;
7941
7942     if (v7m_using_psp(env)) {
7943         env->v7m.other_ss_psp = env->regs[13];
7944         env->v7m.other_ss_msp = env->v7m.other_sp;
7945     } else {
7946         env->v7m.other_ss_msp = env->regs[13];
7947         env->v7m.other_ss_psp = env->v7m.other_sp;
7948     }
7949
7950     env->v7m.secure = new_secstate;
7951
7952     if (v7m_using_psp(env)) {
7953         env->regs[13] = new_ss_psp;
7954         env->v7m.other_sp = new_ss_msp;
7955     } else {
7956         env->regs[13] = new_ss_msp;
7957         env->v7m.other_sp = new_ss_psp;
7958     }
7959 }
7960
7961 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
7962 {
7963     /* Handle v7M BXNS:
7964      *  - if the return value is a magic value, do exception return (like BX)
7965      *  - otherwise bit 0 of the return value is the target security state
7966      */
7967     uint32_t min_magic;
7968
7969     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7970         /* Covers FNC_RETURN and EXC_RETURN magic */
7971         min_magic = FNC_RETURN_MIN_MAGIC;
7972     } else {
7973         /* EXC_RETURN magic only */
7974         min_magic = EXC_RETURN_MIN_MAGIC;
7975     }
7976
7977     if (dest >= min_magic) {
7978         /* This is an exception return magic value; put it where
7979          * do_v7m_exception_exit() expects and raise EXCEPTION_EXIT.
7980          * Note that if we ever add gen_ss_advance() singlestep support to
7981          * M profile this should count as an "instruction execution complete"
7982          * event (compare gen_bx_excret_final_code()).
7983          */
7984         env->regs[15] = dest & ~1;
7985         env->thumb = dest & 1;
7986         HELPER(exception_internal)(env, EXCP_EXCEPTION_EXIT);
7987         /* notreached */
7988     }
7989
7990     /* translate.c should have made BXNS UNDEF unless we're secure */
7991     assert(env->v7m.secure);
7992
7993     if (!(dest & 1)) {
7994         env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
7995     }
7996     switch_v7m_security_state(env, dest & 1);
7997     env->thumb = 1;
7998     env->regs[15] = dest & ~1;
7999 }
8000
8001 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
8002 {
8003     /* Handle v7M BLXNS:
8004      *  - bit 0 of the destination address is the target security state
8005      */
8006
8007     /* At this point regs[15] is the address just after the BLXNS */
8008     uint32_t nextinst = env->regs[15] | 1;
8009     uint32_t sp = env->regs[13] - 8;
8010     uint32_t saved_psr;
8011
8012     /* translate.c will have made BLXNS UNDEF unless we're secure */
8013     assert(env->v7m.secure);
8014
8015     if (dest & 1) {
8016         /* target is Secure, so this is just a normal BLX,
8017          * except that the low bit doesn't indicate Thumb/not.
8018          */
8019         env->regs[14] = nextinst;
8020         env->thumb = 1;
8021         env->regs[15] = dest & ~1;
8022         return;
8023     }
8024
8025     /* Target is non-secure: first push a stack frame */
8026     if (!QEMU_IS_ALIGNED(sp, 8)) {
8027         qemu_log_mask(LOG_GUEST_ERROR,
8028                       "BLXNS with misaligned SP is UNPREDICTABLE\n");
8029     }
8030
8031     if (sp < v7m_sp_limit(env)) {
8032         raise_exception(env, EXCP_STKOF, 0, 1);
8033     }
8034
8035     saved_psr = env->v7m.exception;
8036     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK) {
8037         saved_psr |= XPSR_SFPA;
8038     }
8039
8040     /* Note that these stores can throw exceptions on MPU faults */
8041     cpu_stl_data(env, sp, nextinst);
8042     cpu_stl_data(env, sp + 4, saved_psr);
8043
8044     env->regs[13] = sp;
8045     env->regs[14] = 0xfeffffff;
8046     if (arm_v7m_is_handler_mode(env)) {
8047         /* Write a dummy value to IPSR, to avoid leaking the current secure
8048          * exception number to non-secure code. This is guaranteed not
8049          * to cause write_v7m_exception() to actually change stacks.
8050          */
8051         write_v7m_exception(env, 1);
8052     }
8053     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
8054     switch_v7m_security_state(env, 0);
8055     env->thumb = 1;
8056     env->regs[15] = dest;
8057 }
8058
8059 static uint32_t *get_v7m_sp_ptr(CPUARMState *env, bool secure, bool threadmode,
8060                                 bool spsel)
8061 {
8062     /* Return a pointer to the location where we currently store the
8063      * stack pointer for the requested security state and thread mode.
8064      * This pointer will become invalid if the CPU state is updated
8065      * such that the stack pointers are switched around (eg changing
8066      * the SPSEL control bit).
8067      * Compare the v8M ARM ARM pseudocode LookUpSP_with_security_mode().
8068      * Unlike that pseudocode, we require the caller to pass us in the
8069      * SPSEL control bit value; this is because we also use this
8070      * function in handling of pushing of the callee-saves registers
8071      * part of the v8M stack frame (pseudocode PushCalleeStack()),
8072      * and in the tailchain codepath the SPSEL bit comes from the exception
8073      * return magic LR value from the previous exception. The pseudocode
8074      * opencodes the stack-selection in PushCalleeStack(), but we prefer
8075      * to make this utility function generic enough to do the job.
8076      */
8077     bool want_psp = threadmode && spsel;
8078
8079     if (secure == env->v7m.secure) {
8080         if (want_psp == v7m_using_psp(env)) {
8081             return &env->regs[13];
8082         } else {
8083             return &env->v7m.other_sp;
8084         }
8085     } else {
8086         if (want_psp) {
8087             return &env->v7m.other_ss_psp;
8088         } else {
8089             return &env->v7m.other_ss_msp;
8090         }
8091     }
8092 }
8093
8094 static bool arm_v7m_load_vector(ARMCPU *cpu, int exc, bool targets_secure,
8095                                 uint32_t *pvec)
8096 {
8097     CPUState *cs = CPU(cpu);
8098     CPUARMState *env = &cpu->env;
8099     MemTxResult result;
8100     uint32_t addr = env->v7m.vecbase[targets_secure] + exc * 4;
8101     uint32_t vector_entry;
8102     MemTxAttrs attrs = {};
8103     ARMMMUIdx mmu_idx;
8104     bool exc_secure;
8105
8106     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targets_secure, true);
8107
8108     /* We don't do a get_phys_addr() here because the rules for vector
8109      * loads are special: they always use the default memory map, and
8110      * the default memory map permits reads from all addresses.
8111      * Since there's no easy way to pass through to pmsav8_mpu_lookup()
8112      * that we want this special case which would always say "yes",
8113      * we just do the SAU lookup here followed by a direct physical load.
8114      */
8115     attrs.secure = targets_secure;
8116     attrs.user = false;
8117
8118     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8119         V8M_SAttributes sattrs = {};
8120
8121         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
8122         if (sattrs.ns) {
8123             attrs.secure = false;
8124         } else if (!targets_secure) {
8125             /* NS access to S memory */
8126             goto load_fail;
8127         }
8128     }
8129
8130     vector_entry = address_space_ldl(arm_addressspace(cs, attrs), addr,
8131                                      attrs, &result);
8132     if (result != MEMTX_OK) {
8133         goto load_fail;
8134     }
8135     *pvec = vector_entry;
8136     return true;
8137
8138 load_fail:
8139     /* All vector table fetch fails are reported as HardFault, with
8140      * HFSR.VECTTBL and .FORCED set. (FORCED is set because
8141      * technically the underlying exception is a MemManage or BusFault
8142      * that is escalated to HardFault.) This is a terminal exception,
8143      * so we will either take the HardFault immediately or else enter
8144      * lockup (the latter case is handled in armv7m_nvic_set_pending_derived()).
8145      */
8146     exc_secure = targets_secure ||
8147         !(cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK);
8148     env->v7m.hfsr |= R_V7M_HFSR_VECTTBL_MASK | R_V7M_HFSR_FORCED_MASK;
8149     armv7m_nvic_set_pending_derived(env->nvic, ARMV7M_EXCP_HARD, exc_secure);
8150     return false;
8151 }
8152
8153 static uint32_t v7m_integrity_sig(CPUARMState *env, uint32_t lr)
8154 {
8155     /*
8156      * Return the integrity signature value for the callee-saves
8157      * stack frame section. @lr is the exception return payload/LR value
8158      * whose FType bit forms bit 0 of the signature if FP is present.
8159      */
8160     uint32_t sig = 0xfefa125a;
8161
8162     if (!arm_feature(env, ARM_FEATURE_VFP) || (lr & R_V7M_EXCRET_FTYPE_MASK)) {
8163         sig |= 1;
8164     }
8165     return sig;
8166 }
8167
8168 static bool v7m_push_callee_stack(ARMCPU *cpu, uint32_t lr, bool dotailchain,
8169                                   bool ignore_faults)
8170 {
8171     /* For v8M, push the callee-saves register part of the stack frame.
8172      * Compare the v8M pseudocode PushCalleeStack().
8173      * In the tailchaining case this may not be the current stack.
8174      */
8175     CPUARMState *env = &cpu->env;
8176     uint32_t *frame_sp_p;
8177     uint32_t frameptr;
8178     ARMMMUIdx mmu_idx;
8179     bool stacked_ok;
8180     uint32_t limit;
8181     bool want_psp;
8182     uint32_t sig;
8183     StackingMode smode = ignore_faults ? STACK_IGNFAULTS : STACK_NORMAL;
8184
8185     if (dotailchain) {
8186         bool mode = lr & R_V7M_EXCRET_MODE_MASK;
8187         bool priv = !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_NPRIV_MASK) ||
8188             !mode;
8189
8190         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, M_REG_S, priv);
8191         frame_sp_p = get_v7m_sp_ptr(env, M_REG_S, mode,
8192                                     lr & R_V7M_EXCRET_SPSEL_MASK);
8193         want_psp = mode && (lr & R_V7M_EXCRET_SPSEL_MASK);
8194         if (want_psp) {
8195             limit = env->v7m.psplim[M_REG_S];
8196         } else {
8197             limit = env->v7m.msplim[M_REG_S];
8198         }
8199     } else {
8200         mmu_idx = arm_mmu_idx(env);
8201         frame_sp_p = &env->regs[13];
8202         limit = v7m_sp_limit(env);
8203     }
8204
8205     frameptr = *frame_sp_p - 0x28;
8206     if (frameptr < limit) {
8207         /*
8208          * Stack limit failure: set SP to the limit value, and generate
8209          * STKOF UsageFault. Stack pushes below the limit must not be
8210          * performed. It is IMPDEF whether pushes above the limit are
8211          * performed; we choose not to.
8212          */
8213         qemu_log_mask(CPU_LOG_INT,
8214                       "...STKOF during callee-saves register stacking\n");
8215         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
8216         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
8217                                 env->v7m.secure);
8218         *frame_sp_p = limit;
8219         return true;
8220     }
8221
8222     /* Write as much of the stack frame as we can. A write failure may
8223      * cause us to pend a derived exception.
8224      */
8225     sig = v7m_integrity_sig(env, lr);
8226     stacked_ok =
8227         v7m_stack_write(cpu, frameptr, sig, mmu_idx, smode) &&
8228         v7m_stack_write(cpu, frameptr + 0x8, env->regs[4], mmu_idx, smode) &&
8229         v7m_stack_write(cpu, frameptr + 0xc, env->regs[5], mmu_idx, smode) &&
8230         v7m_stack_write(cpu, frameptr + 0x10, env->regs[6], mmu_idx, smode) &&
8231         v7m_stack_write(cpu, frameptr + 0x14, env->regs[7], mmu_idx, smode) &&
8232         v7m_stack_write(cpu, frameptr + 0x18, env->regs[8], mmu_idx, smode) &&
8233         v7m_stack_write(cpu, frameptr + 0x1c, env->regs[9], mmu_idx, smode) &&
8234         v7m_stack_write(cpu, frameptr + 0x20, env->regs[10], mmu_idx, smode) &&
8235         v7m_stack_write(cpu, frameptr + 0x24, env->regs[11], mmu_idx, smode);
8236
8237     /* Update SP regardless of whether any of the stack accesses failed. */
8238     *frame_sp_p = frameptr;
8239
8240     return !stacked_ok;
8241 }
8242
8243 static void v7m_exception_taken(ARMCPU *cpu, uint32_t lr, bool dotailchain,
8244                                 bool ignore_stackfaults)
8245 {
8246     /* Do the "take the exception" parts of exception entry,
8247      * but not the pushing of state to the stack. This is
8248      * similar to the pseudocode ExceptionTaken() function.
8249      */
8250     CPUARMState *env = &cpu->env;
8251     uint32_t addr;
8252     bool targets_secure;
8253     int exc;
8254     bool push_failed = false;
8255
8256     armv7m_nvic_get_pending_irq_info(env->nvic, &exc, &targets_secure);
8257     qemu_log_mask(CPU_LOG_INT, "...taking pending %s exception %d\n",
8258                   targets_secure ? "secure" : "nonsecure", exc);
8259
8260     if (dotailchain) {
8261         /* Sanitize LR FType and PREFIX bits */
8262         if (!arm_feature(env, ARM_FEATURE_VFP)) {
8263             lr |= R_V7M_EXCRET_FTYPE_MASK;
8264         }
8265         lr = deposit32(lr, 24, 8, 0xff);
8266     }
8267
8268     if (arm_feature(env, ARM_FEATURE_V8)) {
8269         if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
8270             (lr & R_V7M_EXCRET_S_MASK)) {
8271             /* The background code (the owner of the registers in the
8272              * exception frame) is Secure. This means it may either already
8273              * have or now needs to push callee-saves registers.
8274              */
8275             if (targets_secure) {
8276                 if (dotailchain && !(lr & R_V7M_EXCRET_ES_MASK)) {
8277                     /* We took an exception from Secure to NonSecure
8278                      * (which means the callee-saved registers got stacked)
8279                      * and are now tailchaining to a Secure exception.
8280                      * Clear DCRS so eventual return from this Secure
8281                      * exception unstacks the callee-saved registers.
8282                      */
8283                     lr &= ~R_V7M_EXCRET_DCRS_MASK;
8284                 }
8285             } else {
8286                 /* We're going to a non-secure exception; push the
8287                  * callee-saves registers to the stack now, if they're
8288                  * not already saved.
8289                  */
8290                 if (lr & R_V7M_EXCRET_DCRS_MASK &&
8291                     !(dotailchain && !(lr & R_V7M_EXCRET_ES_MASK))) {
8292                     push_failed = v7m_push_callee_stack(cpu, lr, dotailchain,
8293                                                         ignore_stackfaults);
8294                 }
8295                 lr |= R_V7M_EXCRET_DCRS_MASK;
8296             }
8297         }
8298
8299         lr &= ~R_V7M_EXCRET_ES_MASK;
8300         if (targets_secure || !arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8301             lr |= R_V7M_EXCRET_ES_MASK;
8302         }
8303         lr &= ~R_V7M_EXCRET_SPSEL_MASK;
8304         if (env->v7m.control[targets_secure] & R_V7M_CONTROL_SPSEL_MASK) {
8305             lr |= R_V7M_EXCRET_SPSEL_MASK;
8306         }
8307
8308         /* Clear registers if necessary to prevent non-secure exception
8309          * code being able to see register values from secure code.
8310          * Where register values become architecturally UNKNOWN we leave
8311          * them with their previous values.
8312          */
8313         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8314             if (!targets_secure) {
8315                 /* Always clear the caller-saved registers (they have been
8316                  * pushed to the stack earlier in v7m_push_stack()).
8317                  * Clear callee-saved registers if the background code is
8318                  * Secure (in which case these regs were saved in
8319                  * v7m_push_callee_stack()).
8320                  */
8321                 int i;
8322
8323                 for (i = 0; i < 13; i++) {
8324                     /* r4..r11 are callee-saves, zero only if EXCRET.S == 1 */
8325                     if (i < 4 || i > 11 || (lr & R_V7M_EXCRET_S_MASK)) {
8326                         env->regs[i] = 0;
8327                     }
8328                 }
8329                 /* Clear EAPSR */
8330                 xpsr_write(env, 0, XPSR_NZCV | XPSR_Q | XPSR_GE | XPSR_IT);
8331             }
8332         }
8333     }
8334
8335     if (push_failed && !ignore_stackfaults) {
8336         /* Derived exception on callee-saves register stacking:
8337          * we might now want to take a different exception which
8338          * targets a different security state, so try again from the top.
8339          */
8340         qemu_log_mask(CPU_LOG_INT,
8341                       "...derived exception on callee-saves register stacking");
8342         v7m_exception_taken(cpu, lr, true, true);
8343         return;
8344     }
8345
8346     if (!arm_v7m_load_vector(cpu, exc, targets_secure, &addr)) {
8347         /* Vector load failed: derived exception */
8348         qemu_log_mask(CPU_LOG_INT, "...derived exception on vector table load");
8349         v7m_exception_taken(cpu, lr, true, true);
8350         return;
8351     }
8352
8353     /* Now we've done everything that might cause a derived exception
8354      * we can go ahead and activate whichever exception we're going to
8355      * take (which might now be the derived exception).
8356      */
8357     armv7m_nvic_acknowledge_irq(env->nvic);
8358
8359     /* Switch to target security state -- must do this before writing SPSEL */
8360     switch_v7m_security_state(env, targets_secure);
8361     write_v7m_control_spsel(env, 0);
8362     arm_clear_exclusive(env);
8363     /* Clear SFPA and FPCA (has no effect if no FPU) */
8364     env->v7m.control[M_REG_S] &=
8365         ~(R_V7M_CONTROL_FPCA_MASK | R_V7M_CONTROL_SFPA_MASK);
8366     /* Clear IT bits */
8367     env->condexec_bits = 0;
8368     env->regs[14] = lr;
8369     env->regs[15] = addr & 0xfffffffe;
8370     env->thumb = addr & 1;
8371 }
8372
8373 static void v7m_update_fpccr(CPUARMState *env, uint32_t frameptr,
8374                              bool apply_splim)
8375 {
8376     /*
8377      * Like the pseudocode UpdateFPCCR: save state in FPCAR and FPCCR
8378      * that we will need later in order to do lazy FP reg stacking.
8379      */
8380     bool is_secure = env->v7m.secure;
8381     void *nvic = env->nvic;
8382     /*
8383      * Some bits are unbanked and live always in fpccr[M_REG_S]; some bits
8384      * are banked and we want to update the bit in the bank for the
8385      * current security state; and in one case we want to specifically
8386      * update the NS banked version of a bit even if we are secure.
8387      */
8388     uint32_t *fpccr_s = &env->v7m.fpccr[M_REG_S];
8389     uint32_t *fpccr_ns = &env->v7m.fpccr[M_REG_NS];
8390     uint32_t *fpccr = &env->v7m.fpccr[is_secure];
8391     bool hfrdy, bfrdy, mmrdy, ns_ufrdy, s_ufrdy, sfrdy, monrdy;
8392
8393     env->v7m.fpcar[is_secure] = frameptr & ~0x7;
8394
8395     if (apply_splim && arm_feature(env, ARM_FEATURE_V8)) {
8396         bool splimviol;
8397         uint32_t splim = v7m_sp_limit(env);
8398         bool ign = armv7m_nvic_neg_prio_requested(nvic, is_secure) &&
8399             (env->v7m.ccr[is_secure] & R_V7M_CCR_STKOFHFNMIGN_MASK);
8400
8401         splimviol = !ign && frameptr < splim;
8402         *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, SPLIMVIOL, splimviol);
8403     }
8404
8405     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, LSPACT, 1);
8406
8407     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, S, is_secure);
8408
8409     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, USER, arm_current_el(env) == 0);
8410
8411     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, THREAD,
8412                         !arm_v7m_is_handler_mode(env));
8413
8414     hfrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_HARD, false);
8415     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, HFRDY, hfrdy);
8416
8417     bfrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_BUS, false);
8418     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, BFRDY, bfrdy);
8419
8420     mmrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_MEM, is_secure);
8421     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, MMRDY, mmrdy);
8422
8423     ns_ufrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_USAGE, false);
8424     *fpccr_ns = FIELD_DP32(*fpccr_ns, V7M_FPCCR, UFRDY, ns_ufrdy);
8425
8426     monrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_DEBUG, false);
8427     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, MONRDY, monrdy);
8428
8429     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8430         s_ufrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_USAGE, true);
8431         *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, UFRDY, s_ufrdy);
8432
8433         sfrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_SECURE, false);
8434         *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, SFRDY, sfrdy);
8435     }
8436 }
8437
8438 void HELPER(v7m_vlstm)(CPUARMState *env, uint32_t fptr)
8439 {
8440     /* fptr is the value of Rn, the frame pointer we store the FP regs to */
8441     bool s = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
8442     bool lspact = env->v7m.fpccr[s] & R_V7M_FPCCR_LSPACT_MASK;
8443
8444     assert(env->v7m.secure);
8445
8446     if (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)) {
8447         return;
8448     }
8449
8450     /* Check access to the coprocessor is permitted */
8451     if (!v7m_cpacr_pass(env, true, arm_current_el(env) != 0)) {
8452         raise_exception_ra(env, EXCP_NOCP, 0, 1, GETPC());
8453     }
8454
8455     if (lspact) {
8456         /* LSPACT should not be active when there is active FP state */
8457         raise_exception_ra(env, EXCP_LSERR, 0, 1, GETPC());
8458     }
8459
8460     if (fptr & 7) {
8461         raise_exception_ra(env, EXCP_UNALIGNED, 0, 1, GETPC());
8462     }
8463
8464     /*
8465      * Note that we do not use v7m_stack_write() here, because the
8466      * accesses should not set the FSR bits for stacking errors if they
8467      * fail. (In pseudocode terms, they are AccType_NORMAL, not AccType_STACK
8468      * or AccType_LAZYFP). Faults in cpu_stl_data() will throw exceptions
8469      * and longjmp out.
8470      */
8471     if (!(env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPEN_MASK)) {
8472         bool ts = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK;
8473         int i;
8474
8475         for (i = 0; i < (ts ? 32 : 16); i += 2) {
8476             uint64_t dn = *aa32_vfp_dreg(env, i / 2);
8477             uint32_t faddr = fptr + 4 * i;
8478             uint32_t slo = extract64(dn, 0, 32);
8479             uint32_t shi = extract64(dn, 32, 32);
8480
8481             if (i >= 16) {
8482                 faddr += 8; /* skip the slot for the FPSCR */
8483             }
8484             cpu_stl_data(env, faddr, slo);
8485             cpu_stl_data(env, faddr + 4, shi);
8486         }
8487         cpu_stl_data(env, fptr + 0x40, vfp_get_fpscr(env));
8488
8489         /*
8490          * If TS is 0 then s0 to s15 and FPSCR are UNKNOWN; we choose to
8491          * leave them unchanged, matching our choice in v7m_preserve_fp_state.
8492          */
8493         if (ts) {
8494             for (i = 0; i < 32; i += 2) {
8495                 *aa32_vfp_dreg(env, i / 2) = 0;
8496             }
8497             vfp_set_fpscr(env, 0);
8498         }
8499     } else {
8500         v7m_update_fpccr(env, fptr, false);
8501     }
8502
8503     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_FPCA_MASK;
8504 }
8505
8506 void HELPER(v7m_vlldm)(CPUARMState *env, uint32_t fptr)
8507 {
8508     /* fptr is the value of Rn, the frame pointer we load the FP regs from */
8509     assert(env->v7m.secure);
8510
8511     if (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)) {
8512         return;
8513     }
8514
8515     /* Check access to the coprocessor is permitted */
8516     if (!v7m_cpacr_pass(env, true, arm_current_el(env) != 0)) {
8517         raise_exception_ra(env, EXCP_NOCP, 0, 1, GETPC());
8518     }
8519
8520     if (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPACT_MASK) {
8521         /* State in FP is still valid */
8522         env->v7m.fpccr[M_REG_S] &= ~R_V7M_FPCCR_LSPACT_MASK;
8523     } else {
8524         bool ts = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK;
8525         int i;
8526         uint32_t fpscr;
8527
8528         if (fptr & 7) {
8529             raise_exception_ra(env, EXCP_UNALIGNED, 0, 1, GETPC());
8530         }
8531
8532         for (i = 0; i < (ts ? 32 : 16); i += 2) {
8533             uint32_t slo, shi;
8534             uint64_t dn;
8535             uint32_t faddr = fptr + 4 * i;
8536
8537             if (i >= 16) {
8538                 faddr += 8; /* skip the slot for the FPSCR */
8539             }
8540
8541             slo = cpu_ldl_data(env, faddr);
8542             shi = cpu_ldl_data(env, faddr + 4);
8543
8544             dn = (uint64_t) shi << 32 | slo;
8545             *aa32_vfp_dreg(env, i / 2) = dn;
8546         }
8547         fpscr = cpu_ldl_data(env, fptr + 0x40);
8548         vfp_set_fpscr(env, fpscr);
8549     }
8550
8551     env->v7m.control[M_REG_S] |= R_V7M_CONTROL_FPCA_MASK;
8552 }
8553
8554 static bool v7m_push_stack(ARMCPU *cpu)
8555 {
8556     /* Do the "set up stack frame" part of exception entry,
8557      * similar to pseudocode PushStack().
8558      * Return true if we generate a derived exception (and so
8559      * should ignore further stack faults trying to process
8560      * that derived exception.)
8561      */
8562     bool stacked_ok = true, limitviol = false;
8563     CPUARMState *env = &cpu->env;
8564     uint32_t xpsr = xpsr_read(env);
8565     uint32_t frameptr = env->regs[13];
8566     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
8567     uint32_t framesize;
8568     bool nsacr_cp10 = extract32(env->v7m.nsacr, 10, 1);
8569
8570     if ((env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) &&
8571         (env->v7m.secure || nsacr_cp10)) {
8572         if (env->v7m.secure &&
8573             env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK) {
8574             framesize = 0xa8;
8575         } else {
8576             framesize = 0x68;
8577         }
8578     } else {
8579         framesize = 0x20;
8580     }
8581
8582     /* Align stack pointer if the guest wants that */
8583     if ((frameptr & 4) &&
8584         (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKALIGN_MASK)) {
8585         frameptr -= 4;
8586         xpsr |= XPSR_SPREALIGN;
8587     }
8588
8589     xpsr &= ~XPSR_SFPA;
8590     if (env->v7m.secure &&
8591         (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)) {
8592         xpsr |= XPSR_SFPA;
8593     }
8594
8595     frameptr -= framesize;
8596
8597     if (arm_feature(env, ARM_FEATURE_V8)) {
8598         uint32_t limit = v7m_sp_limit(env);
8599
8600         if (frameptr < limit) {
8601             /*
8602              * Stack limit failure: set SP to the limit value, and generate
8603              * STKOF UsageFault. Stack pushes below the limit must not be
8604              * performed. It is IMPDEF whether pushes above the limit are
8605              * performed; we choose not to.
8606              */
8607             qemu_log_mask(CPU_LOG_INT,
8608                           "...STKOF during stacking\n");
8609             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
8610             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
8611                                     env->v7m.secure);
8612             env->regs[13] = limit;
8613             /*
8614              * We won't try to perform any further memory accesses but
8615              * we must continue through the following code to check for
8616              * permission faults during FPU state preservation, and we
8617              * must update FPCCR if lazy stacking is enabled.
8618              */
8619             limitviol = true;
8620             stacked_ok = false;
8621         }
8622     }
8623
8624     /* Write as much of the stack frame as we can. If we fail a stack
8625      * write this will result in a derived exception being pended
8626      * (which may be taken in preference to the one we started with
8627      * if it has higher priority).
8628      */
8629     stacked_ok = stacked_ok &&
8630         v7m_stack_write(cpu, frameptr, env->regs[0], mmu_idx, STACK_NORMAL) &&
8631         v7m_stack_write(cpu, frameptr + 4, env->regs[1],
8632                         mmu_idx, STACK_NORMAL) &&
8633         v7m_stack_write(cpu, frameptr + 8, env->regs[2],
8634                         mmu_idx, STACK_NORMAL) &&
8635         v7m_stack_write(cpu, frameptr + 12, env->regs[3],
8636                         mmu_idx, STACK_NORMAL) &&
8637         v7m_stack_write(cpu, frameptr + 16, env->regs[12],
8638                         mmu_idx, STACK_NORMAL) &&
8639         v7m_stack_write(cpu, frameptr + 20, env->regs[14],
8640                         mmu_idx, STACK_NORMAL) &&
8641         v7m_stack_write(cpu, frameptr + 24, env->regs[15],
8642                         mmu_idx, STACK_NORMAL) &&
8643         v7m_stack_write(cpu, frameptr + 28, xpsr, mmu_idx, STACK_NORMAL);
8644
8645     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) {
8646         /* FPU is active, try to save its registers */
8647         bool fpccr_s = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
8648         bool lspact = env->v7m.fpccr[fpccr_s] & R_V7M_FPCCR_LSPACT_MASK;
8649
8650         if (lspact && arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8651             qemu_log_mask(CPU_LOG_INT,
8652                           "...SecureFault because LSPACT and FPCA both set\n");
8653             env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
8654             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
8655         } else if (!env->v7m.secure && !nsacr_cp10) {
8656             qemu_log_mask(CPU_LOG_INT,
8657                           "...Secure UsageFault with CFSR.NOCP because "
8658                           "NSACR.CP10 prevents stacking FP regs\n");
8659             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, M_REG_S);
8660             env->v7m.cfsr[M_REG_S] |= R_V7M_CFSR_NOCP_MASK;
8661         } else {
8662             if (!(env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPEN_MASK)) {
8663                 /* Lazy stacking disabled, save registers now */
8664                 int i;
8665                 bool cpacr_pass = v7m_cpacr_pass(env, env->v7m.secure,
8666                                                  arm_current_el(env) != 0);
8667
8668                 if (stacked_ok && !cpacr_pass) {
8669                     /*
8670                      * Take UsageFault if CPACR forbids access. The pseudocode
8671                      * here does a full CheckCPEnabled() but we know the NSACR
8672                      * check can never fail as we have already handled that.
8673                      */
8674                     qemu_log_mask(CPU_LOG_INT,
8675                                   "...UsageFault with CFSR.NOCP because "
8676                                   "CPACR.CP10 prevents stacking FP regs\n");
8677                     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
8678                                             env->v7m.secure);
8679                     env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;
8680                     stacked_ok = false;
8681                 }
8682
8683                 for (i = 0; i < ((framesize == 0xa8) ? 32 : 16); i += 2) {
8684                     uint64_t dn = *aa32_vfp_dreg(env, i / 2);
8685                     uint32_t faddr = frameptr + 0x20 + 4 * i;
8686                     uint32_t slo = extract64(dn, 0, 32);
8687                     uint32_t shi = extract64(dn, 32, 32);
8688
8689                     if (i >= 16) {
8690                         faddr += 8; /* skip the slot for the FPSCR */
8691                     }
8692                     stacked_ok = stacked_ok &&
8693                         v7m_stack_write(cpu, faddr, slo,
8694                                         mmu_idx, STACK_NORMAL) &&
8695                         v7m_stack_write(cpu, faddr + 4, shi,
8696                                         mmu_idx, STACK_NORMAL);
8697                 }
8698                 stacked_ok = stacked_ok &&
8699                     v7m_stack_write(cpu, frameptr + 0x60,
8700                                     vfp_get_fpscr(env), mmu_idx, STACK_NORMAL);
8701                 if (cpacr_pass) {
8702                     for (i = 0; i < ((framesize == 0xa8) ? 32 : 16); i += 2) {
8703                         *aa32_vfp_dreg(env, i / 2) = 0;
8704                     }
8705                     vfp_set_fpscr(env, 0);
8706                 }
8707             } else {
8708                 /* Lazy stacking enabled, save necessary info to stack later */
8709                 v7m_update_fpccr(env, frameptr + 0x20, true);
8710             }
8711         }
8712     }
8713
8714     /*
8715      * If we broke a stack limit then SP was already updated earlier;
8716      * otherwise we update SP regardless of whether any of the stack
8717      * accesses failed or we took some other kind of fault.
8718      */
8719     if (!limitviol) {
8720         env->regs[13] = frameptr;
8721     }
8722
8723     return !stacked_ok;
8724 }
8725
8726 static void do_v7m_exception_exit(ARMCPU *cpu)
8727 {
8728     CPUARMState *env = &cpu->env;
8729     uint32_t excret;
8730     uint32_t xpsr, xpsr_mask;
8731     bool ufault = false;
8732     bool sfault = false;
8733     bool return_to_sp_process;
8734     bool return_to_handler;
8735     bool rettobase = false;
8736     bool exc_secure = false;
8737     bool return_to_secure;
8738     bool ftype;
8739     bool restore_s16_s31;
8740
8741     /* If we're not in Handler mode then jumps to magic exception-exit
8742      * addresses don't have magic behaviour. However for the v8M
8743      * security extensions the magic secure-function-return has to
8744      * work in thread mode too, so to avoid doing an extra check in
8745      * the generated code we allow exception-exit magic to also cause the
8746      * internal exception and bring us here in thread mode. Correct code
8747      * will never try to do this (the following insn fetch will always
8748      * fault) so we the overhead of having taken an unnecessary exception
8749      * doesn't matter.
8750      */
8751     if (!arm_v7m_is_handler_mode(env)) {
8752         return;
8753     }
8754
8755     /* In the spec pseudocode ExceptionReturn() is called directly
8756      * from BXWritePC() and gets the full target PC value including
8757      * bit zero. In QEMU's implementation we treat it as a normal
8758      * jump-to-register (which is then caught later on), and so split
8759      * the target value up between env->regs[15] and env->thumb in
8760      * gen_bx(). Reconstitute it.
8761      */
8762     excret = env->regs[15];
8763     if (env->thumb) {
8764         excret |= 1;
8765     }
8766
8767     qemu_log_mask(CPU_LOG_INT, "Exception return: magic PC %" PRIx32
8768                   " previous exception %d\n",
8769                   excret, env->v7m.exception);
8770
8771     if ((excret & R_V7M_EXCRET_RES1_MASK) != R_V7M_EXCRET_RES1_MASK) {
8772         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero high bits in exception "
8773                       "exit PC value 0x%" PRIx32 " are UNPREDICTABLE\n",
8774                       excret);
8775     }
8776
8777     ftype = excret & R_V7M_EXCRET_FTYPE_MASK;
8778
8779     if (!arm_feature(env, ARM_FEATURE_VFP) && !ftype) {
8780         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero FTYPE in exception "
8781                       "exit PC value 0x%" PRIx32 " is UNPREDICTABLE "
8782                       "if FPU not present\n",
8783                       excret);
8784         ftype = true;
8785     }
8786
8787     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8788         /* EXC_RETURN.ES validation check (R_SMFL). We must do this before
8789          * we pick which FAULTMASK to clear.
8790          */
8791         if (!env->v7m.secure &&
8792             ((excret & R_V7M_EXCRET_ES_MASK) ||
8793              !(excret & R_V7M_EXCRET_DCRS_MASK))) {
8794             sfault = 1;
8795             /* For all other purposes, treat ES as 0 (R_HXSR) */
8796             excret &= ~R_V7M_EXCRET_ES_MASK;
8797         }
8798         exc_secure = excret & R_V7M_EXCRET_ES_MASK;
8799     }
8800
8801     if (env->v7m.exception != ARMV7M_EXCP_NMI) {
8802         /* Auto-clear FAULTMASK on return from other than NMI.
8803          * If the security extension is implemented then this only
8804          * happens if the raw execution priority is >= 0; the
8805          * value of the ES bit in the exception return value indicates
8806          * which security state's faultmask to clear. (v8M ARM ARM R_KBNF.)
8807          */
8808         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8809             if (armv7m_nvic_raw_execution_priority(env->nvic) >= 0) {
8810                 env->v7m.faultmask[exc_secure] = 0;
8811             }
8812         } else {
8813             env->v7m.faultmask[M_REG_NS] = 0;
8814         }
8815     }
8816
8817     switch (armv7m_nvic_complete_irq(env->nvic, env->v7m.exception,
8818                                      exc_secure)) {
8819     case -1:
8820         /* attempt to exit an exception that isn't active */
8821         ufault = true;
8822         break;
8823     case 0:
8824         /* still an irq active now */
8825         break;
8826     case 1:
8827         /* we returned to base exception level, no nesting.
8828          * (In the pseudocode this is written using "NestedActivation != 1"
8829          * where we have 'rettobase == false'.)
8830          */
8831         rettobase = true;
8832         break;
8833     default:
8834         g_assert_not_reached();
8835     }
8836
8837     return_to_handler = !(excret & R_V7M_EXCRET_MODE_MASK);
8838     return_to_sp_process = excret & R_V7M_EXCRET_SPSEL_MASK;
8839     return_to_secure = arm_feature(env, ARM_FEATURE_M_SECURITY) &&
8840         (excret & R_V7M_EXCRET_S_MASK);
8841
8842     if (arm_feature(env, ARM_FEATURE_V8)) {
8843         if (!arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8844             /* UNPREDICTABLE if S == 1 or DCRS == 0 or ES == 1 (R_XLCP);
8845              * we choose to take the UsageFault.
8846              */
8847             if ((excret & R_V7M_EXCRET_S_MASK) ||
8848                 (excret & R_V7M_EXCRET_ES_MASK) ||
8849                 !(excret & R_V7M_EXCRET_DCRS_MASK)) {
8850                 ufault = true;
8851             }
8852         }
8853         if (excret & R_V7M_EXCRET_RES0_MASK) {
8854             ufault = true;
8855         }
8856     } else {
8857         /* For v7M we only recognize certain combinations of the low bits */
8858         switch (excret & 0xf) {
8859         case 1: /* Return to Handler */
8860             break;
8861         case 13: /* Return to Thread using Process stack */
8862         case 9: /* Return to Thread using Main stack */
8863             /* We only need to check NONBASETHRDENA for v7M, because in
8864              * v8M this bit does not exist (it is RES1).
8865              */
8866             if (!rettobase &&
8867                 !(env->v7m.ccr[env->v7m.secure] &
8868                   R_V7M_CCR_NONBASETHRDENA_MASK)) {
8869                 ufault = true;
8870             }
8871             break;
8872         default:
8873             ufault = true;
8874         }
8875     }
8876
8877     /*
8878      * Set CONTROL.SPSEL from excret.SPSEL. Since we're still in
8879      * Handler mode (and will be until we write the new XPSR.Interrupt
8880      * field) this does not switch around the current stack pointer.
8881      * We must do this before we do any kind of tailchaining, including
8882      * for the derived exceptions on integrity check failures, or we will
8883      * give the guest an incorrect EXCRET.SPSEL value on exception entry.
8884      */
8885     write_v7m_control_spsel_for_secstate(env, return_to_sp_process, exc_secure);
8886
8887     /*
8888      * Clear scratch FP values left in caller saved registers; this
8889      * must happen before any kind of tail chaining.
8890      */
8891     if ((env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_CLRONRET_MASK) &&
8892         (env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK)) {
8893         if (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPACT_MASK) {
8894             env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
8895             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
8896             qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
8897                           "stackframe: error during lazy state deactivation\n");
8898             v7m_exception_taken(cpu, excret, true, false);
8899             return;
8900         } else {
8901             /* Clear s0..s15 and FPSCR */
8902             int i;
8903
8904             for (i = 0; i < 16; i += 2) {
8905                 *aa32_vfp_dreg(env, i / 2) = 0;
8906             }
8907             vfp_set_fpscr(env, 0);
8908         }
8909     }
8910
8911     if (sfault) {
8912         env->v7m.sfsr |= R_V7M_SFSR_INVER_MASK;
8913         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
8914         qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
8915                       "stackframe: failed EXC_RETURN.ES validity check\n");
8916         v7m_exception_taken(cpu, excret, true, false);
8917         return;
8918     }
8919
8920     if (ufault) {
8921         /* Bad exception return: instead of popping the exception
8922          * stack, directly take a usage fault on the current stack.
8923          */
8924         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
8925         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
8926         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
8927                       "stackframe: failed exception return integrity check\n");
8928         v7m_exception_taken(cpu, excret, true, false);
8929         return;
8930     }
8931
8932     /*
8933      * Tailchaining: if there is currently a pending exception that
8934      * is high enough priority to preempt execution at the level we're
8935      * about to return to, then just directly take that exception now,
8936      * avoiding an unstack-and-then-stack. Note that now we have
8937      * deactivated the previous exception by calling armv7m_nvic_complete_irq()
8938      * our current execution priority is already the execution priority we are
8939      * returning to -- none of the state we would unstack or set based on
8940      * the EXCRET value affects it.
8941      */
8942     if (armv7m_nvic_can_take_pending_exception(env->nvic)) {
8943         qemu_log_mask(CPU_LOG_INT, "...tailchaining to pending exception\n");
8944         v7m_exception_taken(cpu, excret, true, false);
8945         return;
8946     }
8947
8948     switch_v7m_security_state(env, return_to_secure);
8949
8950     {
8951         /* The stack pointer we should be reading the exception frame from
8952          * depends on bits in the magic exception return type value (and
8953          * for v8M isn't necessarily the stack pointer we will eventually
8954          * end up resuming execution with). Get a pointer to the location
8955          * in the CPU state struct where the SP we need is currently being
8956          * stored; we will use and modify it in place.
8957          * We use this limited C variable scope so we don't accidentally
8958          * use 'frame_sp_p' after we do something that makes it invalid.
8959          */
8960         uint32_t *frame_sp_p = get_v7m_sp_ptr(env,
8961                                               return_to_secure,
8962                                               !return_to_handler,
8963                                               return_to_sp_process);
8964         uint32_t frameptr = *frame_sp_p;
8965         bool pop_ok = true;
8966         ARMMMUIdx mmu_idx;
8967         bool return_to_priv = return_to_handler ||
8968             !(env->v7m.control[return_to_secure] & R_V7M_CONTROL_NPRIV_MASK);
8969
8970         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, return_to_secure,
8971                                                         return_to_priv);
8972
8973         if (!QEMU_IS_ALIGNED(frameptr, 8) &&
8974             arm_feature(env, ARM_FEATURE_V8)) {
8975             qemu_log_mask(LOG_GUEST_ERROR,
8976                           "M profile exception return with non-8-aligned SP "
8977                           "for destination state is UNPREDICTABLE\n");
8978         }
8979
8980         /* Do we need to pop callee-saved registers? */
8981         if (return_to_secure &&
8982             ((excret & R_V7M_EXCRET_ES_MASK) == 0 ||
8983              (excret & R_V7M_EXCRET_DCRS_MASK) == 0)) {
8984             uint32_t actual_sig;
8985
8986             pop_ok = v7m_stack_read(cpu, &actual_sig, frameptr, mmu_idx);
8987
8988             if (pop_ok && v7m_integrity_sig(env, excret) != actual_sig) {
8989                 /* Take a SecureFault on the current stack */
8990                 env->v7m.sfsr |= R_V7M_SFSR_INVIS_MASK;
8991                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
8992                 qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
8993                               "stackframe: failed exception return integrity "
8994                               "signature check\n");
8995                 v7m_exception_taken(cpu, excret, true, false);
8996                 return;
8997             }
8998
8999             pop_ok = pop_ok &&
9000                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
9001                 v7m_stack_read(cpu, &env->regs[5], frameptr + 0xc, mmu_idx) &&
9002                 v7m_stack_read(cpu, &env->regs[6], frameptr + 0x10, mmu_idx) &&
9003                 v7m_stack_read(cpu, &env->regs[7], frameptr + 0x14, mmu_idx) &&
9004                 v7m_stack_read(cpu, &env->regs[8], frameptr + 0x18, mmu_idx) &&
9005                 v7m_stack_read(cpu, &env->regs[9], frameptr + 0x1c, mmu_idx) &&
9006                 v7m_stack_read(cpu, &env->regs[10], frameptr + 0x20, mmu_idx) &&
9007                 v7m_stack_read(cpu, &env->regs[11], frameptr + 0x24, mmu_idx);
9008
9009             frameptr += 0x28;
9010         }
9011
9012         /* Pop registers */
9013         pop_ok = pop_ok &&
9014             v7m_stack_read(cpu, &env->regs[0], frameptr, mmu_idx) &&
9015             v7m_stack_read(cpu, &env->regs[1], frameptr + 0x4, mmu_idx) &&
9016             v7m_stack_read(cpu, &env->regs[2], frameptr + 0x8, mmu_idx) &&
9017             v7m_stack_read(cpu, &env->regs[3], frameptr + 0xc, mmu_idx) &&
9018             v7m_stack_read(cpu, &env->regs[12], frameptr + 0x10, mmu_idx) &&
9019             v7m_stack_read(cpu, &env->regs[14], frameptr + 0x14, mmu_idx) &&
9020             v7m_stack_read(cpu, &env->regs[15], frameptr + 0x18, mmu_idx) &&
9021             v7m_stack_read(cpu, &xpsr, frameptr + 0x1c, mmu_idx);
9022
9023         if (!pop_ok) {
9024             /* v7m_stack_read() pended a fault, so take it (as a tail
9025              * chained exception on the same stack frame)
9026              */
9027             qemu_log_mask(CPU_LOG_INT, "...derived exception on unstacking\n");
9028             v7m_exception_taken(cpu, excret, true, false);
9029             return;
9030         }
9031
9032         /* Returning from an exception with a PC with bit 0 set is defined
9033          * behaviour on v8M (bit 0 is ignored), but for v7M it was specified
9034          * to be UNPREDICTABLE. In practice actual v7M hardware seems to ignore
9035          * the lsbit, and there are several RTOSes out there which incorrectly
9036          * assume the r15 in the stack frame should be a Thumb-style "lsbit
9037          * indicates ARM/Thumb" value, so ignore the bit on v7M as well, but
9038          * complain about the badly behaved guest.
9039          */
9040         if (env->regs[15] & 1) {
9041             env->regs[15] &= ~1U;
9042             if (!arm_feature(env, ARM_FEATURE_V8)) {
9043                 qemu_log_mask(LOG_GUEST_ERROR,
9044                               "M profile return from interrupt with misaligned "
9045                               "PC is UNPREDICTABLE on v7M\n");
9046             }
9047         }
9048
9049         if (arm_feature(env, ARM_FEATURE_V8)) {
9050             /* For v8M we have to check whether the xPSR exception field
9051              * matches the EXCRET value for return to handler/thread
9052              * before we commit to changing the SP and xPSR.
9053              */
9054             bool will_be_handler = (xpsr & XPSR_EXCP) != 0;
9055             if (return_to_handler != will_be_handler) {
9056                 /* Take an INVPC UsageFault on the current stack.
9057                  * By this point we will have switched to the security state
9058                  * for the background state, so this UsageFault will target
9059                  * that state.
9060                  */
9061                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
9062                                         env->v7m.secure);
9063                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9064                 qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
9065                               "stackframe: failed exception return integrity "
9066                               "check\n");
9067                 v7m_exception_taken(cpu, excret, true, false);
9068                 return;
9069             }
9070         }
9071
9072         if (!ftype) {
9073             /* FP present and we need to handle it */
9074             if (!return_to_secure &&
9075                 (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPACT_MASK)) {
9076                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9077                 env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
9078                 qemu_log_mask(CPU_LOG_INT,
9079                               "...taking SecureFault on existing stackframe: "
9080                               "Secure LSPACT set but exception return is "
9081                               "not to secure state\n");
9082                 v7m_exception_taken(cpu, excret, true, false);
9083                 return;
9084             }
9085
9086             restore_s16_s31 = return_to_secure &&
9087                 (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK);
9088
9089             if (env->v7m.fpccr[return_to_secure] & R_V7M_FPCCR_LSPACT_MASK) {
9090                 /* State in FPU is still valid, just clear LSPACT */
9091                 env->v7m.fpccr[return_to_secure] &= ~R_V7M_FPCCR_LSPACT_MASK;
9092             } else {
9093                 int i;
9094                 uint32_t fpscr;
9095                 bool cpacr_pass, nsacr_pass;
9096
9097                 cpacr_pass = v7m_cpacr_pass(env, return_to_secure,
9098                                             return_to_priv);
9099                 nsacr_pass = return_to_secure ||
9100                     extract32(env->v7m.nsacr, 10, 1);
9101
9102                 if (!cpacr_pass) {
9103                     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
9104                                             return_to_secure);
9105                     env->v7m.cfsr[return_to_secure] |= R_V7M_CFSR_NOCP_MASK;
9106                     qemu_log_mask(CPU_LOG_INT,
9107                                   "...taking UsageFault on existing "
9108                                   "stackframe: CPACR.CP10 prevents unstacking "
9109                                   "FP regs\n");
9110                     v7m_exception_taken(cpu, excret, true, false);
9111                     return;
9112                 } else if (!nsacr_pass) {
9113                     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, true);
9114                     env->v7m.cfsr[M_REG_S] |= R_V7M_CFSR_INVPC_MASK;
9115                     qemu_log_mask(CPU_LOG_INT,
9116                                   "...taking Secure UsageFault on existing "
9117                                   "stackframe: NSACR.CP10 prevents unstacking "
9118                                   "FP regs\n");
9119                     v7m_exception_taken(cpu, excret, true, false);
9120                     return;
9121                 }
9122
9123                 for (i = 0; i < (restore_s16_s31 ? 32 : 16); i += 2) {
9124                     uint32_t slo, shi;
9125                     uint64_t dn;
9126                     uint32_t faddr = frameptr + 0x20 + 4 * i;
9127
9128                     if (i >= 16) {
9129                         faddr += 8; /* Skip the slot for the FPSCR */
9130                     }
9131
9132                     pop_ok = pop_ok &&
9133                         v7m_stack_read(cpu, &slo, faddr, mmu_idx) &&
9134                         v7m_stack_read(cpu, &shi, faddr + 4, mmu_idx);
9135
9136                     if (!pop_ok) {
9137                         break;
9138                     }
9139
9140                     dn = (uint64_t)shi << 32 | slo;
9141                     *aa32_vfp_dreg(env, i / 2) = dn;
9142                 }
9143                 pop_ok = pop_ok &&
9144                     v7m_stack_read(cpu, &fpscr, frameptr + 0x60, mmu_idx);
9145                 if (pop_ok) {
9146                     vfp_set_fpscr(env, fpscr);
9147                 }
9148                 if (!pop_ok) {
9149                     /*
9150                      * These regs are 0 if security extension present;
9151                      * otherwise merely UNKNOWN. We zero always.
9152                      */
9153                     for (i = 0; i < (restore_s16_s31 ? 32 : 16); i += 2) {
9154                         *aa32_vfp_dreg(env, i / 2) = 0;
9155                     }
9156                     vfp_set_fpscr(env, 0);
9157                 }
9158             }
9159         }
9160         env->v7m.control[M_REG_S] = FIELD_DP32(env->v7m.control[M_REG_S],
9161                                                V7M_CONTROL, FPCA, !ftype);
9162
9163         /* Commit to consuming the stack frame */
9164         frameptr += 0x20;
9165         if (!ftype) {
9166             frameptr += 0x48;
9167             if (restore_s16_s31) {
9168                 frameptr += 0x40;
9169             }
9170         }
9171         /* Undo stack alignment (the SPREALIGN bit indicates that the original
9172          * pre-exception SP was not 8-aligned and we added a padding word to
9173          * align it, so we undo this by ORing in the bit that increases it
9174          * from the current 8-aligned value to the 8-unaligned value. (Adding 4
9175          * would work too but a logical OR is how the pseudocode specifies it.)
9176          */
9177         if (xpsr & XPSR_SPREALIGN) {
9178             frameptr |= 4;
9179         }
9180         *frame_sp_p = frameptr;
9181     }
9182
9183     xpsr_mask = ~(XPSR_SPREALIGN | XPSR_SFPA);
9184     if (!arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
9185         xpsr_mask &= ~XPSR_GE;
9186     }
9187     /* This xpsr_write() will invalidate frame_sp_p as it may switch stack */
9188     xpsr_write(env, xpsr, xpsr_mask);
9189
9190     if (env->v7m.secure) {
9191         bool sfpa = xpsr & XPSR_SFPA;
9192
9193         env->v7m.control[M_REG_S] = FIELD_DP32(env->v7m.control[M_REG_S],
9194                                                V7M_CONTROL, SFPA, sfpa);
9195     }
9196
9197     /* The restored xPSR exception field will be zero if we're
9198      * resuming in Thread mode. If that doesn't match what the
9199      * exception return excret specified then this is a UsageFault.
9200      * v7M requires we make this check here; v8M did it earlier.
9201      */
9202     if (return_to_handler != arm_v7m_is_handler_mode(env)) {
9203         /* Take an INVPC UsageFault by pushing the stack again;
9204          * we know we're v7M so this is never a Secure UsageFault.
9205          */
9206         bool ignore_stackfaults;
9207
9208         assert(!arm_feature(env, ARM_FEATURE_V8));
9209         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, false);
9210         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9211         ignore_stackfaults = v7m_push_stack(cpu);
9212         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on new stackframe: "
9213                       "failed exception return integrity check\n");
9214         v7m_exception_taken(cpu, excret, false, ignore_stackfaults);
9215         return;
9216     }
9217
9218     /* Otherwise, we have a successful exception exit. */
9219     arm_clear_exclusive(env);
9220     qemu_log_mask(CPU_LOG_INT, "...successful exception return\n");
9221 }
9222
9223 static bool do_v7m_function_return(ARMCPU *cpu)
9224 {
9225     /* v8M security extensions magic function return.
9226      * We may either:
9227      *  (1) throw an exception (longjump)
9228      *  (2) return true if we successfully handled the function return
9229      *  (3) return false if we failed a consistency check and have
9230      *      pended a UsageFault that needs to be taken now
9231      *
9232      * At this point the magic return value is split between env->regs[15]
9233      * and env->thumb. We don't bother to reconstitute it because we don't
9234      * need it (all values are handled the same way).
9235      */
9236     CPUARMState *env = &cpu->env;
9237     uint32_t newpc, newpsr, newpsr_exc;
9238
9239     qemu_log_mask(CPU_LOG_INT, "...really v7M secure function return\n");
9240
9241     {
9242         bool threadmode, spsel;
9243         TCGMemOpIdx oi;
9244         ARMMMUIdx mmu_idx;
9245         uint32_t *frame_sp_p;
9246         uint32_t frameptr;
9247
9248         /* Pull the return address and IPSR from the Secure stack */
9249         threadmode = !arm_v7m_is_handler_mode(env);
9250         spsel = env->v7m.control[M_REG_S] & R_V7M_CONTROL_SPSEL_MASK;
9251
9252         frame_sp_p = get_v7m_sp_ptr(env, true, threadmode, spsel);
9253         frameptr = *frame_sp_p;
9254
9255         /* These loads may throw an exception (for MPU faults). We want to
9256          * do them as secure, so work out what MMU index that is.
9257          */
9258         mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
9259         oi = make_memop_idx(MO_LE, arm_to_core_mmu_idx(mmu_idx));
9260         newpc = helper_le_ldul_mmu(env, frameptr, oi, 0);
9261         newpsr = helper_le_ldul_mmu(env, frameptr + 4, oi, 0);
9262
9263         /* Consistency checks on new IPSR */
9264         newpsr_exc = newpsr & XPSR_EXCP;
9265         if (!((env->v7m.exception == 0 && newpsr_exc == 0) ||
9266               (env->v7m.exception == 1 && newpsr_exc != 0))) {
9267             /* Pend the fault and tell our caller to take it */
9268             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9269             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
9270                                     env->v7m.secure);
9271             qemu_log_mask(CPU_LOG_INT,
9272                           "...taking INVPC UsageFault: "
9273                           "IPSR consistency check failed\n");
9274             return false;
9275         }
9276
9277         *frame_sp_p = frameptr + 8;
9278     }
9279
9280     /* This invalidates frame_sp_p */
9281     switch_v7m_security_state(env, true);
9282     env->v7m.exception = newpsr_exc;
9283     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
9284     if (newpsr & XPSR_SFPA) {
9285         env->v7m.control[M_REG_S] |= R_V7M_CONTROL_SFPA_MASK;
9286     }
9287     xpsr_write(env, 0, XPSR_IT);
9288     env->thumb = newpc & 1;
9289     env->regs[15] = newpc & ~1;
9290
9291     qemu_log_mask(CPU_LOG_INT, "...function return successful\n");
9292     return true;
9293 }
9294
9295 static void arm_log_exception(int idx)
9296 {
9297     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9298         const char *exc = NULL;
9299         static const char * const excnames[] = {
9300             [EXCP_UDEF] = "Undefined Instruction",
9301             [EXCP_SWI] = "SVC",
9302             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9303             [EXCP_DATA_ABORT] = "Data Abort",
9304             [EXCP_IRQ] = "IRQ",
9305             [EXCP_FIQ] = "FIQ",
9306             [EXCP_BKPT] = "Breakpoint",
9307             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9308             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9309             [EXCP_HVC] = "Hypervisor Call",
9310             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9311             [EXCP_SMC] = "Secure Monitor Call",
9312             [EXCP_VIRQ] = "Virtual IRQ",
9313             [EXCP_VFIQ] = "Virtual FIQ",
9314             [EXCP_SEMIHOST] = "Semihosting call",
9315             [EXCP_NOCP] = "v7M NOCP UsageFault",
9316             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9317             [EXCP_STKOF] = "v8M STKOF UsageFault",
9318             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9319             [EXCP_LSERR] = "v8M LSERR UsageFault",
9320             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9321         };
9322
9323         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9324             exc = excnames[idx];
9325         }
9326         if (!exc) {
9327             exc = "unknown";
9328         }
9329         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
9330     }
9331 }
9332
9333 static bool v7m_read_half_insn(ARMCPU *cpu, ARMMMUIdx mmu_idx,
9334                                uint32_t addr, uint16_t *insn)
9335 {
9336     /* Load a 16-bit portion of a v7M instruction, returning true on success,
9337      * or false on failure (in which case we will have pended the appropriate
9338      * exception).
9339      * We need to do the instruction fetch's MPU and SAU checks
9340      * like this because there is no MMU index that would allow
9341      * doing the load with a single function call. Instead we must
9342      * first check that the security attributes permit the load
9343      * and that they don't mismatch on the two halves of the instruction,
9344      * and then we do the load as a secure load (ie using the security
9345      * attributes of the address, not the CPU, as architecturally required).
9346      */
9347     CPUState *cs = CPU(cpu);
9348     CPUARMState *env = &cpu->env;
9349     V8M_SAttributes sattrs = {};
9350     MemTxAttrs attrs = {};
9351     ARMMMUFaultInfo fi = {};
9352     MemTxResult txres;
9353     target_ulong page_size;
9354     hwaddr physaddr;
9355     int prot;
9356
9357     v8m_security_lookup(env, addr, MMU_INST_FETCH, mmu_idx, &sattrs);
9358     if (!sattrs.nsc || sattrs.ns) {
9359         /* This must be the second half of the insn, and it straddles a
9360          * region boundary with the second half not being S&NSC.
9361          */
9362         env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
9363         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9364         qemu_log_mask(CPU_LOG_INT,
9365                       "...really SecureFault with SFSR.INVEP\n");
9366         return false;
9367     }
9368     if (get_phys_addr(env, addr, MMU_INST_FETCH, mmu_idx,
9369                       &physaddr, &attrs, &prot, &page_size, &fi, NULL)) {
9370         /* the MPU lookup failed */
9371         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
9372         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM, env->v7m.secure);
9373         qemu_log_mask(CPU_LOG_INT, "...really MemManage with CFSR.IACCVIOL\n");
9374         return false;
9375     }
9376     *insn = address_space_lduw_le(arm_addressspace(cs, attrs), physaddr,
9377                                  attrs, &txres);
9378     if (txres != MEMTX_OK) {
9379         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
9380         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
9381         qemu_log_mask(CPU_LOG_INT, "...really BusFault with CFSR.IBUSERR\n");
9382         return false;
9383     }
9384     return true;
9385 }
9386
9387 static bool v7m_handle_execute_nsc(ARMCPU *cpu)
9388 {
9389     /* Check whether this attempt to execute code in a Secure & NS-Callable
9390      * memory region is for an SG instruction; if so, then emulate the
9391      * effect of the SG instruction and return true. Otherwise pend
9392      * the correct kind of exception and return false.
9393      */
9394     CPUARMState *env = &cpu->env;
9395     ARMMMUIdx mmu_idx;
9396     uint16_t insn;
9397
9398     /* We should never get here unless get_phys_addr_pmsav8() caused
9399      * an exception for NS executing in S&NSC memory.
9400      */
9401     assert(!env->v7m.secure);
9402     assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
9403
9404     /* We want to do the MPU lookup as secure; work out what mmu_idx that is */
9405     mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
9406
9407     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15], &insn)) {
9408         return false;
9409     }
9410
9411     if (!env->thumb) {
9412         goto gen_invep;
9413     }
9414
9415     if (insn != 0xe97f) {
9416         /* Not an SG instruction first half (we choose the IMPDEF
9417          * early-SG-check option).
9418          */
9419         goto gen_invep;
9420     }
9421
9422     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15] + 2, &insn)) {
9423         return false;
9424     }
9425
9426     if (insn != 0xe97f) {
9427         /* Not an SG instruction second half (yes, both halves of the SG
9428          * insn have the same hex value)
9429          */
9430         goto gen_invep;
9431     }
9432
9433     /* OK, we have confirmed that we really have an SG instruction.
9434      * We know we're NS in S memory so don't need to repeat those checks.
9435      */
9436     qemu_log_mask(CPU_LOG_INT, "...really an SG instruction at 0x%08" PRIx32
9437                   ", executing it\n", env->regs[15]);
9438     env->regs[14] &= ~1;
9439     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
9440     switch_v7m_security_state(env, true);
9441     xpsr_write(env, 0, XPSR_IT);
9442     env->regs[15] += 4;
9443     return true;
9444
9445 gen_invep:
9446     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
9447     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9448     qemu_log_mask(CPU_LOG_INT,
9449                   "...really SecureFault with SFSR.INVEP\n");
9450     return false;
9451 }
9452
9453 void arm_v7m_cpu_do_interrupt(CPUState *cs)
9454 {
9455     ARMCPU *cpu = ARM_CPU(cs);
9456     CPUARMState *env = &cpu->env;
9457     uint32_t lr;
9458     bool ignore_stackfaults;
9459
9460     arm_log_exception(cs->exception_index);
9461
9462     /* For exceptions we just mark as pending on the NVIC, and let that
9463        handle it.  */
9464     switch (cs->exception_index) {
9465     case EXCP_UDEF:
9466         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9467         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;
9468         break;
9469     case EXCP_NOCP:
9470     {
9471         /*
9472          * NOCP might be directed to something other than the current
9473          * security state if this fault is because of NSACR; we indicate
9474          * the target security state using exception.target_el.
9475          */
9476         int target_secstate;
9477
9478         if (env->exception.target_el == 3) {
9479             target_secstate = M_REG_S;
9480         } else {
9481             target_secstate = env->v7m.secure;
9482         }
9483         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, target_secstate);
9484         env->v7m.cfsr[target_secstate] |= R_V7M_CFSR_NOCP_MASK;
9485         break;
9486     }
9487     case EXCP_INVSTATE:
9488         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9489         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;
9490         break;
9491     case EXCP_STKOF:
9492         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9493         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
9494         break;
9495     case EXCP_LSERR:
9496         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9497         env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
9498         break;
9499     case EXCP_UNALIGNED:
9500         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9501         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNALIGNED_MASK;
9502         break;
9503     case EXCP_SWI:
9504         /* The PC already points to the next instruction.  */
9505         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC, env->v7m.secure);
9506         break;
9507     case EXCP_PREFETCH_ABORT:
9508     case EXCP_DATA_ABORT:
9509         /* Note that for M profile we don't have a guest facing FSR, but
9510          * the env->exception.fsr will be populated by the code that
9511          * raises the fault, in the A profile short-descriptor format.
9512          */
9513         switch (env->exception.fsr & 0xf) {
9514         case M_FAKE_FSR_NSC_EXEC:
9515             /* Exception generated when we try to execute code at an address
9516              * which is marked as Secure & Non-Secure Callable and the CPU
9517              * is in the Non-Secure state. The only instruction which can
9518              * be executed like this is SG (and that only if both halves of
9519              * the SG instruction have the same security attributes.)
9520              * Everything else must generate an INVEP SecureFault, so we
9521              * emulate the SG instruction here.
9522              */
9523             if (v7m_handle_execute_nsc(cpu)) {
9524                 return;
9525             }
9526             break;
9527         case M_FAKE_FSR_SFAULT:
9528             /* Various flavours of SecureFault for attempts to execute or
9529              * access data in the wrong security state.
9530              */
9531             switch (cs->exception_index) {
9532             case EXCP_PREFETCH_ABORT:
9533                 if (env->v7m.secure) {
9534                     env->v7m.sfsr |= R_V7M_SFSR_INVTRAN_MASK;
9535                     qemu_log_mask(CPU_LOG_INT,
9536                                   "...really SecureFault with SFSR.INVTRAN\n");
9537                 } else {
9538                     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
9539                     qemu_log_mask(CPU_LOG_INT,
9540                                   "...really SecureFault with SFSR.INVEP\n");
9541                 }
9542                 break;
9543             case EXCP_DATA_ABORT:
9544                 /* This must be an NS access to S memory */
9545                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
9546                 qemu_log_mask(CPU_LOG_INT,
9547                               "...really SecureFault with SFSR.AUVIOL\n");
9548                 break;
9549             }
9550             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9551             break;
9552         case 0x8: /* External Abort */
9553             switch (cs->exception_index) {
9554             case EXCP_PREFETCH_ABORT:
9555                 env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
9556                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");
9557                 break;
9558             case EXCP_DATA_ABORT:
9559                 env->v7m.cfsr[M_REG_NS] |=
9560                     (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);
9561                 env->v7m.bfar = env->exception.vaddress;
9562                 qemu_log_mask(CPU_LOG_INT,
9563                               "...with CFSR.PRECISERR and BFAR 0x%x\n",
9564                               env->v7m.bfar);
9565                 break;
9566             }
9567             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
9568             break;
9569         default:
9570             /* All other FSR values are either MPU faults or "can't happen
9571              * for M profile" cases.
9572              */
9573             switch (cs->exception_index) {
9574             case EXCP_PREFETCH_ABORT:
9575                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
9576                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");
9577                 break;
9578             case EXCP_DATA_ABORT:
9579                 env->v7m.cfsr[env->v7m.secure] |=
9580                     (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);
9581                 env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;
9582                 qemu_log_mask(CPU_LOG_INT,
9583                               "...with CFSR.DACCVIOL and MMFAR 0x%x\n",
9584                               env->v7m.mmfar[env->v7m.secure]);
9585                 break;
9586             }
9587             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM,
9588                                     env->v7m.secure);
9589             break;
9590         }
9591         break;
9592     case EXCP_BKPT:
9593         if (semihosting_enabled()) {
9594             int nr;
9595             nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;
9596             if (nr == 0xab) {
9597                 env->regs[15] += 2;
9598                 qemu_log_mask(CPU_LOG_INT,
9599                               "...handling as semihosting call 0x%x\n",
9600                               env->regs[0]);
9601                 env->regs[0] = do_arm_semihosting(env);
9602                 return;
9603             }
9604         }
9605         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG, false);
9606         break;
9607     case EXCP_IRQ:
9608         break;
9609     case EXCP_EXCEPTION_EXIT:
9610         if (env->regs[15] < EXC_RETURN_MIN_MAGIC) {
9611             /* Must be v8M security extension function return */
9612             assert(env->regs[15] >= FNC_RETURN_MIN_MAGIC);
9613             assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
9614             if (do_v7m_function_return(cpu)) {
9615                 return;
9616             }
9617         } else {
9618             do_v7m_exception_exit(cpu);
9619             return;
9620         }
9621         break;
9622     case EXCP_LAZYFP:
9623         /*
9624          * We already pended the specific exception in the NVIC in the
9625          * v7m_preserve_fp_state() helper function.
9626          */
9627         break;
9628     default:
9629         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9630         return; /* Never happens.  Keep compiler happy.  */
9631     }
9632
9633     if (arm_feature(env, ARM_FEATURE_V8)) {
9634         lr = R_V7M_EXCRET_RES1_MASK |
9635             R_V7M_EXCRET_DCRS_MASK;
9636         /* The S bit indicates whether we should return to Secure
9637          * or NonSecure (ie our current state).
9638          * The ES bit indicates whether we're taking this exception
9639          * to Secure or NonSecure (ie our target state). We set it
9640          * later, in v7m_exception_taken().
9641          * The SPSEL bit is also set in v7m_exception_taken() for v8M.
9642          * This corresponds to the ARM ARM pseudocode for v8M setting
9643          * some LR bits in PushStack() and some in ExceptionTaken();
9644          * the distinction matters for the tailchain cases where we
9645          * can take an exception without pushing the stack.
9646          */
9647         if (env->v7m.secure) {
9648             lr |= R_V7M_EXCRET_S_MASK;
9649         }
9650         if (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK)) {
9651             lr |= R_V7M_EXCRET_FTYPE_MASK;
9652         }
9653     } else {
9654         lr = R_V7M_EXCRET_RES1_MASK |
9655             R_V7M_EXCRET_S_MASK |
9656             R_V7M_EXCRET_DCRS_MASK |
9657             R_V7M_EXCRET_FTYPE_MASK |
9658             R_V7M_EXCRET_ES_MASK;
9659         if (env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK) {
9660             lr |= R_V7M_EXCRET_SPSEL_MASK;
9661         }
9662     }
9663     if (!arm_v7m_is_handler_mode(env)) {
9664         lr |= R_V7M_EXCRET_MODE_MASK;
9665     }
9666
9667     ignore_stackfaults = v7m_push_stack(cpu);
9668     v7m_exception_taken(cpu, lr, false, ignore_stackfaults);
9669 }
9670
9671 /* Function used to synchronize QEMU's AArch64 register set with AArch32
9672  * register set.  This is necessary when switching between AArch32 and AArch64
9673  * execution state.
9674  */
9675 void aarch64_sync_32_to_64(CPUARMState *env)
9676 {
9677     int i;
9678     uint32_t mode = env->uncached_cpsr & CPSR_M;
9679
9680     /* We can blanket copy R[0:7] to X[0:7] */
9681     for (i = 0; i < 8; i++) {
9682         env->xregs[i] = env->regs[i];
9683     }
9684
9685     /* Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9686      * Otherwise, they come from the banked user regs.
9687      */
9688     if (mode == ARM_CPU_MODE_FIQ) {
9689         for (i = 8; i < 13; i++) {
9690             env->xregs[i] = env->usr_regs[i - 8];
9691         }
9692     } else {
9693         for (i = 8; i < 13; i++) {
9694             env->xregs[i] = env->regs[i];
9695         }
9696     }
9697
9698     /* Registers x13-x23 are the various mode SP and FP registers. Registers
9699      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9700      * from the mode banked register.
9701      */
9702     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9703         env->xregs[13] = env->regs[13];
9704         env->xregs[14] = env->regs[14];
9705     } else {
9706         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9707         /* HYP is an exception in that it is copied from r14 */
9708         if (mode == ARM_CPU_MODE_HYP) {
9709             env->xregs[14] = env->regs[14];
9710         } else {
9711             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9712         }
9713     }
9714
9715     if (mode == ARM_CPU_MODE_HYP) {
9716         env->xregs[15] = env->regs[13];
9717     } else {
9718         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9719     }
9720
9721     if (mode == ARM_CPU_MODE_IRQ) {
9722         env->xregs[16] = env->regs[14];
9723         env->xregs[17] = env->regs[13];
9724     } else {
9725         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9726         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9727     }
9728
9729     if (mode == ARM_CPU_MODE_SVC) {
9730         env->xregs[18] = env->regs[14];
9731         env->xregs[19] = env->regs[13];
9732     } else {
9733         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9734         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9735     }
9736
9737     if (mode == ARM_CPU_MODE_ABT) {
9738         env->xregs[20] = env->regs[14];
9739         env->xregs[21] = env->regs[13];
9740     } else {
9741         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9742         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9743     }
9744
9745     if (mode == ARM_CPU_MODE_UND) {
9746         env->xregs[22] = env->regs[14];
9747         env->xregs[23] = env->regs[13];
9748     } else {
9749         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9750         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9751     }
9752
9753     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9754      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9755      * FIQ bank for r8-r14.
9756      */
9757     if (mode == ARM_CPU_MODE_FIQ) {
9758         for (i = 24; i < 31; i++) {
9759             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9760         }
9761     } else {
9762         for (i = 24; i < 29; i++) {
9763             env->xregs[i] = env->fiq_regs[i - 24];
9764         }
9765         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9766         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9767     }
9768
9769     env->pc = env->regs[15];
9770 }
9771
9772 /* Function used to synchronize QEMU's AArch32 register set with AArch64
9773  * register set.  This is necessary when switching between AArch32 and AArch64
9774  * execution state.
9775  */
9776 void aarch64_sync_64_to_32(CPUARMState *env)
9777 {
9778     int i;
9779     uint32_t mode = env->uncached_cpsr & CPSR_M;
9780
9781     /* We can blanket copy X[0:7] to R[0:7] */
9782     for (i = 0; i < 8; i++) {
9783         env->regs[i] = env->xregs[i];
9784     }
9785
9786     /* Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9787      * Otherwise, we copy x8-x12 into the banked user regs.
9788      */
9789     if (mode == ARM_CPU_MODE_FIQ) {
9790         for (i = 8; i < 13; i++) {
9791             env->usr_regs[i - 8] = env->xregs[i];
9792         }
9793     } else {
9794         for (i = 8; i < 13; i++) {
9795             env->regs[i] = env->xregs[i];
9796         }
9797     }
9798
9799     /* Registers r13 & r14 depend on the current mode.
9800      * If we are in a given mode, we copy the corresponding x registers to r13
9801      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9802      * for the mode.
9803      */
9804     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9805         env->regs[13] = env->xregs[13];
9806         env->regs[14] = env->xregs[14];
9807     } else {
9808         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9809
9810         /* HYP is an exception in that it does not have its own banked r14 but
9811          * shares the USR r14
9812          */
9813         if (mode == ARM_CPU_MODE_HYP) {
9814             env->regs[14] = env->xregs[14];
9815         } else {
9816             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9817         }
9818     }
9819
9820     if (mode == ARM_CPU_MODE_HYP) {
9821         env->regs[13] = env->xregs[15];
9822     } else {
9823         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9824     }
9825
9826     if (mode == ARM_CPU_MODE_IRQ) {
9827         env->regs[14] = env->xregs[16];
9828         env->regs[13] = env->xregs[17];
9829     } else {
9830         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9831         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9832     }
9833
9834     if (mode == ARM_CPU_MODE_SVC) {
9835         env->regs[14] = env->xregs[18];
9836         env->regs[13] = env->xregs[19];
9837     } else {
9838         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9839         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9840     }
9841
9842     if (mode == ARM_CPU_MODE_ABT) {
9843         env->regs[14] = env->xregs[20];
9844         env->regs[13] = env->xregs[21];
9845     } else {
9846         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9847         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9848     }
9849
9850     if (mode == ARM_CPU_MODE_UND) {
9851         env->regs[14] = env->xregs[22];
9852         env->regs[13] = env->xregs[23];
9853     } else {
9854         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9855         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9856     }
9857
9858     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9859      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9860      * FIQ bank for r8-r14.
9861      */
9862     if (mode == ARM_CPU_MODE_FIQ) {
9863         for (i = 24; i < 31; i++) {
9864             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9865         }
9866     } else {
9867         for (i = 24; i < 29; i++) {
9868             env->fiq_regs[i - 24] = env->xregs[i];
9869         }
9870         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9871         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9872     }
9873
9874     env->regs[15] = env->pc;
9875 }
9876
9877 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9878                                    uint32_t mask, uint32_t offset,
9879                                    uint32_t newpc)
9880 {
9881     /* Change the CPU state so as to actually take the exception. */
9882     switch_mode(env, new_mode);
9883     /*
9884      * For exceptions taken to AArch32 we must clear the SS bit in both
9885      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9886      */
9887     env->uncached_cpsr &= ~PSTATE_SS;
9888     env->spsr = cpsr_read(env);
9889     /* Clear IT bits.  */
9890     env->condexec_bits = 0;
9891     /* Switch to the new mode, and to the correct instruction set.  */
9892     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9893     /* Set new mode endianness */
9894     env->uncached_cpsr &= ~CPSR_E;
9895     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
9896         env->uncached_cpsr |= CPSR_E;
9897     }
9898     /* J and IL must always be cleared for exception entry */
9899     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9900     env->daif |= mask;
9901
9902     if (new_mode == ARM_CPU_MODE_HYP) {
9903         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9904         env->elr_el[2] = env->regs[15];
9905     } else {
9906         /*
9907          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9908          * and we should just guard the thumb mode on V4
9909          */
9910         if (arm_feature(env, ARM_FEATURE_V4T)) {
9911             env->thumb =
9912                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9913         }
9914         env->regs[14] = env->regs[15] + offset;
9915     }
9916     env->regs[15] = newpc;
9917 }
9918
9919 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9920 {
9921     /*
9922      * Handle exception entry to Hyp mode; this is sufficiently
9923      * different to entry to other AArch32 modes that we handle it
9924      * separately here.
9925      *
9926      * The vector table entry used is always the 0x14 Hyp mode entry point,
9927      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
9928      * The offset applied to the preferred return address is always zero
9929      * (see DDI0487C.a section G1.12.3).
9930      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9931      */
9932     uint32_t addr, mask;
9933     ARMCPU *cpu = ARM_CPU(cs);
9934     CPUARMState *env = &cpu->env;
9935
9936     switch (cs->exception_index) {
9937     case EXCP_UDEF:
9938         addr = 0x04;
9939         break;
9940     case EXCP_SWI:
9941         addr = 0x14;
9942         break;
9943     case EXCP_BKPT:
9944         /* Fall through to prefetch abort.  */
9945     case EXCP_PREFETCH_ABORT:
9946         env->cp15.ifar_s = env->exception.vaddress;
9947         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9948                       (uint32_t)env->exception.vaddress);
9949         addr = 0x0c;
9950         break;
9951     case EXCP_DATA_ABORT:
9952         env->cp15.dfar_s = env->exception.vaddress;
9953         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9954                       (uint32_t)env->exception.vaddress);
9955         addr = 0x10;
9956         break;
9957     case EXCP_IRQ:
9958         addr = 0x18;
9959         break;
9960     case EXCP_FIQ:
9961         addr = 0x1c;
9962         break;
9963     case EXCP_HVC:
9964         addr = 0x08;
9965         break;
9966     case EXCP_HYP_TRAP:
9967         addr = 0x14;
9968     default:
9969         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9970     }
9971
9972     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9973         if (!arm_feature(env, ARM_FEATURE_V8)) {
9974             /*
9975              * QEMU syndrome values are v8-style. v7 has the IL bit
9976              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9977              * If this is a v7 CPU, squash the IL bit in those cases.
9978              */
9979             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9980                 (cs->exception_index == EXCP_DATA_ABORT &&
9981                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9982                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9983                 env->exception.syndrome &= ~ARM_EL_IL;
9984             }
9985         }
9986         env->cp15.esr_el[2] = env->exception.syndrome;
9987     }
9988
9989     if (arm_current_el(env) != 2 && addr < 0x14) {
9990         addr = 0x14;
9991     }
9992
9993     mask = 0;
9994     if (!(env->cp15.scr_el3 & SCR_EA)) {
9995         mask |= CPSR_A;
9996     }
9997     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9998         mask |= CPSR_I;
9999     }
10000     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
10001         mask |= CPSR_F;
10002     }
10003
10004     addr += env->cp15.hvbar;
10005
10006     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
10007 }
10008
10009 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
10010 {
10011     ARMCPU *cpu = ARM_CPU(cs);
10012     CPUARMState *env = &cpu->env;
10013     uint32_t addr;
10014     uint32_t mask;
10015     int new_mode;
10016     uint32_t offset;
10017     uint32_t moe;
10018
10019     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
10020     switch (syn_get_ec(env->exception.syndrome)) {
10021     case EC_BREAKPOINT:
10022     case EC_BREAKPOINT_SAME_EL:
10023         moe = 1;
10024         break;
10025     case EC_WATCHPOINT:
10026     case EC_WATCHPOINT_SAME_EL:
10027         moe = 10;
10028         break;
10029     case EC_AA32_BKPT:
10030         moe = 3;
10031         break;
10032     case EC_VECTORCATCH:
10033         moe = 5;
10034         break;
10035     default:
10036         moe = 0;
10037         break;
10038     }
10039
10040     if (moe) {
10041         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
10042     }
10043
10044     if (env->exception.target_el == 2) {
10045         arm_cpu_do_interrupt_aarch32_hyp(cs);
10046         return;
10047     }
10048
10049     switch (cs->exception_index) {
10050     case EXCP_UDEF:
10051         new_mode = ARM_CPU_MODE_UND;
10052         addr = 0x04;
10053         mask = CPSR_I;
10054         if (env->thumb)
10055             offset = 2;
10056         else
10057             offset = 4;
10058         break;
10059     case EXCP_SWI:
10060         new_mode = ARM_CPU_MODE_SVC;
10061         addr = 0x08;
10062         mask = CPSR_I;
10063         /* The PC already points to the next instruction.  */
10064         offset = 0;
10065         break;
10066     case EXCP_BKPT:
10067         /* Fall through to prefetch abort.  */
10068     case EXCP_PREFETCH_ABORT:
10069         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
10070         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
10071         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
10072                       env->exception.fsr, (uint32_t)env->exception.vaddress);
10073         new_mode = ARM_CPU_MODE_ABT;
10074         addr = 0x0c;
10075         mask = CPSR_A | CPSR_I;
10076         offset = 4;
10077         break;
10078     case EXCP_DATA_ABORT:
10079         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
10080         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
10081         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
10082                       env->exception.fsr,
10083                       (uint32_t)env->exception.vaddress);
10084         new_mode = ARM_CPU_MODE_ABT;
10085         addr = 0x10;
10086         mask = CPSR_A | CPSR_I;
10087         offset = 8;
10088         break;
10089     case EXCP_IRQ:
10090         new_mode = ARM_CPU_MODE_IRQ;
10091         addr = 0x18;
10092         /* Disable IRQ and imprecise data aborts.  */
10093         mask = CPSR_A | CPSR_I;
10094         offset = 4;
10095         if (env->cp15.scr_el3 & SCR_IRQ) {
10096             /* IRQ routed to monitor mode */
10097             new_mode = ARM_CPU_MODE_MON;
10098             mask |= CPSR_F;
10099         }
10100         break;
10101     case EXCP_FIQ:
10102         new_mode = ARM_CPU_MODE_FIQ;
10103         addr = 0x1c;
10104         /* Disable FIQ, IRQ and imprecise data aborts.  */
10105         mask = CPSR_A | CPSR_I | CPSR_F;
10106         if (env->cp15.scr_el3 & SCR_FIQ) {
10107             /* FIQ routed to monitor mode */
10108             new_mode = ARM_CPU_MODE_MON;
10109         }
10110         offset = 4;
10111         break;
10112     case EXCP_VIRQ:
10113         new_mode = ARM_CPU_MODE_IRQ;
10114         addr = 0x18;
10115         /* Disable IRQ and imprecise data aborts.  */
10116         mask = CPSR_A | CPSR_I;
10117         offset = 4;
10118         break;
10119     case EXCP_VFIQ:
10120         new_mode = ARM_CPU_MODE_FIQ;
10121         addr = 0x1c;
10122         /* Disable FIQ, IRQ and imprecise data aborts.  */
10123         mask = CPSR_A | CPSR_I | CPSR_F;
10124         offset = 4;
10125         break;
10126     case EXCP_SMC:
10127         new_mode = ARM_CPU_MODE_MON;
10128         addr = 0x08;
10129         mask = CPSR_A | CPSR_I | CPSR_F;
10130         offset = 0;
10131         break;
10132     default:
10133         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10134         return; /* Never happens.  Keep compiler happy.  */
10135     }
10136
10137     if (new_mode == ARM_CPU_MODE_MON) {
10138         addr += env->cp15.mvbar;
10139     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
10140         /* High vectors. When enabled, base address cannot be remapped. */
10141         addr += 0xffff0000;
10142     } else {
10143         /* ARM v7 architectures provide a vector base address register to remap
10144          * the interrupt vector table.
10145          * This register is only followed in non-monitor mode, and is banked.
10146          * Note: only bits 31:5 are valid.
10147          */
10148         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
10149     }
10150
10151     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
10152         env->cp15.scr_el3 &= ~SCR_NS;
10153     }
10154
10155     take_aarch32_exception(env, new_mode, mask, offset, addr);
10156 }
10157
10158 /* Handle exception entry to a target EL which is using AArch64 */
10159 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
10160 {
10161     ARMCPU *cpu = ARM_CPU(cs);
10162     CPUARMState *env = &cpu->env;
10163     unsigned int new_el = env->exception.target_el;
10164     target_ulong addr = env->cp15.vbar_el[new_el];
10165     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
10166     unsigned int cur_el = arm_current_el(env);
10167
10168     /*
10169      * Note that new_el can never be 0.  If cur_el is 0, then
10170      * el0_a64 is is_a64(), else el0_a64 is ignored.
10171      */
10172     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
10173
10174     if (cur_el < new_el) {
10175         /* Entry vector offset depends on whether the implemented EL
10176          * immediately lower than the target level is using AArch32 or AArch64
10177          */
10178         bool is_aa64;
10179
10180         switch (new_el) {
10181         case 3:
10182             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
10183             break;
10184         case 2:
10185             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
10186             break;
10187         case 1:
10188             is_aa64 = is_a64(env);
10189             break;
10190         default:
10191             g_assert_not_reached();
10192         }
10193
10194         if (is_aa64) {
10195             addr += 0x400;
10196         } else {
10197             addr += 0x600;
10198         }
10199     } else if (pstate_read(env) & PSTATE_SP) {
10200         addr += 0x200;
10201     }
10202
10203     switch (cs->exception_index) {
10204     case EXCP_PREFETCH_ABORT:
10205     case EXCP_DATA_ABORT:
10206         env->cp15.far_el[new_el] = env->exception.vaddress;
10207         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
10208                       env->cp15.far_el[new_el]);
10209         /* fall through */
10210     case EXCP_BKPT:
10211     case EXCP_UDEF:
10212     case EXCP_SWI:
10213     case EXCP_HVC:
10214     case EXCP_HYP_TRAP:
10215     case EXCP_SMC:
10216         if (syn_get_ec(env->exception.syndrome) == EC_ADVSIMDFPACCESSTRAP) {
10217             /*
10218              * QEMU internal FP/SIMD syndromes from AArch32 include the
10219              * TA and coproc fields which are only exposed if the exception
10220              * is taken to AArch32 Hyp mode. Mask them out to get a valid
10221              * AArch64 format syndrome.
10222              */
10223             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
10224         }
10225         env->cp15.esr_el[new_el] = env->exception.syndrome;
10226         break;
10227     case EXCP_IRQ:
10228     case EXCP_VIRQ:
10229         addr += 0x80;
10230         break;
10231     case EXCP_FIQ:
10232     case EXCP_VFIQ:
10233         addr += 0x100;
10234         break;
10235     case EXCP_SEMIHOST:
10236         qemu_log_mask(CPU_LOG_INT,
10237                       "...handling as semihosting call 0x%" PRIx64 "\n",
10238                       env->xregs[0]);
10239         env->xregs[0] = do_arm_semihosting(env);
10240         return;
10241     default:
10242         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10243     }
10244
10245     if (is_a64(env)) {
10246         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
10247         aarch64_save_sp(env, arm_current_el(env));
10248         env->elr_el[new_el] = env->pc;
10249     } else {
10250         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
10251         env->elr_el[new_el] = env->regs[15];
10252
10253         aarch64_sync_32_to_64(env);
10254
10255         env->condexec_bits = 0;
10256     }
10257     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
10258                   env->elr_el[new_el]);
10259
10260     pstate_write(env, PSTATE_DAIF | new_mode);
10261     env->aarch64 = 1;
10262     aarch64_restore_sp(env, new_el);
10263
10264     env->pc = addr;
10265
10266     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10267                   new_el, env->pc, pstate_read(env));
10268 }
10269
10270 static inline bool check_for_semihosting(CPUState *cs)
10271 {
10272     /* Check whether this exception is a semihosting call; if so
10273      * then handle it and return true; otherwise return false.
10274      */
10275     ARMCPU *cpu = ARM_CPU(cs);
10276     CPUARMState *env = &cpu->env;
10277
10278     if (is_a64(env)) {
10279         if (cs->exception_index == EXCP_SEMIHOST) {
10280             /* This is always the 64-bit semihosting exception.
10281              * The "is this usermode" and "is semihosting enabled"
10282              * checks have been done at translate time.
10283              */
10284             qemu_log_mask(CPU_LOG_INT,
10285                           "...handling as semihosting call 0x%" PRIx64 "\n",
10286                           env->xregs[0]);
10287             env->xregs[0] = do_arm_semihosting(env);
10288             return true;
10289         }
10290         return false;
10291     } else {
10292         uint32_t imm;
10293
10294         /* Only intercept calls from privileged modes, to provide some
10295          * semblance of security.
10296          */
10297         if (cs->exception_index != EXCP_SEMIHOST &&
10298             (!semihosting_enabled() ||
10299              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
10300             return false;
10301         }
10302
10303         switch (cs->exception_index) {
10304         case EXCP_SEMIHOST:
10305             /* This is always a semihosting call; the "is this usermode"
10306              * and "is semihosting enabled" checks have been done at
10307              * translate time.
10308              */
10309             break;
10310         case EXCP_SWI:
10311             /* Check for semihosting interrupt.  */
10312             if (env->thumb) {
10313                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
10314                     & 0xff;
10315                 if (imm == 0xab) {
10316                     break;
10317                 }
10318             } else {
10319                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
10320                     & 0xffffff;
10321                 if (imm == 0x123456) {
10322                     break;
10323                 }
10324             }
10325             return false;
10326         case EXCP_BKPT:
10327             /* See if this is a semihosting syscall.  */
10328             if (env->thumb) {
10329                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
10330                     & 0xff;
10331                 if (imm == 0xab) {
10332                     env->regs[15] += 2;
10333                     break;
10334                 }
10335             }
10336             return false;
10337         default:
10338             return false;
10339         }
10340
10341         qemu_log_mask(CPU_LOG_INT,
10342                       "...handling as semihosting call 0x%x\n",
10343                       env->regs[0]);
10344         env->regs[0] = do_arm_semihosting(env);
10345         return true;
10346     }
10347 }
10348
10349 /* Handle a CPU exception for A and R profile CPUs.
10350  * Do any appropriate logging, handle PSCI calls, and then hand off
10351  * to the AArch64-entry or AArch32-entry function depending on the
10352  * target exception level's register width.
10353  */
10354 void arm_cpu_do_interrupt(CPUState *cs)
10355 {
10356     ARMCPU *cpu = ARM_CPU(cs);
10357     CPUARMState *env = &cpu->env;
10358     unsigned int new_el = env->exception.target_el;
10359
10360     assert(!arm_feature(env, ARM_FEATURE_M));
10361
10362     arm_log_exception(cs->exception_index);
10363     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10364                   new_el);
10365     if (qemu_loglevel_mask(CPU_LOG_INT)
10366         && !excp_is_internal(cs->exception_index)) {
10367         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10368                       syn_get_ec(env->exception.syndrome),
10369                       env->exception.syndrome);
10370     }
10371
10372     if (arm_is_psci_call(cpu, cs->exception_index)) {
10373         arm_handle_psci_call(cpu);
10374         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10375         return;
10376     }
10377
10378     /* Semihosting semantics depend on the register width of the
10379      * code that caused the exception, not the target exception level,
10380      * so must be handled here.
10381      */
10382     if (check_for_semihosting(cs)) {
10383         return;
10384     }
10385
10386     /* Hooks may change global state so BQL should be held, also the
10387      * BQL needs to be held for any modification of
10388      * cs->interrupt_request.
10389      */
10390     g_assert(qemu_mutex_iothread_locked());
10391
10392     arm_call_pre_el_change_hook(cpu);
10393
10394     assert(!excp_is_internal(cs->exception_index));
10395     if (arm_el_is_aa64(env, new_el)) {
10396         arm_cpu_do_interrupt_aarch64(cs);
10397     } else {
10398         arm_cpu_do_interrupt_aarch32(cs);
10399     }
10400
10401     arm_call_el_change_hook(cpu);
10402
10403     if (!kvm_enabled()) {
10404         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10405     }
10406 }
10407 #endif /* !CONFIG_USER_ONLY */
10408
10409 /* Return the exception level which controls this address translation regime */
10410 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
10411 {
10412     switch (mmu_idx) {
10413     case ARMMMUIdx_S2NS:
10414     case ARMMMUIdx_S1E2:
10415         return 2;
10416     case ARMMMUIdx_S1E3:
10417         return 3;
10418     case ARMMMUIdx_S1SE0:
10419         return arm_el_is_aa64(env, 3) ? 1 : 3;
10420     case ARMMMUIdx_S1SE1:
10421     case ARMMMUIdx_S1NSE0:
10422     case ARMMMUIdx_S1NSE1:
10423     case ARMMMUIdx_MPrivNegPri:
10424     case ARMMMUIdx_MUserNegPri:
10425     case ARMMMUIdx_MPriv:
10426     case ARMMMUIdx_MUser:
10427     case ARMMMUIdx_MSPrivNegPri:
10428     case ARMMMUIdx_MSUserNegPri:
10429     case ARMMMUIdx_MSPriv:
10430     case ARMMMUIdx_MSUser:
10431         return 1;
10432     default:
10433         g_assert_not_reached();
10434     }
10435 }
10436
10437 #ifndef CONFIG_USER_ONLY
10438
10439 /* Return the SCTLR value which controls this address translation regime */
10440 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10441 {
10442     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10443 }
10444
10445 /* Return true if the specified stage of address translation is disabled */
10446 static inline bool regime_translation_disabled(CPUARMState *env,
10447                                                ARMMMUIdx mmu_idx)
10448 {
10449     if (arm_feature(env, ARM_FEATURE_M)) {
10450         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10451                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10452         case R_V7M_MPU_CTRL_ENABLE_MASK:
10453             /* Enabled, but not for HardFault and NMI */
10454             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10455         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10456             /* Enabled for all cases */
10457             return false;
10458         case 0:
10459         default:
10460             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10461              * we warned about that in armv7m_nvic.c when the guest set it.
10462              */
10463             return true;
10464         }
10465     }
10466
10467     if (mmu_idx == ARMMMUIdx_S2NS) {
10468         /* HCR.DC means HCR.VM behaves as 1 */
10469         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10470     }
10471
10472     if (env->cp15.hcr_el2 & HCR_TGE) {
10473         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10474         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10475             return true;
10476         }
10477     }
10478
10479     if ((env->cp15.hcr_el2 & HCR_DC) &&
10480         (mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1)) {
10481         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10482         return true;
10483     }
10484
10485     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10486 }
10487
10488 static inline bool regime_translation_big_endian(CPUARMState *env,
10489                                                  ARMMMUIdx mmu_idx)
10490 {
10491     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10492 }
10493
10494 /* Return the TTBR associated with this translation regime */
10495 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10496                                    int ttbrn)
10497 {
10498     if (mmu_idx == ARMMMUIdx_S2NS) {
10499         return env->cp15.vttbr_el2;
10500     }
10501     if (ttbrn == 0) {
10502         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10503     } else {
10504         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10505     }
10506 }
10507
10508 #endif /* !CONFIG_USER_ONLY */
10509
10510 /* Return the TCR controlling this translation regime */
10511 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
10512 {
10513     if (mmu_idx == ARMMMUIdx_S2NS) {
10514         return &env->cp15.vtcr_el2;
10515     }
10516     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
10517 }
10518
10519 /* Convert a possible stage1+2 MMU index into the appropriate
10520  * stage 1 MMU index
10521  */
10522 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10523 {
10524     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10525         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
10526     }
10527     return mmu_idx;
10528 }
10529
10530 /* Return true if the translation regime is using LPAE format page tables */
10531 static inline bool regime_using_lpae_format(CPUARMState *env,
10532                                             ARMMMUIdx mmu_idx)
10533 {
10534     int el = regime_el(env, mmu_idx);
10535     if (el == 2 || arm_el_is_aa64(env, el)) {
10536         return true;
10537     }
10538     if (arm_feature(env, ARM_FEATURE_LPAE)
10539         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10540         return true;
10541     }
10542     return false;
10543 }
10544
10545 /* Returns true if the stage 1 translation regime is using LPAE format page
10546  * tables. Used when raising alignment exceptions, whose FSR changes depending
10547  * on whether the long or short descriptor format is in use. */
10548 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10549 {
10550     mmu_idx = stage_1_mmu_idx(mmu_idx);
10551
10552     return regime_using_lpae_format(env, mmu_idx);
10553 }
10554
10555 #ifndef CONFIG_USER_ONLY
10556 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10557 {
10558     switch (mmu_idx) {
10559     case ARMMMUIdx_S1SE0:
10560     case ARMMMUIdx_S1NSE0:
10561     case ARMMMUIdx_MUser:
10562     case ARMMMUIdx_MSUser:
10563     case ARMMMUIdx_MUserNegPri:
10564     case ARMMMUIdx_MSUserNegPri:
10565         return true;
10566     default:
10567         return false;
10568     case ARMMMUIdx_S12NSE0:
10569     case ARMMMUIdx_S12NSE1:
10570         g_assert_not_reached();
10571     }
10572 }
10573
10574 /* Translate section/page access permissions to page
10575  * R/W protection flags
10576  *
10577  * @env:         CPUARMState
10578  * @mmu_idx:     MMU index indicating required translation regime
10579  * @ap:          The 3-bit access permissions (AP[2:0])
10580  * @domain_prot: The 2-bit domain access permissions
10581  */
10582 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10583                                 int ap, int domain_prot)
10584 {
10585     bool is_user = regime_is_user(env, mmu_idx);
10586
10587     if (domain_prot == 3) {
10588         return PAGE_READ | PAGE_WRITE;
10589     }
10590
10591     switch (ap) {
10592     case 0:
10593         if (arm_feature(env, ARM_FEATURE_V7)) {
10594             return 0;
10595         }
10596         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10597         case SCTLR_S:
10598             return is_user ? 0 : PAGE_READ;
10599         case SCTLR_R:
10600             return PAGE_READ;
10601         default:
10602             return 0;
10603         }
10604     case 1:
10605         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10606     case 2:
10607         if (is_user) {
10608             return PAGE_READ;
10609         } else {
10610             return PAGE_READ | PAGE_WRITE;
10611         }
10612     case 3:
10613         return PAGE_READ | PAGE_WRITE;
10614     case 4: /* Reserved.  */
10615         return 0;
10616     case 5:
10617         return is_user ? 0 : PAGE_READ;
10618     case 6:
10619         return PAGE_READ;
10620     case 7:
10621         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10622             return 0;
10623         }
10624         return PAGE_READ;
10625     default:
10626         g_assert_not_reached();
10627     }
10628 }
10629
10630 /* Translate section/page access permissions to page
10631  * R/W protection flags.
10632  *
10633  * @ap:      The 2-bit simple AP (AP[2:1])
10634  * @is_user: TRUE if accessing from PL0
10635  */
10636 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10637 {
10638     switch (ap) {
10639     case 0:
10640         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10641     case 1:
10642         return PAGE_READ | PAGE_WRITE;
10643     case 2:
10644         return is_user ? 0 : PAGE_READ;
10645     case 3:
10646         return PAGE_READ;
10647     default:
10648         g_assert_not_reached();
10649     }
10650 }
10651
10652 static inline int
10653 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10654 {
10655     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10656 }
10657
10658 /* Translate S2 section/page access permissions to protection flags
10659  *
10660  * @env:     CPUARMState
10661  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10662  * @xn:      XN (execute-never) bit
10663  */
10664 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
10665 {
10666     int prot = 0;
10667
10668     if (s2ap & 1) {
10669         prot |= PAGE_READ;
10670     }
10671     if (s2ap & 2) {
10672         prot |= PAGE_WRITE;
10673     }
10674     if (!xn) {
10675         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10676             prot |= PAGE_EXEC;
10677         }
10678     }
10679     return prot;
10680 }
10681
10682 /* Translate section/page access permissions to protection flags
10683  *
10684  * @env:     CPUARMState
10685  * @mmu_idx: MMU index indicating required translation regime
10686  * @is_aa64: TRUE if AArch64
10687  * @ap:      The 2-bit simple AP (AP[2:1])
10688  * @ns:      NS (non-secure) bit
10689  * @xn:      XN (execute-never) bit
10690  * @pxn:     PXN (privileged execute-never) bit
10691  */
10692 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10693                       int ap, int ns, int xn, int pxn)
10694 {
10695     bool is_user = regime_is_user(env, mmu_idx);
10696     int prot_rw, user_rw;
10697     bool have_wxn;
10698     int wxn = 0;
10699
10700     assert(mmu_idx != ARMMMUIdx_S2NS);
10701
10702     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10703     if (is_user) {
10704         prot_rw = user_rw;
10705     } else {
10706         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10707     }
10708
10709     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10710         return prot_rw;
10711     }
10712
10713     /* TODO have_wxn should be replaced with
10714      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10715      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10716      * compatible processors have EL2, which is required for [U]WXN.
10717      */
10718     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10719
10720     if (have_wxn) {
10721         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10722     }
10723
10724     if (is_aa64) {
10725         switch (regime_el(env, mmu_idx)) {
10726         case 1:
10727             if (!is_user) {
10728                 xn = pxn || (user_rw & PAGE_WRITE);
10729             }
10730             break;
10731         case 2:
10732         case 3:
10733             break;
10734         }
10735     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10736         switch (regime_el(env, mmu_idx)) {
10737         case 1:
10738         case 3:
10739             if (is_user) {
10740                 xn = xn || !(user_rw & PAGE_READ);
10741             } else {
10742                 int uwxn = 0;
10743                 if (have_wxn) {
10744                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10745                 }
10746                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10747                      (uwxn && (user_rw & PAGE_WRITE));
10748             }
10749             break;
10750         case 2:
10751             break;
10752         }
10753     } else {
10754         xn = wxn = 0;
10755     }
10756
10757     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10758         return prot_rw;
10759     }
10760     return prot_rw | PAGE_EXEC;
10761 }
10762
10763 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10764                                      uint32_t *table, uint32_t address)
10765 {
10766     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10767     TCR *tcr = regime_tcr(env, mmu_idx);
10768
10769     if (address & tcr->mask) {
10770         if (tcr->raw_tcr & TTBCR_PD1) {
10771             /* Translation table walk disabled for TTBR1 */
10772             return false;
10773         }
10774         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10775     } else {
10776         if (tcr->raw_tcr & TTBCR_PD0) {
10777             /* Translation table walk disabled for TTBR0 */
10778             return false;
10779         }
10780         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10781     }
10782     *table |= (address >> 18) & 0x3ffc;
10783     return true;
10784 }
10785
10786 /* Translate a S1 pagetable walk through S2 if needed.  */
10787 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10788                                hwaddr addr, MemTxAttrs txattrs,
10789                                ARMMMUFaultInfo *fi)
10790 {
10791     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
10792         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10793         target_ulong s2size;
10794         hwaddr s2pa;
10795         int s2prot;
10796         int ret;
10797         ARMCacheAttrs cacheattrs = {};
10798         ARMCacheAttrs *pcacheattrs = NULL;
10799
10800         if (env->cp15.hcr_el2 & HCR_PTW) {
10801             /*
10802              * PTW means we must fault if this S1 walk touches S2 Device
10803              * memory; otherwise we don't care about the attributes and can
10804              * save the S2 translation the effort of computing them.
10805              */
10806             pcacheattrs = &cacheattrs;
10807         }
10808
10809         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
10810                                  &txattrs, &s2prot, &s2size, fi, pcacheattrs);
10811         if (ret) {
10812             assert(fi->type != ARMFault_None);
10813             fi->s2addr = addr;
10814             fi->stage2 = true;
10815             fi->s1ptw = true;
10816             return ~0;
10817         }
10818         if (pcacheattrs && (pcacheattrs->attrs & 0xf0) == 0) {
10819             /* Access was to Device memory: generate Permission fault */
10820             fi->type = ARMFault_Permission;
10821             fi->s2addr = addr;
10822             fi->stage2 = true;
10823             fi->s1ptw = true;
10824             return ~0;
10825         }
10826         addr = s2pa;
10827     }
10828     return addr;
10829 }
10830
10831 /* All loads done in the course of a page table walk go through here. */
10832 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10833                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10834 {
10835     ARMCPU *cpu = ARM_CPU(cs);
10836     CPUARMState *env = &cpu->env;
10837     MemTxAttrs attrs = {};
10838     MemTxResult result = MEMTX_OK;
10839     AddressSpace *as;
10840     uint32_t data;
10841
10842     attrs.secure = is_secure;
10843     as = arm_addressspace(cs, attrs);
10844     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10845     if (fi->s1ptw) {
10846         return 0;
10847     }
10848     if (regime_translation_big_endian(env, mmu_idx)) {
10849         data = address_space_ldl_be(as, addr, attrs, &result);
10850     } else {
10851         data = address_space_ldl_le(as, addr, attrs, &result);
10852     }
10853     if (result == MEMTX_OK) {
10854         return data;
10855     }
10856     fi->type = ARMFault_SyncExternalOnWalk;
10857     fi->ea = arm_extabort_type(result);
10858     return 0;
10859 }
10860
10861 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10862                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10863 {
10864     ARMCPU *cpu = ARM_CPU(cs);
10865     CPUARMState *env = &cpu->env;
10866     MemTxAttrs attrs = {};
10867     MemTxResult result = MEMTX_OK;
10868     AddressSpace *as;
10869     uint64_t data;
10870
10871     attrs.secure = is_secure;
10872     as = arm_addressspace(cs, attrs);
10873     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10874     if (fi->s1ptw) {
10875         return 0;
10876     }
10877     if (regime_translation_big_endian(env, mmu_idx)) {
10878         data = address_space_ldq_be(as, addr, attrs, &result);
10879     } else {
10880         data = address_space_ldq_le(as, addr, attrs, &result);
10881     }
10882     if (result == MEMTX_OK) {
10883         return data;
10884     }
10885     fi->type = ARMFault_SyncExternalOnWalk;
10886     fi->ea = arm_extabort_type(result);
10887     return 0;
10888 }
10889
10890 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10891                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10892                              hwaddr *phys_ptr, int *prot,
10893                              target_ulong *page_size,
10894                              ARMMMUFaultInfo *fi)
10895 {
10896     CPUState *cs = CPU(arm_env_get_cpu(env));
10897     int level = 1;
10898     uint32_t table;
10899     uint32_t desc;
10900     int type;
10901     int ap;
10902     int domain = 0;
10903     int domain_prot;
10904     hwaddr phys_addr;
10905     uint32_t dacr;
10906
10907     /* Pagetable walk.  */
10908     /* Lookup l1 descriptor.  */
10909     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10910         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10911         fi->type = ARMFault_Translation;
10912         goto do_fault;
10913     }
10914     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10915                        mmu_idx, fi);
10916     if (fi->type != ARMFault_None) {
10917         goto do_fault;
10918     }
10919     type = (desc & 3);
10920     domain = (desc >> 5) & 0x0f;
10921     if (regime_el(env, mmu_idx) == 1) {
10922         dacr = env->cp15.dacr_ns;
10923     } else {
10924         dacr = env->cp15.dacr_s;
10925     }
10926     domain_prot = (dacr >> (domain * 2)) & 3;
10927     if (type == 0) {
10928         /* Section translation fault.  */
10929         fi->type = ARMFault_Translation;
10930         goto do_fault;
10931     }
10932     if (type != 2) {
10933         level = 2;
10934     }
10935     if (domain_prot == 0 || domain_prot == 2) {
10936         fi->type = ARMFault_Domain;
10937         goto do_fault;
10938     }
10939     if (type == 2) {
10940         /* 1Mb section.  */
10941         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10942         ap = (desc >> 10) & 3;
10943         *page_size = 1024 * 1024;
10944     } else {
10945         /* Lookup l2 entry.  */
10946         if (type == 1) {
10947             /* Coarse pagetable.  */
10948             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10949         } else {
10950             /* Fine pagetable.  */
10951             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10952         }
10953         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10954                            mmu_idx, fi);
10955         if (fi->type != ARMFault_None) {
10956             goto do_fault;
10957         }
10958         switch (desc & 3) {
10959         case 0: /* Page translation fault.  */
10960             fi->type = ARMFault_Translation;
10961             goto do_fault;
10962         case 1: /* 64k page.  */
10963             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10964             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10965             *page_size = 0x10000;
10966             break;
10967         case 2: /* 4k page.  */
10968             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10969             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10970             *page_size = 0x1000;
10971             break;
10972         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10973             if (type == 1) {
10974                 /* ARMv6/XScale extended small page format */
10975                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10976                     || arm_feature(env, ARM_FEATURE_V6)) {
10977                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10978                     *page_size = 0x1000;
10979                 } else {
10980                     /* UNPREDICTABLE in ARMv5; we choose to take a
10981                      * page translation fault.
10982                      */
10983                     fi->type = ARMFault_Translation;
10984                     goto do_fault;
10985                 }
10986             } else {
10987                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10988                 *page_size = 0x400;
10989             }
10990             ap = (desc >> 4) & 3;
10991             break;
10992         default:
10993             /* Never happens, but compiler isn't smart enough to tell.  */
10994             abort();
10995         }
10996     }
10997     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10998     *prot |= *prot ? PAGE_EXEC : 0;
10999     if (!(*prot & (1 << access_type))) {
11000         /* Access permission fault.  */
11001         fi->type = ARMFault_Permission;
11002         goto do_fault;
11003     }
11004     *phys_ptr = phys_addr;
11005     return false;
11006 do_fault:
11007     fi->domain = domain;
11008     fi->level = level;
11009     return true;
11010 }
11011
11012 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
11013                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
11014                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
11015                              target_ulong *page_size, ARMMMUFaultInfo *fi)
11016 {
11017     CPUState *cs = CPU(arm_env_get_cpu(env));
11018     int level = 1;
11019     uint32_t table;
11020     uint32_t desc;
11021     uint32_t xn;
11022     uint32_t pxn = 0;
11023     int type;
11024     int ap;
11025     int domain = 0;
11026     int domain_prot;
11027     hwaddr phys_addr;
11028     uint32_t dacr;
11029     bool ns;
11030
11031     /* Pagetable walk.  */
11032     /* Lookup l1 descriptor.  */
11033     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
11034         /* Section translation fault if page walk is disabled by PD0 or PD1 */
11035         fi->type = ARMFault_Translation;
11036         goto do_fault;
11037     }
11038     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11039                        mmu_idx, fi);
11040     if (fi->type != ARMFault_None) {
11041         goto do_fault;
11042     }
11043     type = (desc & 3);
11044     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
11045         /* Section translation fault, or attempt to use the encoding
11046          * which is Reserved on implementations without PXN.
11047          */
11048         fi->type = ARMFault_Translation;
11049         goto do_fault;
11050     }
11051     if ((type == 1) || !(desc & (1 << 18))) {
11052         /* Page or Section.  */
11053         domain = (desc >> 5) & 0x0f;
11054     }
11055     if (regime_el(env, mmu_idx) == 1) {
11056         dacr = env->cp15.dacr_ns;
11057     } else {
11058         dacr = env->cp15.dacr_s;
11059     }
11060     if (type == 1) {
11061         level = 2;
11062     }
11063     domain_prot = (dacr >> (domain * 2)) & 3;
11064     if (domain_prot == 0 || domain_prot == 2) {
11065         /* Section or Page domain fault */
11066         fi->type = ARMFault_Domain;
11067         goto do_fault;
11068     }
11069     if (type != 1) {
11070         if (desc & (1 << 18)) {
11071             /* Supersection.  */
11072             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
11073             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
11074             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
11075             *page_size = 0x1000000;
11076         } else {
11077             /* Section.  */
11078             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
11079             *page_size = 0x100000;
11080         }
11081         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
11082         xn = desc & (1 << 4);
11083         pxn = desc & 1;
11084         ns = extract32(desc, 19, 1);
11085     } else {
11086         if (arm_feature(env, ARM_FEATURE_PXN)) {
11087             pxn = (desc >> 2) & 1;
11088         }
11089         ns = extract32(desc, 3, 1);
11090         /* Lookup l2 entry.  */
11091         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11092         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11093                            mmu_idx, fi);
11094         if (fi->type != ARMFault_None) {
11095             goto do_fault;
11096         }
11097         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
11098         switch (desc & 3) {
11099         case 0: /* Page translation fault.  */
11100             fi->type = ARMFault_Translation;
11101             goto do_fault;
11102         case 1: /* 64k page.  */
11103             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11104             xn = desc & (1 << 15);
11105             *page_size = 0x10000;
11106             break;
11107         case 2: case 3: /* 4k page.  */
11108             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11109             xn = desc & 1;
11110             *page_size = 0x1000;
11111             break;
11112         default:
11113             /* Never happens, but compiler isn't smart enough to tell.  */
11114             abort();
11115         }
11116     }
11117     if (domain_prot == 3) {
11118         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11119     } else {
11120         if (pxn && !regime_is_user(env, mmu_idx)) {
11121             xn = 1;
11122         }
11123         if (xn && access_type == MMU_INST_FETCH) {
11124             fi->type = ARMFault_Permission;
11125             goto do_fault;
11126         }
11127
11128         if (arm_feature(env, ARM_FEATURE_V6K) &&
11129                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
11130             /* The simplified model uses AP[0] as an access control bit.  */
11131             if ((ap & 1) == 0) {
11132                 /* Access flag fault.  */
11133                 fi->type = ARMFault_AccessFlag;
11134                 goto do_fault;
11135             }
11136             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
11137         } else {
11138             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11139         }
11140         if (*prot && !xn) {
11141             *prot |= PAGE_EXEC;
11142         }
11143         if (!(*prot & (1 << access_type))) {
11144             /* Access permission fault.  */
11145             fi->type = ARMFault_Permission;
11146             goto do_fault;
11147         }
11148     }
11149     if (ns) {
11150         /* The NS bit will (as required by the architecture) have no effect if
11151          * the CPU doesn't support TZ or this is a non-secure translation
11152          * regime, because the attribute will already be non-secure.
11153          */
11154         attrs->secure = false;
11155     }
11156     *phys_ptr = phys_addr;
11157     return false;
11158 do_fault:
11159     fi->domain = domain;
11160     fi->level = level;
11161     return true;
11162 }
11163
11164 /*
11165  * check_s2_mmu_setup
11166  * @cpu:        ARMCPU
11167  * @is_aa64:    True if the translation regime is in AArch64 state
11168  * @startlevel: Suggested starting level
11169  * @inputsize:  Bitsize of IPAs
11170  * @stride:     Page-table stride (See the ARM ARM)
11171  *
11172  * Returns true if the suggested S2 translation parameters are OK and
11173  * false otherwise.
11174  */
11175 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
11176                                int inputsize, int stride)
11177 {
11178     const int grainsize = stride + 3;
11179     int startsizecheck;
11180
11181     /* Negative levels are never allowed.  */
11182     if (level < 0) {
11183         return false;
11184     }
11185
11186     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
11187     if (startsizecheck < 1 || startsizecheck > stride + 4) {
11188         return false;
11189     }
11190
11191     if (is_aa64) {
11192         CPUARMState *env = &cpu->env;
11193         unsigned int pamax = arm_pamax(cpu);
11194
11195         switch (stride) {
11196         case 13: /* 64KB Pages.  */
11197             if (level == 0 || (level == 1 && pamax <= 42)) {
11198                 return false;
11199             }
11200             break;
11201         case 11: /* 16KB Pages.  */
11202             if (level == 0 || (level == 1 && pamax <= 40)) {
11203                 return false;
11204             }
11205             break;
11206         case 9: /* 4KB Pages.  */
11207             if (level == 0 && pamax <= 42) {
11208                 return false;
11209             }
11210             break;
11211         default:
11212             g_assert_not_reached();
11213         }
11214
11215         /* Inputsize checks.  */
11216         if (inputsize > pamax &&
11217             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
11218             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
11219             return false;
11220         }
11221     } else {
11222         /* AArch32 only supports 4KB pages. Assert on that.  */
11223         assert(stride == 9);
11224
11225         if (level == 0) {
11226             return false;
11227         }
11228     }
11229     return true;
11230 }
11231
11232 /* Translate from the 4-bit stage 2 representation of
11233  * memory attributes (without cache-allocation hints) to
11234  * the 8-bit representation of the stage 1 MAIR registers
11235  * (which includes allocation hints).
11236  *
11237  * ref: shared/translation/attrs/S2AttrDecode()
11238  *      .../S2ConvertAttrsHints()
11239  */
11240 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11241 {
11242     uint8_t hiattr = extract32(s2attrs, 2, 2);
11243     uint8_t loattr = extract32(s2attrs, 0, 2);
11244     uint8_t hihint = 0, lohint = 0;
11245
11246     if (hiattr != 0) { /* normal memory */
11247         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
11248             hiattr = loattr = 1; /* non-cacheable */
11249         } else {
11250             if (hiattr != 1) { /* Write-through or write-back */
11251                 hihint = 3; /* RW allocate */
11252             }
11253             if (loattr != 1) { /* Write-through or write-back */
11254                 lohint = 3; /* RW allocate */
11255             }
11256         }
11257     }
11258
11259     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11260 }
11261 #endif /* !CONFIG_USER_ONLY */
11262
11263 ARMVAParameters aa64_va_parameters_both(CPUARMState *env, uint64_t va,
11264                                         ARMMMUIdx mmu_idx)
11265 {
11266     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11267     uint32_t el = regime_el(env, mmu_idx);
11268     bool tbi, tbid, epd, hpd, using16k, using64k;
11269     int select, tsz;
11270
11271     /*
11272      * Bit 55 is always between the two regions, and is canonical for
11273      * determining if address tagging is enabled.
11274      */
11275     select = extract64(va, 55, 1);
11276
11277     if (el > 1) {
11278         tsz = extract32(tcr, 0, 6);
11279         using64k = extract32(tcr, 14, 1);
11280         using16k = extract32(tcr, 15, 1);
11281         if (mmu_idx == ARMMMUIdx_S2NS) {
11282             /* VTCR_EL2 */
11283             tbi = tbid = hpd = false;
11284         } else {
11285             tbi = extract32(tcr, 20, 1);
11286             hpd = extract32(tcr, 24, 1);
11287             tbid = extract32(tcr, 29, 1);
11288         }
11289         epd = false;
11290     } else if (!select) {
11291         tsz = extract32(tcr, 0, 6);
11292         epd = extract32(tcr, 7, 1);
11293         using64k = extract32(tcr, 14, 1);
11294         using16k = extract32(tcr, 15, 1);
11295         tbi = extract64(tcr, 37, 1);
11296         hpd = extract64(tcr, 41, 1);
11297         tbid = extract64(tcr, 51, 1);
11298     } else {
11299         int tg = extract32(tcr, 30, 2);
11300         using16k = tg == 1;
11301         using64k = tg == 3;
11302         tsz = extract32(tcr, 16, 6);
11303         epd = extract32(tcr, 23, 1);
11304         tbi = extract64(tcr, 38, 1);
11305         hpd = extract64(tcr, 42, 1);
11306         tbid = extract64(tcr, 52, 1);
11307     }
11308     tsz = MIN(tsz, 39);  /* TODO: ARMv8.4-TTST */
11309     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
11310
11311     return (ARMVAParameters) {
11312         .tsz = tsz,
11313         .select = select,
11314         .tbi = tbi,
11315         .tbid = tbid,
11316         .epd = epd,
11317         .hpd = hpd,
11318         .using16k = using16k,
11319         .using64k = using64k,
11320     };
11321 }
11322
11323 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11324                                    ARMMMUIdx mmu_idx, bool data)
11325 {
11326     ARMVAParameters ret = aa64_va_parameters_both(env, va, mmu_idx);
11327
11328     /* Present TBI as a composite with TBID.  */
11329     ret.tbi &= (data || !ret.tbid);
11330     return ret;
11331 }
11332
11333 #ifndef CONFIG_USER_ONLY
11334 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11335                                           ARMMMUIdx mmu_idx)
11336 {
11337     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11338     uint32_t el = regime_el(env, mmu_idx);
11339     int select, tsz;
11340     bool epd, hpd;
11341
11342     if (mmu_idx == ARMMMUIdx_S2NS) {
11343         /* VTCR */
11344         bool sext = extract32(tcr, 4, 1);
11345         bool sign = extract32(tcr, 3, 1);
11346
11347         /*
11348          * If the sign-extend bit is not the same as t0sz[3], the result
11349          * is unpredictable. Flag this as a guest error.
11350          */
11351         if (sign != sext) {
11352             qemu_log_mask(LOG_GUEST_ERROR,
11353                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11354         }
11355         tsz = sextract32(tcr, 0, 4) + 8;
11356         select = 0;
11357         hpd = false;
11358         epd = false;
11359     } else if (el == 2) {
11360         /* HTCR */
11361         tsz = extract32(tcr, 0, 3);
11362         select = 0;
11363         hpd = extract64(tcr, 24, 1);
11364         epd = false;
11365     } else {
11366         int t0sz = extract32(tcr, 0, 3);
11367         int t1sz = extract32(tcr, 16, 3);
11368
11369         if (t1sz == 0) {
11370             select = va > (0xffffffffu >> t0sz);
11371         } else {
11372             /* Note that we will detect errors later.  */
11373             select = va >= ~(0xffffffffu >> t1sz);
11374         }
11375         if (!select) {
11376             tsz = t0sz;
11377             epd = extract32(tcr, 7, 1);
11378             hpd = extract64(tcr, 41, 1);
11379         } else {
11380             tsz = t1sz;
11381             epd = extract32(tcr, 23, 1);
11382             hpd = extract64(tcr, 42, 1);
11383         }
11384         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11385         hpd &= extract32(tcr, 6, 1);
11386     }
11387
11388     return (ARMVAParameters) {
11389         .tsz = tsz,
11390         .select = select,
11391         .epd = epd,
11392         .hpd = hpd,
11393     };
11394 }
11395
11396 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
11397                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11398                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11399                                target_ulong *page_size_ptr,
11400                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11401 {
11402     ARMCPU *cpu = arm_env_get_cpu(env);
11403     CPUState *cs = CPU(cpu);
11404     /* Read an LPAE long-descriptor translation table. */
11405     ARMFaultType fault_type = ARMFault_Translation;
11406     uint32_t level;
11407     ARMVAParameters param;
11408     uint64_t ttbr;
11409     hwaddr descaddr, indexmask, indexmask_grainsize;
11410     uint32_t tableattrs;
11411     target_ulong page_size;
11412     uint32_t attrs;
11413     int32_t stride;
11414     int addrsize, inputsize;
11415     TCR *tcr = regime_tcr(env, mmu_idx);
11416     int ap, ns, xn, pxn;
11417     uint32_t el = regime_el(env, mmu_idx);
11418     bool ttbr1_valid;
11419     uint64_t descaddrmask;
11420     bool aarch64 = arm_el_is_aa64(env, el);
11421     bool guarded = false;
11422
11423     /* TODO:
11424      * This code does not handle the different format TCR for VTCR_EL2.
11425      * This code also does not support shareability levels.
11426      * Attribute and permission bit handling should also be checked when adding
11427      * support for those page table walks.
11428      */
11429     if (aarch64) {
11430         param = aa64_va_parameters(env, address, mmu_idx,
11431                                    access_type != MMU_INST_FETCH);
11432         level = 0;
11433         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
11434          * invalid.
11435          */
11436         ttbr1_valid = (el < 2);
11437         addrsize = 64 - 8 * param.tbi;
11438         inputsize = 64 - param.tsz;
11439     } else {
11440         param = aa32_va_parameters(env, address, mmu_idx);
11441         level = 1;
11442         /* There is no TTBR1 for EL2 */
11443         ttbr1_valid = (el != 2);
11444         addrsize = (mmu_idx == ARMMMUIdx_S2NS ? 40 : 32);
11445         inputsize = addrsize - param.tsz;
11446     }
11447
11448     /*
11449      * We determined the region when collecting the parameters, but we
11450      * have not yet validated that the address is valid for the region.
11451      * Extract the top bits and verify that they all match select.
11452      *
11453      * For aa32, if inputsize == addrsize, then we have selected the
11454      * region by exclusion in aa32_va_parameters and there is no more
11455      * validation to do here.
11456      */
11457     if (inputsize < addrsize) {
11458         target_ulong top_bits = sextract64(address, inputsize,
11459                                            addrsize - inputsize);
11460         if (-top_bits != param.select || (param.select && !ttbr1_valid)) {
11461             /* The gap between the two regions is a Translation fault */
11462             fault_type = ARMFault_Translation;
11463             goto do_fault;
11464         }
11465     }
11466
11467     if (param.using64k) {
11468         stride = 13;
11469     } else if (param.using16k) {
11470         stride = 11;
11471     } else {
11472         stride = 9;
11473     }
11474
11475     /* Note that QEMU ignores shareability and cacheability attributes,
11476      * so we don't need to do anything with the SH, ORGN, IRGN fields
11477      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11478      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11479      * implement any ASID-like capability so we can ignore it (instead
11480      * we will always flush the TLB any time the ASID is changed).
11481      */
11482     ttbr = regime_ttbr(env, mmu_idx, param.select);
11483
11484     /* Here we should have set up all the parameters for the translation:
11485      * inputsize, ttbr, epd, stride, tbi
11486      */
11487
11488     if (param.epd) {
11489         /* Translation table walk disabled => Translation fault on TLB miss
11490          * Note: This is always 0 on 64-bit EL2 and EL3.
11491          */
11492         goto do_fault;
11493     }
11494
11495     if (mmu_idx != ARMMMUIdx_S2NS) {
11496         /* The starting level depends on the virtual address size (which can
11497          * be up to 48 bits) and the translation granule size. It indicates
11498          * the number of strides (stride bits at a time) needed to
11499          * consume the bits of the input address. In the pseudocode this is:
11500          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11501          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11502          * our 'stride + 3' and 'stride' is our 'stride'.
11503          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11504          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11505          * = 4 - (inputsize - 4) / stride;
11506          */
11507         level = 4 - (inputsize - 4) / stride;
11508     } else {
11509         /* For stage 2 translations the starting level is specified by the
11510          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11511          */
11512         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11513         uint32_t startlevel;
11514         bool ok;
11515
11516         if (!aarch64 || stride == 9) {
11517             /* AArch32 or 4KB pages */
11518             startlevel = 2 - sl0;
11519         } else {
11520             /* 16KB or 64KB pages */
11521             startlevel = 3 - sl0;
11522         }
11523
11524         /* Check that the starting level is valid. */
11525         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11526                                 inputsize, stride);
11527         if (!ok) {
11528             fault_type = ARMFault_Translation;
11529             goto do_fault;
11530         }
11531         level = startlevel;
11532     }
11533
11534     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
11535     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
11536
11537     /* Now we can extract the actual base address from the TTBR */
11538     descaddr = extract64(ttbr, 0, 48);
11539     descaddr &= ~indexmask;
11540
11541     /* The address field in the descriptor goes up to bit 39 for ARMv7
11542      * but up to bit 47 for ARMv8, but we use the descaddrmask
11543      * up to bit 39 for AArch32, because we don't need other bits in that case
11544      * to construct next descriptor address (anyway they should be all zeroes).
11545      */
11546     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
11547                    ~indexmask_grainsize;
11548
11549     /* Secure accesses start with the page table in secure memory and
11550      * can be downgraded to non-secure at any step. Non-secure accesses
11551      * remain non-secure. We implement this by just ORing in the NSTable/NS
11552      * bits at each step.
11553      */
11554     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11555     for (;;) {
11556         uint64_t descriptor;
11557         bool nstable;
11558
11559         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11560         descaddr &= ~7ULL;
11561         nstable = extract32(tableattrs, 4, 1);
11562         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11563         if (fi->type != ARMFault_None) {
11564             goto do_fault;
11565         }
11566
11567         if (!(descriptor & 1) ||
11568             (!(descriptor & 2) && (level == 3))) {
11569             /* Invalid, or the Reserved level 3 encoding */
11570             goto do_fault;
11571         }
11572         descaddr = descriptor & descaddrmask;
11573
11574         if ((descriptor & 2) && (level < 3)) {
11575             /* Table entry. The top five bits are attributes which may
11576              * propagate down through lower levels of the table (and
11577              * which are all arranged so that 0 means "no effect", so
11578              * we can gather them up by ORing in the bits at each level).
11579              */
11580             tableattrs |= extract64(descriptor, 59, 5);
11581             level++;
11582             indexmask = indexmask_grainsize;
11583             continue;
11584         }
11585         /* Block entry at level 1 or 2, or page entry at level 3.
11586          * These are basically the same thing, although the number
11587          * of bits we pull in from the vaddr varies.
11588          */
11589         page_size = (1ULL << ((stride * (4 - level)) + 3));
11590         descaddr |= (address & (page_size - 1));
11591         /* Extract attributes from the descriptor */
11592         attrs = extract64(descriptor, 2, 10)
11593             | (extract64(descriptor, 52, 12) << 10);
11594
11595         if (mmu_idx == ARMMMUIdx_S2NS) {
11596             /* Stage 2 table descriptors do not include any attribute fields */
11597             break;
11598         }
11599         /* Merge in attributes from table descriptors */
11600         attrs |= nstable << 3; /* NS */
11601         guarded = extract64(descriptor, 50, 1);  /* GP */
11602         if (param.hpd) {
11603             /* HPD disables all the table attributes except NSTable.  */
11604             break;
11605         }
11606         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11607         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11608          * means "force PL1 access only", which means forcing AP[1] to 0.
11609          */
11610         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11611         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11612         break;
11613     }
11614     /* Here descaddr is the final physical address, and attributes
11615      * are all in attrs.
11616      */
11617     fault_type = ARMFault_AccessFlag;
11618     if ((attrs & (1 << 8)) == 0) {
11619         /* Access flag */
11620         goto do_fault;
11621     }
11622
11623     ap = extract32(attrs, 4, 2);
11624     xn = extract32(attrs, 12, 1);
11625
11626     if (mmu_idx == ARMMMUIdx_S2NS) {
11627         ns = true;
11628         *prot = get_S2prot(env, ap, xn);
11629     } else {
11630         ns = extract32(attrs, 3, 1);
11631         pxn = extract32(attrs, 11, 1);
11632         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11633     }
11634
11635     fault_type = ARMFault_Permission;
11636     if (!(*prot & (1 << access_type))) {
11637         goto do_fault;
11638     }
11639
11640     if (ns) {
11641         /* The NS bit will (as required by the architecture) have no effect if
11642          * the CPU doesn't support TZ or this is a non-secure translation
11643          * regime, because the attribute will already be non-secure.
11644          */
11645         txattrs->secure = false;
11646     }
11647     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11648     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11649         txattrs->target_tlb_bit0 = true;
11650     }
11651
11652     if (cacheattrs != NULL) {
11653         if (mmu_idx == ARMMMUIdx_S2NS) {
11654             cacheattrs->attrs = convert_stage2_attrs(env,
11655                                                      extract32(attrs, 0, 4));
11656         } else {
11657             /* Index into MAIR registers for cache attributes */
11658             uint8_t attrindx = extract32(attrs, 0, 3);
11659             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11660             assert(attrindx <= 7);
11661             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11662         }
11663         cacheattrs->shareability = extract32(attrs, 6, 2);
11664     }
11665
11666     *phys_ptr = descaddr;
11667     *page_size_ptr = page_size;
11668     return false;
11669
11670 do_fault:
11671     fi->type = fault_type;
11672     fi->level = level;
11673     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11674     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
11675     return true;
11676 }
11677
11678 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11679                                                 ARMMMUIdx mmu_idx,
11680                                                 int32_t address, int *prot)
11681 {
11682     if (!arm_feature(env, ARM_FEATURE_M)) {
11683         *prot = PAGE_READ | PAGE_WRITE;
11684         switch (address) {
11685         case 0xF0000000 ... 0xFFFFFFFF:
11686             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11687                 /* hivecs execing is ok */
11688                 *prot |= PAGE_EXEC;
11689             }
11690             break;
11691         case 0x00000000 ... 0x7FFFFFFF:
11692             *prot |= PAGE_EXEC;
11693             break;
11694         }
11695     } else {
11696         /* Default system address map for M profile cores.
11697          * The architecture specifies which regions are execute-never;
11698          * at the MPU level no other checks are defined.
11699          */
11700         switch (address) {
11701         case 0x00000000 ... 0x1fffffff: /* ROM */
11702         case 0x20000000 ... 0x3fffffff: /* SRAM */
11703         case 0x60000000 ... 0x7fffffff: /* RAM */
11704         case 0x80000000 ... 0x9fffffff: /* RAM */
11705             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11706             break;
11707         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11708         case 0xa0000000 ... 0xbfffffff: /* Device */
11709         case 0xc0000000 ... 0xdfffffff: /* Device */
11710         case 0xe0000000 ... 0xffffffff: /* System */
11711             *prot = PAGE_READ | PAGE_WRITE;
11712             break;
11713         default:
11714             g_assert_not_reached();
11715         }
11716     }
11717 }
11718
11719 static bool pmsav7_use_background_region(ARMCPU *cpu,
11720                                          ARMMMUIdx mmu_idx, bool is_user)
11721 {
11722     /* Return true if we should use the default memory map as a
11723      * "background" region if there are no hits against any MPU regions.
11724      */
11725     CPUARMState *env = &cpu->env;
11726
11727     if (is_user) {
11728         return false;
11729     }
11730
11731     if (arm_feature(env, ARM_FEATURE_M)) {
11732         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11733             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11734     } else {
11735         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11736     }
11737 }
11738
11739 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11740 {
11741     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11742     return arm_feature(env, ARM_FEATURE_M) &&
11743         extract32(address, 20, 12) == 0xe00;
11744 }
11745
11746 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11747 {
11748     /* True if address is in the M profile system region
11749      * 0xe0000000 - 0xffffffff
11750      */
11751     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11752 }
11753
11754 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11755                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11756                                  hwaddr *phys_ptr, int *prot,
11757                                  target_ulong *page_size,
11758                                  ARMMMUFaultInfo *fi)
11759 {
11760     ARMCPU *cpu = arm_env_get_cpu(env);
11761     int n;
11762     bool is_user = regime_is_user(env, mmu_idx);
11763
11764     *phys_ptr = address;
11765     *page_size = TARGET_PAGE_SIZE;
11766     *prot = 0;
11767
11768     if (regime_translation_disabled(env, mmu_idx) ||
11769         m_is_ppb_region(env, address)) {
11770         /* MPU disabled or M profile PPB access: use default memory map.
11771          * The other case which uses the default memory map in the
11772          * v7M ARM ARM pseudocode is exception vector reads from the vector
11773          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11774          * which always does a direct read using address_space_ldl(), rather
11775          * than going via this function, so we don't need to check that here.
11776          */
11777         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11778     } else { /* MPU enabled */
11779         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11780             /* region search */
11781             uint32_t base = env->pmsav7.drbar[n];
11782             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11783             uint32_t rmask;
11784             bool srdis = false;
11785
11786             if (!(env->pmsav7.drsr[n] & 0x1)) {
11787                 continue;
11788             }
11789
11790             if (!rsize) {
11791                 qemu_log_mask(LOG_GUEST_ERROR,
11792                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11793                 continue;
11794             }
11795             rsize++;
11796             rmask = (1ull << rsize) - 1;
11797
11798             if (base & rmask) {
11799                 qemu_log_mask(LOG_GUEST_ERROR,
11800                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11801                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11802                               n, base, rmask);
11803                 continue;
11804             }
11805
11806             if (address < base || address > base + rmask) {
11807                 /*
11808                  * Address not in this region. We must check whether the
11809                  * region covers addresses in the same page as our address.
11810                  * In that case we must not report a size that covers the
11811                  * whole page for a subsequent hit against a different MPU
11812                  * region or the background region, because it would result in
11813                  * incorrect TLB hits for subsequent accesses to addresses that
11814                  * are in this MPU region.
11815                  */
11816                 if (ranges_overlap(base, rmask,
11817                                    address & TARGET_PAGE_MASK,
11818                                    TARGET_PAGE_SIZE)) {
11819                     *page_size = 1;
11820                 }
11821                 continue;
11822             }
11823
11824             /* Region matched */
11825
11826             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11827                 int i, snd;
11828                 uint32_t srdis_mask;
11829
11830                 rsize -= 3; /* sub region size (power of 2) */
11831                 snd = ((address - base) >> rsize) & 0x7;
11832                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11833
11834                 srdis_mask = srdis ? 0x3 : 0x0;
11835                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11836                     /* This will check in groups of 2, 4 and then 8, whether
11837                      * the subregion bits are consistent. rsize is incremented
11838                      * back up to give the region size, considering consistent
11839                      * adjacent subregions as one region. Stop testing if rsize
11840                      * is already big enough for an entire QEMU page.
11841                      */
11842                     int snd_rounded = snd & ~(i - 1);
11843                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11844                                                      snd_rounded + 8, i);
11845                     if (srdis_mask ^ srdis_multi) {
11846                         break;
11847                     }
11848                     srdis_mask = (srdis_mask << i) | srdis_mask;
11849                     rsize++;
11850                 }
11851             }
11852             if (srdis) {
11853                 continue;
11854             }
11855             if (rsize < TARGET_PAGE_BITS) {
11856                 *page_size = 1 << rsize;
11857             }
11858             break;
11859         }
11860
11861         if (n == -1) { /* no hits */
11862             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11863                 /* background fault */
11864                 fi->type = ARMFault_Background;
11865                 return true;
11866             }
11867             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11868         } else { /* a MPU hit! */
11869             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11870             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11871
11872             if (m_is_system_region(env, address)) {
11873                 /* System space is always execute never */
11874                 xn = 1;
11875             }
11876
11877             if (is_user) { /* User mode AP bit decoding */
11878                 switch (ap) {
11879                 case 0:
11880                 case 1:
11881                 case 5:
11882                     break; /* no access */
11883                 case 3:
11884                     *prot |= PAGE_WRITE;
11885                     /* fall through */
11886                 case 2:
11887                 case 6:
11888                     *prot |= PAGE_READ | PAGE_EXEC;
11889                     break;
11890                 case 7:
11891                     /* for v7M, same as 6; for R profile a reserved value */
11892                     if (arm_feature(env, ARM_FEATURE_M)) {
11893                         *prot |= PAGE_READ | PAGE_EXEC;
11894                         break;
11895                     }
11896                     /* fall through */
11897                 default:
11898                     qemu_log_mask(LOG_GUEST_ERROR,
11899                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11900                                   PRIx32 "\n", n, ap);
11901                 }
11902             } else { /* Priv. mode AP bits decoding */
11903                 switch (ap) {
11904                 case 0:
11905                     break; /* no access */
11906                 case 1:
11907                 case 2:
11908                 case 3:
11909                     *prot |= PAGE_WRITE;
11910                     /* fall through */
11911                 case 5:
11912                 case 6:
11913                     *prot |= PAGE_READ | PAGE_EXEC;
11914                     break;
11915                 case 7:
11916                     /* for v7M, same as 6; for R profile a reserved value */
11917                     if (arm_feature(env, ARM_FEATURE_M)) {
11918                         *prot |= PAGE_READ | PAGE_EXEC;
11919                         break;
11920                     }
11921                     /* fall through */
11922                 default:
11923                     qemu_log_mask(LOG_GUEST_ERROR,
11924                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11925                                   PRIx32 "\n", n, ap);
11926                 }
11927             }
11928
11929             /* execute never */
11930             if (xn) {
11931                 *prot &= ~PAGE_EXEC;
11932             }
11933         }
11934     }
11935
11936     fi->type = ARMFault_Permission;
11937     fi->level = 1;
11938     return !(*prot & (1 << access_type));
11939 }
11940
11941 static bool v8m_is_sau_exempt(CPUARMState *env,
11942                               uint32_t address, MMUAccessType access_type)
11943 {
11944     /* The architecture specifies that certain address ranges are
11945      * exempt from v8M SAU/IDAU checks.
11946      */
11947     return
11948         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
11949         (address >= 0xe0000000 && address <= 0xe0002fff) ||
11950         (address >= 0xe000e000 && address <= 0xe000efff) ||
11951         (address >= 0xe002e000 && address <= 0xe002efff) ||
11952         (address >= 0xe0040000 && address <= 0xe0041fff) ||
11953         (address >= 0xe00ff000 && address <= 0xe00fffff);
11954 }
11955
11956 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
11957                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
11958                                 V8M_SAttributes *sattrs)
11959 {
11960     /* Look up the security attributes for this address. Compare the
11961      * pseudocode SecurityCheck() function.
11962      * We assume the caller has zero-initialized *sattrs.
11963      */
11964     ARMCPU *cpu = arm_env_get_cpu(env);
11965     int r;
11966     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
11967     int idau_region = IREGION_NOTVALID;
11968     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11969     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11970
11971     if (cpu->idau) {
11972         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
11973         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
11974
11975         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
11976                    &idau_nsc);
11977     }
11978
11979     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
11980         /* 0xf0000000..0xffffffff is always S for insn fetches */
11981         return;
11982     }
11983
11984     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
11985         sattrs->ns = !regime_is_secure(env, mmu_idx);
11986         return;
11987     }
11988
11989     if (idau_region != IREGION_NOTVALID) {
11990         sattrs->irvalid = true;
11991         sattrs->iregion = idau_region;
11992     }
11993
11994     switch (env->sau.ctrl & 3) {
11995     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
11996         break;
11997     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
11998         sattrs->ns = true;
11999         break;
12000     default: /* SAU.ENABLE == 1 */
12001         for (r = 0; r < cpu->sau_sregion; r++) {
12002             if (env->sau.rlar[r] & 1) {
12003                 uint32_t base = env->sau.rbar[r] & ~0x1f;
12004                 uint32_t limit = env->sau.rlar[r] | 0x1f;
12005
12006                 if (base <= address && limit >= address) {
12007                     if (base > addr_page_base || limit < addr_page_limit) {
12008                         sattrs->subpage = true;
12009                     }
12010                     if (sattrs->srvalid) {
12011                         /* If we hit in more than one region then we must report
12012                          * as Secure, not NS-Callable, with no valid region
12013                          * number info.
12014                          */
12015                         sattrs->ns = false;
12016                         sattrs->nsc = false;
12017                         sattrs->sregion = 0;
12018                         sattrs->srvalid = false;
12019                         break;
12020                     } else {
12021                         if (env->sau.rlar[r] & 2) {
12022                             sattrs->nsc = true;
12023                         } else {
12024                             sattrs->ns = true;
12025                         }
12026                         sattrs->srvalid = true;
12027                         sattrs->sregion = r;
12028                     }
12029                 } else {
12030                     /*
12031                      * Address not in this region. We must check whether the
12032                      * region covers addresses in the same page as our address.
12033                      * In that case we must not report a size that covers the
12034                      * whole page for a subsequent hit against a different MPU
12035                      * region or the background region, because it would result
12036                      * in incorrect TLB hits for subsequent accesses to
12037                      * addresses that are in this MPU region.
12038                      */
12039                     if (limit >= base &&
12040                         ranges_overlap(base, limit - base + 1,
12041                                        addr_page_base,
12042                                        TARGET_PAGE_SIZE)) {
12043                         sattrs->subpage = true;
12044                     }
12045                 }
12046             }
12047         }
12048         break;
12049     }
12050
12051     /*
12052      * The IDAU will override the SAU lookup results if it specifies
12053      * higher security than the SAU does.
12054      */
12055     if (!idau_ns) {
12056         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12057             sattrs->ns = false;
12058             sattrs->nsc = idau_nsc;
12059         }
12060     }
12061 }
12062
12063 static bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12064                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12065                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12066                               int *prot, bool *is_subpage,
12067                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12068 {
12069     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12070      * that a full phys-to-virt translation does).
12071      * mregion is (if not NULL) set to the region number which matched,
12072      * or -1 if no region number is returned (MPU off, address did not
12073      * hit a region, address hit in multiple regions).
12074      * We set is_subpage to true if the region hit doesn't cover the
12075      * entire TARGET_PAGE the address is within.
12076      */
12077     ARMCPU *cpu = arm_env_get_cpu(env);
12078     bool is_user = regime_is_user(env, mmu_idx);
12079     uint32_t secure = regime_is_secure(env, mmu_idx);
12080     int n;
12081     int matchregion = -1;
12082     bool hit = false;
12083     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12084     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12085
12086     *is_subpage = false;
12087     *phys_ptr = address;
12088     *prot = 0;
12089     if (mregion) {
12090         *mregion = -1;
12091     }
12092
12093     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12094      * was an exception vector read from the vector table (which is always
12095      * done using the default system address map), because those accesses
12096      * are done in arm_v7m_load_vector(), which always does a direct
12097      * read using address_space_ldl(), rather than going via this function.
12098      */
12099     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12100         hit = true;
12101     } else if (m_is_ppb_region(env, address)) {
12102         hit = true;
12103     } else {
12104         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12105             hit = true;
12106         }
12107
12108         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12109             /* region search */
12110             /* Note that the base address is bits [31:5] from the register
12111              * with bits [4:0] all zeroes, but the limit address is bits
12112              * [31:5] from the register with bits [4:0] all ones.
12113              */
12114             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12115             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12116
12117             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12118                 /* Region disabled */
12119                 continue;
12120             }
12121
12122             if (address < base || address > limit) {
12123                 /*
12124                  * Address not in this region. We must check whether the
12125                  * region covers addresses in the same page as our address.
12126                  * In that case we must not report a size that covers the
12127                  * whole page for a subsequent hit against a different MPU
12128                  * region or the background region, because it would result in
12129                  * incorrect TLB hits for subsequent accesses to addresses that
12130                  * are in this MPU region.
12131                  */
12132                 if (limit >= base &&
12133                     ranges_overlap(base, limit - base + 1,
12134                                    addr_page_base,
12135                                    TARGET_PAGE_SIZE)) {
12136                     *is_subpage = true;
12137                 }
12138                 continue;
12139             }
12140
12141             if (base > addr_page_base || limit < addr_page_limit) {
12142                 *is_subpage = true;
12143             }
12144
12145             if (matchregion != -1) {
12146                 /* Multiple regions match -- always a failure (unlike
12147                  * PMSAv7 where highest-numbered-region wins)
12148                  */
12149                 fi->type = ARMFault_Permission;
12150                 fi->level = 1;
12151                 return true;
12152             }
12153
12154             matchregion = n;
12155             hit = true;
12156         }
12157     }
12158
12159     if (!hit) {
12160         /* background fault */
12161         fi->type = ARMFault_Background;
12162         return true;
12163     }
12164
12165     if (matchregion == -1) {
12166         /* hit using the background region */
12167         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12168     } else {
12169         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12170         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12171
12172         if (m_is_system_region(env, address)) {
12173             /* System space is always execute never */
12174             xn = 1;
12175         }
12176
12177         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12178         if (*prot && !xn) {
12179             *prot |= PAGE_EXEC;
12180         }
12181         /* We don't need to look the attribute up in the MAIR0/MAIR1
12182          * registers because that only tells us about cacheability.
12183          */
12184         if (mregion) {
12185             *mregion = matchregion;
12186         }
12187     }
12188
12189     fi->type = ARMFault_Permission;
12190     fi->level = 1;
12191     return !(*prot & (1 << access_type));
12192 }
12193
12194
12195 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12196                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12197                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12198                                  int *prot, target_ulong *page_size,
12199                                  ARMMMUFaultInfo *fi)
12200 {
12201     uint32_t secure = regime_is_secure(env, mmu_idx);
12202     V8M_SAttributes sattrs = {};
12203     bool ret;
12204     bool mpu_is_subpage;
12205
12206     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12207         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12208         if (access_type == MMU_INST_FETCH) {
12209             /* Instruction fetches always use the MMU bank and the
12210              * transaction attribute determined by the fetch address,
12211              * regardless of CPU state. This is painful for QEMU
12212              * to handle, because it would mean we need to encode
12213              * into the mmu_idx not just the (user, negpri) information
12214              * for the current security state but also that for the
12215              * other security state, which would balloon the number
12216              * of mmu_idx values needed alarmingly.
12217              * Fortunately we can avoid this because it's not actually
12218              * possible to arbitrarily execute code from memory with
12219              * the wrong security attribute: it will always generate
12220              * an exception of some kind or another, apart from the
12221              * special case of an NS CPU executing an SG instruction
12222              * in S&NSC memory. So we always just fail the translation
12223              * here and sort things out in the exception handler
12224              * (including possibly emulating an SG instruction).
12225              */
12226             if (sattrs.ns != !secure) {
12227                 if (sattrs.nsc) {
12228                     fi->type = ARMFault_QEMU_NSCExec;
12229                 } else {
12230                     fi->type = ARMFault_QEMU_SFault;
12231                 }
12232                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12233                 *phys_ptr = address;
12234                 *prot = 0;
12235                 return true;
12236             }
12237         } else {
12238             /* For data accesses we always use the MMU bank indicated
12239              * by the current CPU state, but the security attributes
12240              * might downgrade a secure access to nonsecure.
12241              */
12242             if (sattrs.ns) {
12243                 txattrs->secure = false;
12244             } else if (!secure) {
12245                 /* NS access to S memory must fault.
12246                  * Architecturally we should first check whether the
12247                  * MPU information for this address indicates that we
12248                  * are doing an unaligned access to Device memory, which
12249                  * should generate a UsageFault instead. QEMU does not
12250                  * currently check for that kind of unaligned access though.
12251                  * If we added it we would need to do so as a special case
12252                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12253                  */
12254                 fi->type = ARMFault_QEMU_SFault;
12255                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12256                 *phys_ptr = address;
12257                 *prot = 0;
12258                 return true;
12259             }
12260         }
12261     }
12262
12263     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12264                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12265     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12266     return ret;
12267 }
12268
12269 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12270                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12271                                  hwaddr *phys_ptr, int *prot,
12272                                  ARMMMUFaultInfo *fi)
12273 {
12274     int n;
12275     uint32_t mask;
12276     uint32_t base;
12277     bool is_user = regime_is_user(env, mmu_idx);
12278
12279     if (regime_translation_disabled(env, mmu_idx)) {
12280         /* MPU disabled.  */
12281         *phys_ptr = address;
12282         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12283         return false;
12284     }
12285
12286     *phys_ptr = address;
12287     for (n = 7; n >= 0; n--) {
12288         base = env->cp15.c6_region[n];
12289         if ((base & 1) == 0) {
12290             continue;
12291         }
12292         mask = 1 << ((base >> 1) & 0x1f);
12293         /* Keep this shift separate from the above to avoid an
12294            (undefined) << 32.  */
12295         mask = (mask << 1) - 1;
12296         if (((base ^ address) & ~mask) == 0) {
12297             break;
12298         }
12299     }
12300     if (n < 0) {
12301         fi->type = ARMFault_Background;
12302         return true;
12303     }
12304
12305     if (access_type == MMU_INST_FETCH) {
12306         mask = env->cp15.pmsav5_insn_ap;
12307     } else {
12308         mask = env->cp15.pmsav5_data_ap;
12309     }
12310     mask = (mask >> (n * 4)) & 0xf;
12311     switch (mask) {
12312     case 0:
12313         fi->type = ARMFault_Permission;
12314         fi->level = 1;
12315         return true;
12316     case 1:
12317         if (is_user) {
12318             fi->type = ARMFault_Permission;
12319             fi->level = 1;
12320             return true;
12321         }
12322         *prot = PAGE_READ | PAGE_WRITE;
12323         break;
12324     case 2:
12325         *prot = PAGE_READ;
12326         if (!is_user) {
12327             *prot |= PAGE_WRITE;
12328         }
12329         break;
12330     case 3:
12331         *prot = PAGE_READ | PAGE_WRITE;
12332         break;
12333     case 5:
12334         if (is_user) {
12335             fi->type = ARMFault_Permission;
12336             fi->level = 1;
12337             return true;
12338         }
12339         *prot = PAGE_READ;
12340         break;
12341     case 6:
12342         *prot = PAGE_READ;
12343         break;
12344     default:
12345         /* Bad permission.  */
12346         fi->type = ARMFault_Permission;
12347         fi->level = 1;
12348         return true;
12349     }
12350     *prot |= PAGE_EXEC;
12351     return false;
12352 }
12353
12354 /* Combine either inner or outer cacheability attributes for normal
12355  * memory, according to table D4-42 and pseudocode procedure
12356  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12357  *
12358  * NB: only stage 1 includes allocation hints (RW bits), leading to
12359  * some asymmetry.
12360  */
12361 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12362 {
12363     if (s1 == 4 || s2 == 4) {
12364         /* non-cacheable has precedence */
12365         return 4;
12366     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12367         /* stage 1 write-through takes precedence */
12368         return s1;
12369     } else if (extract32(s2, 2, 2) == 2) {
12370         /* stage 2 write-through takes precedence, but the allocation hint
12371          * is still taken from stage 1
12372          */
12373         return (2 << 2) | extract32(s1, 0, 2);
12374     } else { /* write-back */
12375         return s1;
12376     }
12377 }
12378
12379 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12380  * and CombineS1S2Desc()
12381  *
12382  * @s1:      Attributes from stage 1 walk
12383  * @s2:      Attributes from stage 2 walk
12384  */
12385 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12386 {
12387     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
12388     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
12389     ARMCacheAttrs ret;
12390
12391     /* Combine shareability attributes (table D4-43) */
12392     if (s1.shareability == 2 || s2.shareability == 2) {
12393         /* if either are outer-shareable, the result is outer-shareable */
12394         ret.shareability = 2;
12395     } else if (s1.shareability == 3 || s2.shareability == 3) {
12396         /* if either are inner-shareable, the result is inner-shareable */
12397         ret.shareability = 3;
12398     } else {
12399         /* both non-shareable */
12400         ret.shareability = 0;
12401     }
12402
12403     /* Combine memory type and cacheability attributes */
12404     if (s1hi == 0 || s2hi == 0) {
12405         /* Device has precedence over normal */
12406         if (s1lo == 0 || s2lo == 0) {
12407             /* nGnRnE has precedence over anything */
12408             ret.attrs = 0;
12409         } else if (s1lo == 4 || s2lo == 4) {
12410             /* non-Reordering has precedence over Reordering */
12411             ret.attrs = 4;  /* nGnRE */
12412         } else if (s1lo == 8 || s2lo == 8) {
12413             /* non-Gathering has precedence over Gathering */
12414             ret.attrs = 8;  /* nGRE */
12415         } else {
12416             ret.attrs = 0xc; /* GRE */
12417         }
12418
12419         /* Any location for which the resultant memory type is any
12420          * type of Device memory is always treated as Outer Shareable.
12421          */
12422         ret.shareability = 2;
12423     } else { /* Normal memory */
12424         /* Outer/inner cacheability combine independently */
12425         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12426                   | combine_cacheattr_nibble(s1lo, s2lo);
12427
12428         if (ret.attrs == 0x44) {
12429             /* Any location for which the resultant memory type is Normal
12430              * Inner Non-cacheable, Outer Non-cacheable is always treated
12431              * as Outer Shareable.
12432              */
12433             ret.shareability = 2;
12434         }
12435     }
12436
12437     return ret;
12438 }
12439
12440
12441 /* get_phys_addr - get the physical address for this virtual address
12442  *
12443  * Find the physical address corresponding to the given virtual address,
12444  * by doing a translation table walk on MMU based systems or using the
12445  * MPU state on MPU based systems.
12446  *
12447  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12448  * prot and page_size may not be filled in, and the populated fsr value provides
12449  * information on why the translation aborted, in the format of a
12450  * DFSR/IFSR fault register, with the following caveats:
12451  *  * we honour the short vs long DFSR format differences.
12452  *  * the WnR bit is never set (the caller must do this).
12453  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12454  *    value.
12455  *
12456  * @env: CPUARMState
12457  * @address: virtual address to get physical address for
12458  * @access_type: 0 for read, 1 for write, 2 for execute
12459  * @mmu_idx: MMU index indicating required translation regime
12460  * @phys_ptr: set to the physical address corresponding to the virtual address
12461  * @attrs: set to the memory transaction attributes to use
12462  * @prot: set to the permissions for the page containing phys_ptr
12463  * @page_size: set to the size of the page containing phys_ptr
12464  * @fi: set to fault info if the translation fails
12465  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12466  */
12467 static bool get_phys_addr(CPUARMState *env, target_ulong address,
12468                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
12469                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12470                           target_ulong *page_size,
12471                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12472 {
12473     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
12474         /* Call ourselves recursively to do the stage 1 and then stage 2
12475          * translations.
12476          */
12477         if (arm_feature(env, ARM_FEATURE_EL2)) {
12478             hwaddr ipa;
12479             int s2_prot;
12480             int ret;
12481             ARMCacheAttrs cacheattrs2 = {};
12482
12483             ret = get_phys_addr(env, address, access_type,
12484                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
12485                                 prot, page_size, fi, cacheattrs);
12486
12487             /* If S1 fails or S2 is disabled, return early.  */
12488             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
12489                 *phys_ptr = ipa;
12490                 return ret;
12491             }
12492
12493             /* S1 is done. Now do S2 translation.  */
12494             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
12495                                      phys_ptr, attrs, &s2_prot,
12496                                      page_size, fi,
12497                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
12498             fi->s2addr = ipa;
12499             /* Combine the S1 and S2 perms.  */
12500             *prot &= s2_prot;
12501
12502             /* Combine the S1 and S2 cache attributes, if needed */
12503             if (!ret && cacheattrs != NULL) {
12504                 if (env->cp15.hcr_el2 & HCR_DC) {
12505                     /*
12506                      * HCR.DC forces the first stage attributes to
12507                      *  Normal Non-Shareable,
12508                      *  Inner Write-Back Read-Allocate Write-Allocate,
12509                      *  Outer Write-Back Read-Allocate Write-Allocate.
12510                      */
12511                     cacheattrs->attrs = 0xff;
12512                     cacheattrs->shareability = 0;
12513                 }
12514                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12515             }
12516
12517             return ret;
12518         } else {
12519             /*
12520              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12521              */
12522             mmu_idx = stage_1_mmu_idx(mmu_idx);
12523         }
12524     }
12525
12526     /* The page table entries may downgrade secure to non-secure, but
12527      * cannot upgrade an non-secure translation regime's attributes
12528      * to secure.
12529      */
12530     attrs->secure = regime_is_secure(env, mmu_idx);
12531     attrs->user = regime_is_user(env, mmu_idx);
12532
12533     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12534      * In v7 and earlier it affects all stage 1 translations.
12535      */
12536     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
12537         && !arm_feature(env, ARM_FEATURE_V8)) {
12538         if (regime_el(env, mmu_idx) == 3) {
12539             address += env->cp15.fcseidr_s;
12540         } else {
12541             address += env->cp15.fcseidr_ns;
12542         }
12543     }
12544
12545     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12546         bool ret;
12547         *page_size = TARGET_PAGE_SIZE;
12548
12549         if (arm_feature(env, ARM_FEATURE_V8)) {
12550             /* PMSAv8 */
12551             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12552                                        phys_ptr, attrs, prot, page_size, fi);
12553         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12554             /* PMSAv7 */
12555             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12556                                        phys_ptr, prot, page_size, fi);
12557         } else {
12558             /* Pre-v7 MPU */
12559             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12560                                        phys_ptr, prot, fi);
12561         }
12562         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12563                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12564                       access_type == MMU_DATA_LOAD ? "reading" :
12565                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12566                       (uint32_t)address, mmu_idx,
12567                       ret ? "Miss" : "Hit",
12568                       *prot & PAGE_READ ? 'r' : '-',
12569                       *prot & PAGE_WRITE ? 'w' : '-',
12570                       *prot & PAGE_EXEC ? 'x' : '-');
12571
12572         return ret;
12573     }
12574
12575     /* Definitely a real MMU, not an MPU */
12576
12577     if (regime_translation_disabled(env, mmu_idx)) {
12578         /* MMU disabled. */
12579         *phys_ptr = address;
12580         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12581         *page_size = TARGET_PAGE_SIZE;
12582         return 0;
12583     }
12584
12585     if (regime_using_lpae_format(env, mmu_idx)) {
12586         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
12587                                   phys_ptr, attrs, prot, page_size,
12588                                   fi, cacheattrs);
12589     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12590         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12591                                 phys_ptr, attrs, prot, page_size, fi);
12592     } else {
12593         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12594                                     phys_ptr, prot, page_size, fi);
12595     }
12596 }
12597
12598 /* Walk the page table and (if the mapping exists) add the page
12599  * to the TLB. Return false on success, or true on failure. Populate
12600  * fsr with ARM DFSR/IFSR fault register format value on failure.
12601  */
12602 bool arm_tlb_fill(CPUState *cs, vaddr address,
12603                   MMUAccessType access_type, int mmu_idx,
12604                   ARMMMUFaultInfo *fi)
12605 {
12606     ARMCPU *cpu = ARM_CPU(cs);
12607     CPUARMState *env = &cpu->env;
12608     hwaddr phys_addr;
12609     target_ulong page_size;
12610     int prot;
12611     int ret;
12612     MemTxAttrs attrs = {};
12613
12614     ret = get_phys_addr(env, address, access_type,
12615                         core_to_arm_mmu_idx(env, mmu_idx), &phys_addr,
12616                         &attrs, &prot, &page_size, fi, NULL);
12617     if (!ret) {
12618         /*
12619          * Map a single [sub]page. Regions smaller than our declared
12620          * target page size are handled specially, so for those we
12621          * pass in the exact addresses.
12622          */
12623         if (page_size >= TARGET_PAGE_SIZE) {
12624             phys_addr &= TARGET_PAGE_MASK;
12625             address &= TARGET_PAGE_MASK;
12626         }
12627         tlb_set_page_with_attrs(cs, address, phys_addr, attrs,
12628                                 prot, mmu_idx, page_size);
12629         return 0;
12630     }
12631
12632     return ret;
12633 }
12634
12635 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12636                                          MemTxAttrs *attrs)
12637 {
12638     ARMCPU *cpu = ARM_CPU(cs);
12639     CPUARMState *env = &cpu->env;
12640     hwaddr phys_addr;
12641     target_ulong page_size;
12642     int prot;
12643     bool ret;
12644     ARMMMUFaultInfo fi = {};
12645     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12646
12647     *attrs = (MemTxAttrs) {};
12648
12649     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
12650                         attrs, &prot, &page_size, &fi, NULL);
12651
12652     if (ret) {
12653         return -1;
12654     }
12655     return phys_addr;
12656 }
12657
12658 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
12659 {
12660     uint32_t mask;
12661     unsigned el = arm_current_el(env);
12662
12663     /* First handle registers which unprivileged can read */
12664
12665     switch (reg) {
12666     case 0 ... 7: /* xPSR sub-fields */
12667         mask = 0;
12668         if ((reg & 1) && el) {
12669             mask |= XPSR_EXCP; /* IPSR (unpriv. reads as zero) */
12670         }
12671         if (!(reg & 4)) {
12672             mask |= XPSR_NZCV | XPSR_Q; /* APSR */
12673             if (arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
12674                 mask |= XPSR_GE;
12675             }
12676         }
12677         /* EPSR reads as zero */
12678         return xpsr_read(env) & mask;
12679         break;
12680     case 20: /* CONTROL */
12681     {
12682         uint32_t value = env->v7m.control[env->v7m.secure];
12683         if (!env->v7m.secure) {
12684             /* SFPA is RAZ/WI from NS; FPCA is stored in the M_REG_S bank */
12685             value |= env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK;
12686         }
12687         return value;
12688     }
12689     case 0x94: /* CONTROL_NS */
12690         /* We have to handle this here because unprivileged Secure code
12691          * can read the NS CONTROL register.
12692          */
12693         if (!env->v7m.secure) {
12694             return 0;
12695         }
12696         return env->v7m.control[M_REG_NS] |
12697             (env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK);
12698     }
12699
12700     if (el == 0) {
12701         return 0; /* unprivileged reads others as zero */
12702     }
12703
12704     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12705         switch (reg) {
12706         case 0x88: /* MSP_NS */
12707             if (!env->v7m.secure) {
12708                 return 0;
12709             }
12710             return env->v7m.other_ss_msp;
12711         case 0x89: /* PSP_NS */
12712             if (!env->v7m.secure) {
12713                 return 0;
12714             }
12715             return env->v7m.other_ss_psp;
12716         case 0x8a: /* MSPLIM_NS */
12717             if (!env->v7m.secure) {
12718                 return 0;
12719             }
12720             return env->v7m.msplim[M_REG_NS];
12721         case 0x8b: /* PSPLIM_NS */
12722             if (!env->v7m.secure) {
12723                 return 0;
12724             }
12725             return env->v7m.psplim[M_REG_NS];
12726         case 0x90: /* PRIMASK_NS */
12727             if (!env->v7m.secure) {
12728                 return 0;
12729             }
12730             return env->v7m.primask[M_REG_NS];
12731         case 0x91: /* BASEPRI_NS */
12732             if (!env->v7m.secure) {
12733                 return 0;
12734             }
12735             return env->v7m.basepri[M_REG_NS];
12736         case 0x93: /* FAULTMASK_NS */
12737             if (!env->v7m.secure) {
12738                 return 0;
12739             }
12740             return env->v7m.faultmask[M_REG_NS];
12741         case 0x98: /* SP_NS */
12742         {
12743             /* This gives the non-secure SP selected based on whether we're
12744              * currently in handler mode or not, using the NS CONTROL.SPSEL.
12745              */
12746             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
12747
12748             if (!env->v7m.secure) {
12749                 return 0;
12750             }
12751             if (!arm_v7m_is_handler_mode(env) && spsel) {
12752                 return env->v7m.other_ss_psp;
12753             } else {
12754                 return env->v7m.other_ss_msp;
12755             }
12756         }
12757         default:
12758             break;
12759         }
12760     }
12761
12762     switch (reg) {
12763     case 8: /* MSP */
12764         return v7m_using_psp(env) ? env->v7m.other_sp : env->regs[13];
12765     case 9: /* PSP */
12766         return v7m_using_psp(env) ? env->regs[13] : env->v7m.other_sp;
12767     case 10: /* MSPLIM */
12768         if (!arm_feature(env, ARM_FEATURE_V8)) {
12769             goto bad_reg;
12770         }
12771         return env->v7m.msplim[env->v7m.secure];
12772     case 11: /* PSPLIM */
12773         if (!arm_feature(env, ARM_FEATURE_V8)) {
12774             goto bad_reg;
12775         }
12776         return env->v7m.psplim[env->v7m.secure];
12777     case 16: /* PRIMASK */
12778         return env->v7m.primask[env->v7m.secure];
12779     case 17: /* BASEPRI */
12780     case 18: /* BASEPRI_MAX */
12781         return env->v7m.basepri[env->v7m.secure];
12782     case 19: /* FAULTMASK */
12783         return env->v7m.faultmask[env->v7m.secure];
12784     default:
12785     bad_reg:
12786         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"
12787                                        " register %d\n", reg);
12788         return 0;
12789     }
12790 }
12791
12792 void HELPER(v7m_msr)(CPUARMState *env, uint32_t maskreg, uint32_t val)
12793 {
12794     /* We're passed bits [11..0] of the instruction; extract
12795      * SYSm and the mask bits.
12796      * Invalid combinations of SYSm and mask are UNPREDICTABLE;
12797      * we choose to treat them as if the mask bits were valid.
12798      * NB that the pseudocode 'mask' variable is bits [11..10],
12799      * whereas ours is [11..8].
12800      */
12801     uint32_t mask = extract32(maskreg, 8, 4);
12802     uint32_t reg = extract32(maskreg, 0, 8);
12803     int cur_el = arm_current_el(env);
12804
12805     if (cur_el == 0 && reg > 7 && reg != 20) {
12806         /*
12807          * only xPSR sub-fields and CONTROL.SFPA may be written by
12808          * unprivileged code
12809          */
12810         return;
12811     }
12812
12813     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12814         switch (reg) {
12815         case 0x88: /* MSP_NS */
12816             if (!env->v7m.secure) {
12817                 return;
12818             }
12819             env->v7m.other_ss_msp = val;
12820             return;
12821         case 0x89: /* PSP_NS */
12822             if (!env->v7m.secure) {
12823                 return;
12824             }
12825             env->v7m.other_ss_psp = val;
12826             return;
12827         case 0x8a: /* MSPLIM_NS */
12828             if (!env->v7m.secure) {
12829                 return;
12830             }
12831             env->v7m.msplim[M_REG_NS] = val & ~7;
12832             return;
12833         case 0x8b: /* PSPLIM_NS */
12834             if (!env->v7m.secure) {
12835                 return;
12836             }
12837             env->v7m.psplim[M_REG_NS] = val & ~7;
12838             return;
12839         case 0x90: /* PRIMASK_NS */
12840             if (!env->v7m.secure) {
12841                 return;
12842             }
12843             env->v7m.primask[M_REG_NS] = val & 1;
12844             return;
12845         case 0x91: /* BASEPRI_NS */
12846             if (!env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_MAIN)) {
12847                 return;
12848             }
12849             env->v7m.basepri[M_REG_NS] = val & 0xff;
12850             return;
12851         case 0x93: /* FAULTMASK_NS */
12852             if (!env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_MAIN)) {
12853                 return;
12854             }
12855             env->v7m.faultmask[M_REG_NS] = val & 1;
12856             return;
12857         case 0x94: /* CONTROL_NS */
12858             if (!env->v7m.secure) {
12859                 return;
12860             }
12861             write_v7m_control_spsel_for_secstate(env,
12862                                                  val & R_V7M_CONTROL_SPSEL_MASK,
12863                                                  M_REG_NS);
12864             if (arm_feature(env, ARM_FEATURE_M_MAIN)) {
12865                 env->v7m.control[M_REG_NS] &= ~R_V7M_CONTROL_NPRIV_MASK;
12866                 env->v7m.control[M_REG_NS] |= val & R_V7M_CONTROL_NPRIV_MASK;
12867             }
12868             /*
12869              * SFPA is RAZ/WI from NS. FPCA is RO if NSACR.CP10 == 0,
12870              * RES0 if the FPU is not present, and is stored in the S bank
12871              */
12872             if (arm_feature(env, ARM_FEATURE_VFP) &&
12873                 extract32(env->v7m.nsacr, 10, 1)) {
12874                 env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_FPCA_MASK;
12875                 env->v7m.control[M_REG_S] |= val & R_V7M_CONTROL_FPCA_MASK;
12876             }
12877             return;
12878         case 0x98: /* SP_NS */
12879         {
12880             /* This gives the non-secure SP selected based on whether we're
12881              * currently in handler mode or not, using the NS CONTROL.SPSEL.
12882              */
12883             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
12884             bool is_psp = !arm_v7m_is_handler_mode(env) && spsel;
12885             uint32_t limit;
12886
12887             if (!env->v7m.secure) {
12888                 return;
12889             }
12890
12891             limit = is_psp ? env->v7m.psplim[false] : env->v7m.msplim[false];
12892
12893             if (val < limit) {
12894                 CPUState *cs = CPU(arm_env_get_cpu(env));
12895
12896                 cpu_restore_state(cs, GETPC(), true);
12897                 raise_exception(env, EXCP_STKOF, 0, 1);
12898             }
12899
12900             if (is_psp) {
12901                 env->v7m.other_ss_psp = val;
12902             } else {
12903                 env->v7m.other_ss_msp = val;
12904             }
12905             return;
12906         }
12907         default:
12908             break;
12909         }
12910     }
12911
12912     switch (reg) {
12913     case 0 ... 7: /* xPSR sub-fields */
12914         /* only APSR is actually writable */
12915         if (!(reg & 4)) {
12916             uint32_t apsrmask = 0;
12917
12918             if (mask & 8) {
12919                 apsrmask |= XPSR_NZCV | XPSR_Q;
12920             }
12921             if ((mask & 4) && arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
12922                 apsrmask |= XPSR_GE;
12923             }
12924             xpsr_write(env, val, apsrmask);
12925         }
12926         break;
12927     case 8: /* MSP */
12928         if (v7m_using_psp(env)) {
12929             env->v7m.other_sp = val;
12930         } else {
12931             env->regs[13] = val;
12932         }
12933         break;
12934     case 9: /* PSP */
12935         if (v7m_using_psp(env)) {
12936             env->regs[13] = val;
12937         } else {
12938             env->v7m.other_sp = val;
12939         }
12940         break;
12941     case 10: /* MSPLIM */
12942         if (!arm_feature(env, ARM_FEATURE_V8)) {
12943             goto bad_reg;
12944         }
12945         env->v7m.msplim[env->v7m.secure] = val & ~7;
12946         break;
12947     case 11: /* PSPLIM */
12948         if (!arm_feature(env, ARM_FEATURE_V8)) {
12949             goto bad_reg;
12950         }
12951         env->v7m.psplim[env->v7m.secure] = val & ~7;
12952         break;
12953     case 16: /* PRIMASK */
12954         env->v7m.primask[env->v7m.secure] = val & 1;
12955         break;
12956     case 17: /* BASEPRI */
12957         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
12958             goto bad_reg;
12959         }
12960         env->v7m.basepri[env->v7m.secure] = val & 0xff;
12961         break;
12962     case 18: /* BASEPRI_MAX */
12963         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
12964             goto bad_reg;
12965         }
12966         val &= 0xff;
12967         if (val != 0 && (val < env->v7m.basepri[env->v7m.secure]
12968                          || env->v7m.basepri[env->v7m.secure] == 0)) {
12969             env->v7m.basepri[env->v7m.secure] = val;
12970         }
12971         break;
12972     case 19: /* FAULTMASK */
12973         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
12974             goto bad_reg;
12975         }
12976         env->v7m.faultmask[env->v7m.secure] = val & 1;
12977         break;
12978     case 20: /* CONTROL */
12979         /*
12980          * Writing to the SPSEL bit only has an effect if we are in
12981          * thread mode; other bits can be updated by any privileged code.
12982          * write_v7m_control_spsel() deals with updating the SPSEL bit in
12983          * env->v7m.control, so we only need update the others.
12984          * For v7M, we must just ignore explicit writes to SPSEL in handler
12985          * mode; for v8M the write is permitted but will have no effect.
12986          * All these bits are writes-ignored from non-privileged code,
12987          * except for SFPA.
12988          */
12989         if (cur_el > 0 && (arm_feature(env, ARM_FEATURE_V8) ||
12990                            !arm_v7m_is_handler_mode(env))) {
12991             write_v7m_control_spsel(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);
12992         }
12993         if (cur_el > 0 && arm_feature(env, ARM_FEATURE_M_MAIN)) {
12994             env->v7m.control[env->v7m.secure] &= ~R_V7M_CONTROL_NPRIV_MASK;
12995             env->v7m.control[env->v7m.secure] |= val & R_V7M_CONTROL_NPRIV_MASK;
12996         }
12997         if (arm_feature(env, ARM_FEATURE_VFP)) {
12998             /*
12999              * SFPA is RAZ/WI from NS or if no FPU.
13000              * FPCA is RO if NSACR.CP10 == 0, RES0 if the FPU is not present.
13001              * Both are stored in the S bank.
13002              */
13003             if (env->v7m.secure) {
13004                 env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
13005                 env->v7m.control[M_REG_S] |= val & R_V7M_CONTROL_SFPA_MASK;
13006             }
13007             if (cur_el > 0 &&
13008                 (env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_SECURITY) ||
13009                  extract32(env->v7m.nsacr, 10, 1))) {
13010                 env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_FPCA_MASK;
13011                 env->v7m.control[M_REG_S] |= val & R_V7M_CONTROL_FPCA_MASK;
13012             }
13013         }
13014         break;
13015     default:
13016     bad_reg:
13017         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"
13018                                        " register %d\n", reg);
13019         return;
13020     }
13021 }
13022
13023 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
13024 {
13025     /* Implement the TT instruction. op is bits [7:6] of the insn. */
13026     bool forceunpriv = op & 1;
13027     bool alt = op & 2;
13028     V8M_SAttributes sattrs = {};
13029     uint32_t tt_resp;
13030     bool r, rw, nsr, nsrw, mrvalid;
13031     int prot;
13032     ARMMMUFaultInfo fi = {};
13033     MemTxAttrs attrs = {};
13034     hwaddr phys_addr;
13035     ARMMMUIdx mmu_idx;
13036     uint32_t mregion;
13037     bool targetpriv;
13038     bool targetsec = env->v7m.secure;
13039     bool is_subpage;
13040
13041     /* Work out what the security state and privilege level we're
13042      * interested in is...
13043      */
13044     if (alt) {
13045         targetsec = !targetsec;
13046     }
13047
13048     if (forceunpriv) {
13049         targetpriv = false;
13050     } else {
13051         targetpriv = arm_v7m_is_handler_mode(env) ||
13052             !(env->v7m.control[targetsec] & R_V7M_CONTROL_NPRIV_MASK);
13053     }
13054
13055     /* ...and then figure out which MMU index this is */
13056     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targetsec, targetpriv);
13057
13058     /* We know that the MPU and SAU don't care about the access type
13059      * for our purposes beyond that we don't want to claim to be
13060      * an insn fetch, so we arbitrarily call this a read.
13061      */
13062
13063     /* MPU region info only available for privileged or if
13064      * inspecting the other MPU state.
13065      */
13066     if (arm_current_el(env) != 0 || alt) {
13067         /* We can ignore the return value as prot is always set */
13068         pmsav8_mpu_lookup(env, addr, MMU_DATA_LOAD, mmu_idx,
13069                           &phys_addr, &attrs, &prot, &is_subpage,
13070                           &fi, &mregion);
13071         if (mregion == -1) {
13072             mrvalid = false;
13073             mregion = 0;
13074         } else {
13075             mrvalid = true;
13076         }
13077         r = prot & PAGE_READ;
13078         rw = prot & PAGE_WRITE;
13079     } else {
13080         r = false;
13081         rw = false;
13082         mrvalid = false;
13083         mregion = 0;
13084     }
13085
13086     if (env->v7m.secure) {
13087         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
13088         nsr = sattrs.ns && r;
13089         nsrw = sattrs.ns && rw;
13090     } else {
13091         sattrs.ns = true;
13092         nsr = false;
13093         nsrw = false;
13094     }
13095
13096     tt_resp = (sattrs.iregion << 24) |
13097         (sattrs.irvalid << 23) |
13098         ((!sattrs.ns) << 22) |
13099         (nsrw << 21) |
13100         (nsr << 20) |
13101         (rw << 19) |
13102         (r << 18) |
13103         (sattrs.srvalid << 17) |
13104         (mrvalid << 16) |
13105         (sattrs.sregion << 8) |
13106         mregion;
13107
13108     return tt_resp;
13109 }
13110
13111 #endif
13112
13113 void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)
13114 {
13115     /* Implement DC ZVA, which zeroes a fixed-length block of memory.
13116      * Note that we do not implement the (architecturally mandated)
13117      * alignment fault for attempts to use this on Device memory
13118      * (which matches the usual QEMU behaviour of not implementing either
13119      * alignment faults or any memory attribute handling).
13120      */
13121
13122     ARMCPU *cpu = arm_env_get_cpu(env);
13123     uint64_t blocklen = 4 << cpu->dcz_blocksize;
13124     uint64_t vaddr = vaddr_in & ~(blocklen - 1);
13125
13126 #ifndef CONFIG_USER_ONLY
13127     {
13128         /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than
13129          * the block size so we might have to do more than one TLB lookup.
13130          * We know that in fact for any v8 CPU the page size is at least 4K
13131          * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only
13132          * 1K as an artefact of legacy v5 subpage support being present in the
13133          * same QEMU executable.
13134          */
13135         int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);
13136         void *hostaddr[maxidx];
13137         int try, i;
13138         unsigned mmu_idx = cpu_mmu_index(env, false);
13139         TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);
13140
13141         for (try = 0; try < 2; try++) {
13142
13143             for (i = 0; i < maxidx; i++) {
13144                 hostaddr[i] = tlb_vaddr_to_host(env,
13145                                                 vaddr + TARGET_PAGE_SIZE * i,
13146                                                 1, mmu_idx);
13147                 if (!hostaddr[i]) {
13148                     break;
13149                 }
13150             }
13151             if (i == maxidx) {
13152                 /* If it's all in the TLB it's fair game for just writing to;
13153                  * we know we don't need to update dirty status, etc.
13154                  */
13155                 for (i = 0; i < maxidx - 1; i++) {
13156                     memset(hostaddr[i], 0, TARGET_PAGE_SIZE);
13157                 }
13158                 memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));
13159                 return;
13160             }
13161             /* OK, try a store and see if we can populate the tlb. This
13162              * might cause an exception if the memory isn't writable,
13163              * in which case we will longjmp out of here. We must for
13164              * this purpose use the actual register value passed to us
13165              * so that we get the fault address right.
13166              */
13167             helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETPC());
13168             /* Now we can populate the other TLB entries, if any */
13169             for (i = 0; i < maxidx; i++) {
13170                 uint64_t va = vaddr + TARGET_PAGE_SIZE * i;
13171                 if (va != (vaddr_in & TARGET_PAGE_MASK)) {
13172                     helper_ret_stb_mmu(env, va, 0, oi, GETPC());
13173                 }
13174             }
13175         }
13176
13177         /* Slow path (probably attempt to do this to an I/O device or
13178          * similar, or clearing of a block of code we have translations
13179          * cached for). Just do a series of byte writes as the architecture
13180          * demands. It's not worth trying to use a cpu_physical_memory_map(),
13181          * memset(), unmap() sequence here because:
13182          *  + we'd need to account for the blocksize being larger than a page
13183          *  + the direct-RAM access case is almost always going to be dealt
13184          *    with in the fastpath code above, so there's no speed benefit
13185          *  + we would have to deal with the map returning NULL because the
13186          *    bounce buffer was in use
13187          */
13188         for (i = 0; i < blocklen; i++) {
13189             helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETPC());
13190         }
13191     }
13192 #else
13193     memset(g2h(vaddr), 0, blocklen);
13194 #endif
13195 }
13196
13197 /* Note that signed overflow is undefined in C.  The following routines are
13198    careful to use unsigned types where modulo arithmetic is required.
13199    Failure to do so _will_ break on newer gcc.  */
13200
13201 /* Signed saturating arithmetic.  */
13202
13203 /* Perform 16-bit signed saturating addition.  */
13204 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
13205 {
13206     uint16_t res;
13207
13208     res = a + b;
13209     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
13210         if (a & 0x8000)
13211             res = 0x8000;
13212         else
13213             res = 0x7fff;
13214     }
13215     return res;
13216 }
13217
13218 /* Perform 8-bit signed saturating addition.  */
13219 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
13220 {
13221     uint8_t res;
13222
13223     res = a + b;
13224     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
13225         if (a & 0x80)
13226             res = 0x80;
13227         else
13228             res = 0x7f;
13229     }
13230     return res;
13231 }
13232
13233 /* Perform 16-bit signed saturating subtraction.  */
13234 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
13235 {
13236     uint16_t res;
13237
13238     res = a - b;
13239     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
13240         if (a & 0x8000)
13241             res = 0x8000;
13242         else
13243             res = 0x7fff;
13244     }
13245     return res;
13246 }
13247
13248 /* Perform 8-bit signed saturating subtraction.  */
13249 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
13250 {
13251     uint8_t res;
13252
13253     res = a - b;
13254     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
13255         if (a & 0x80)
13256             res = 0x80;
13257         else
13258             res = 0x7f;
13259     }
13260     return res;
13261 }
13262
13263 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
13264 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
13265 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
13266 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
13267 #define PFX q
13268
13269 #include "op_addsub.h"
13270
13271 /* Unsigned saturating arithmetic.  */
13272 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
13273 {
13274     uint16_t res;
13275     res = a + b;
13276     if (res < a)
13277         res = 0xffff;
13278     return res;
13279 }
13280
13281 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
13282 {
13283     if (a > b)
13284         return a - b;
13285     else
13286         return 0;
13287 }
13288
13289 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
13290 {
13291     uint8_t res;
13292     res = a + b;
13293     if (res < a)
13294         res = 0xff;
13295     return res;
13296 }
13297
13298 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
13299 {
13300     if (a > b)
13301         return a - b;
13302     else
13303         return 0;
13304 }
13305
13306 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
13307 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
13308 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
13309 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
13310 #define PFX uq
13311
13312 #include "op_addsub.h"
13313
13314 /* Signed modulo arithmetic.  */
13315 #define SARITH16(a, b, n, op) do { \
13316     int32_t sum; \
13317     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
13318     RESULT(sum, n, 16); \
13319     if (sum >= 0) \
13320         ge |= 3 << (n * 2); \
13321     } while(0)
13322
13323 #define SARITH8(a, b, n, op) do { \
13324     int32_t sum; \
13325     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
13326     RESULT(sum, n, 8); \
13327     if (sum >= 0) \
13328         ge |= 1 << n; \
13329     } while(0)
13330
13331
13332 #define ADD16(a, b, n) SARITH16(a, b, n, +)
13333 #define SUB16(a, b, n) SARITH16(a, b, n, -)
13334 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
13335 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
13336 #define PFX s
13337 #define ARITH_GE
13338
13339 #include "op_addsub.h"
13340
13341 /* Unsigned modulo arithmetic.  */
13342 #define ADD16(a, b, n) do { \
13343     uint32_t sum; \
13344     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
13345     RESULT(sum, n, 16); \
13346     if ((sum >> 16) == 1) \
13347         ge |= 3 << (n * 2); \
13348     } while(0)
13349
13350 #define ADD8(a, b, n) do { \
13351     uint32_t sum; \
13352     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
13353     RESULT(sum, n, 8); \
13354     if ((sum >> 8) == 1) \
13355         ge |= 1 << n; \
13356     } while(0)
13357
13358 #define SUB16(a, b, n) do { \
13359     uint32_t sum; \
13360     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
13361     RESULT(sum, n, 16); \
13362     if ((sum >> 16) == 0) \
13363         ge |= 3 << (n * 2); \
13364     } while(0)
13365
13366 #define SUB8(a, b, n) do { \
13367     uint32_t sum; \
13368     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
13369     RESULT(sum, n, 8); \
13370     if ((sum >> 8) == 0) \
13371         ge |= 1 << n; \
13372     } while(0)
13373
13374 #define PFX u
13375 #define ARITH_GE
13376
13377 #include "op_addsub.h"
13378
13379 /* Halved signed arithmetic.  */
13380 #define ADD16(a, b, n) \
13381   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
13382 #define SUB16(a, b, n) \
13383   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
13384 #define ADD8(a, b, n) \
13385   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
13386 #define SUB8(a, b, n) \
13387   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
13388 #define PFX sh
13389
13390 #include "op_addsub.h"
13391
13392 /* Halved unsigned arithmetic.  */
13393 #define ADD16(a, b, n) \
13394   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13395 #define SUB16(a, b, n) \
13396   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13397 #define ADD8(a, b, n) \
13398   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13399 #define SUB8(a, b, n) \
13400   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13401 #define PFX uh
13402
13403 #include "op_addsub.h"
13404
13405 static inline uint8_t do_usad(uint8_t a, uint8_t b)
13406 {
13407     if (a > b)
13408         return a - b;
13409     else
13410         return b - a;
13411 }
13412
13413 /* Unsigned sum of absolute byte differences.  */
13414 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
13415 {
13416     uint32_t sum;
13417     sum = do_usad(a, b);
13418     sum += do_usad(a >> 8, b >> 8);
13419     sum += do_usad(a >> 16, b >>16);
13420     sum += do_usad(a >> 24, b >> 24);
13421     return sum;
13422 }
13423
13424 /* For ARMv6 SEL instruction.  */
13425 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
13426 {
13427     uint32_t mask;
13428
13429     mask = 0;
13430     if (flags & 1)
13431         mask |= 0xff;
13432     if (flags & 2)
13433         mask |= 0xff00;
13434     if (flags & 4)
13435         mask |= 0xff0000;
13436     if (flags & 8)
13437         mask |= 0xff000000;
13438     return (a & mask) | (b & ~mask);
13439 }
13440
13441 /* CRC helpers.
13442  * The upper bytes of val (above the number specified by 'bytes') must have
13443  * been zeroed out by the caller.
13444  */
13445 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
13446 {
13447     uint8_t buf[4];
13448
13449     stl_le_p(buf, val);
13450
13451     /* zlib crc32 converts the accumulator and output to one's complement.  */
13452     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
13453 }
13454
13455 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
13456 {
13457     uint8_t buf[4];
13458
13459     stl_le_p(buf, val);
13460
13461     /* Linux crc32c converts the output to one's complement.  */
13462     return crc32c(acc, buf, bytes) ^ 0xffffffff;
13463 }
13464
13465 /* Return the exception level to which FP-disabled exceptions should
13466  * be taken, or 0 if FP is enabled.
13467  */
13468 int fp_exception_el(CPUARMState *env, int cur_el)
13469 {
13470 #ifndef CONFIG_USER_ONLY
13471     int fpen;
13472
13473     /* CPACR and the CPTR registers don't exist before v6, so FP is
13474      * always accessible
13475      */
13476     if (!arm_feature(env, ARM_FEATURE_V6)) {
13477         return 0;
13478     }
13479
13480     if (arm_feature(env, ARM_FEATURE_M)) {
13481         /* CPACR can cause a NOCP UsageFault taken to current security state */
13482         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13483             return 1;
13484         }
13485
13486         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13487             if (!extract32(env->v7m.nsacr, 10, 1)) {
13488                 /* FP insns cause a NOCP UsageFault taken to Secure */
13489                 return 3;
13490             }
13491         }
13492
13493         return 0;
13494     }
13495
13496     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13497      * 0, 2 : trap EL0 and EL1/PL1 accesses
13498      * 1    : trap only EL0 accesses
13499      * 3    : trap no accesses
13500      */
13501     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
13502     switch (fpen) {
13503     case 0:
13504     case 2:
13505         if (cur_el == 0 || cur_el == 1) {
13506             /* Trap to PL1, which might be EL1 or EL3 */
13507             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13508                 return 3;
13509             }
13510             return 1;
13511         }
13512         if (cur_el == 3 && !is_a64(env)) {
13513             /* Secure PL1 running at EL3 */
13514             return 3;
13515         }
13516         break;
13517     case 1:
13518         if (cur_el == 0) {
13519             return 1;
13520         }
13521         break;
13522     case 3:
13523         break;
13524     }
13525
13526     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
13527      * check because zero bits in the registers mean "don't trap".
13528      */
13529
13530     /* CPTR_EL2 : present in v7VE or v8 */
13531     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
13532         && !arm_is_secure_below_el3(env)) {
13533         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
13534         return 2;
13535     }
13536
13537     /* CPTR_EL3 : present in v8 */
13538     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
13539         /* Trap all FP ops to EL3 */
13540         return 3;
13541     }
13542 #endif
13543     return 0;
13544 }
13545
13546 ARMMMUIdx arm_v7m_mmu_idx_all(CPUARMState *env,
13547                               bool secstate, bool priv, bool negpri)
13548 {
13549     ARMMMUIdx mmu_idx = ARM_MMU_IDX_M;
13550
13551     if (priv) {
13552         mmu_idx |= ARM_MMU_IDX_M_PRIV;
13553     }
13554
13555     if (negpri) {
13556         mmu_idx |= ARM_MMU_IDX_M_NEGPRI;
13557     }
13558
13559     if (secstate) {
13560         mmu_idx |= ARM_MMU_IDX_M_S;
13561     }
13562
13563     return mmu_idx;
13564 }
13565
13566 ARMMMUIdx arm_v7m_mmu_idx_for_secstate_and_priv(CPUARMState *env,
13567                                                 bool secstate, bool priv)
13568 {
13569     bool negpri = armv7m_nvic_neg_prio_requested(env->nvic, secstate);
13570
13571     return arm_v7m_mmu_idx_all(env, secstate, priv, negpri);
13572 }
13573
13574 /* Return the MMU index for a v7M CPU in the specified security state */
13575 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13576 {
13577     bool priv = arm_current_el(env) != 0;
13578
13579     return arm_v7m_mmu_idx_for_secstate_and_priv(env, secstate, priv);
13580 }
13581
13582 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13583 {
13584     int el;
13585
13586     if (arm_feature(env, ARM_FEATURE_M)) {
13587         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13588     }
13589
13590     el = arm_current_el(env);
13591     if (el < 2 && arm_is_secure_below_el3(env)) {
13592         return ARMMMUIdx_S1SE0 + el;
13593     } else {
13594         return ARMMMUIdx_S12NSE0 + el;
13595     }
13596 }
13597
13598 int cpu_mmu_index(CPUARMState *env, bool ifetch)
13599 {
13600     return arm_to_core_mmu_idx(arm_mmu_idx(env));
13601 }
13602
13603 #ifndef CONFIG_USER_ONLY
13604 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13605 {
13606     return stage_1_mmu_idx(arm_mmu_idx(env));
13607 }
13608 #endif
13609
13610 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13611                           target_ulong *cs_base, uint32_t *pflags)
13612 {
13613     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
13614     int current_el = arm_current_el(env);
13615     int fp_el = fp_exception_el(env, current_el);
13616     uint32_t flags = 0;
13617
13618     if (is_a64(env)) {
13619         ARMCPU *cpu = arm_env_get_cpu(env);
13620         uint64_t sctlr;
13621
13622         *pc = env->pc;
13623         flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
13624
13625         /* Get control bits for tagged addresses.  */
13626         {
13627             ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13628             ARMVAParameters p0 = aa64_va_parameters_both(env, 0, stage1);
13629             int tbii, tbid;
13630
13631             /* FIXME: ARMv8.1-VHE S2 translation regime.  */
13632             if (regime_el(env, stage1) < 2) {
13633                 ARMVAParameters p1 = aa64_va_parameters_both(env, -1, stage1);
13634                 tbid = (p1.tbi << 1) | p0.tbi;
13635                 tbii = tbid & ~((p1.tbid << 1) | p0.tbid);
13636             } else {
13637                 tbid = p0.tbi;
13638                 tbii = tbid & !p0.tbid;
13639             }
13640
13641             flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
13642             flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
13643         }
13644
13645         if (cpu_isar_feature(aa64_sve, cpu)) {
13646             int sve_el = sve_exception_el(env, current_el);
13647             uint32_t zcr_len;
13648
13649             /* If SVE is disabled, but FP is enabled,
13650              * then the effective len is 0.
13651              */
13652             if (sve_el != 0 && fp_el == 0) {
13653                 zcr_len = 0;
13654             } else {
13655                 zcr_len = sve_zcr_len_for_el(env, current_el);
13656             }
13657             flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
13658             flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
13659         }
13660
13661         sctlr = arm_sctlr(env, current_el);
13662
13663         if (cpu_isar_feature(aa64_pauth, cpu)) {
13664             /*
13665              * In order to save space in flags, we record only whether
13666              * pauth is "inactive", meaning all insns are implemented as
13667              * a nop, or "active" when some action must be performed.
13668              * The decision of which action to take is left to a helper.
13669              */
13670             if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13671                 flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
13672             }
13673         }
13674
13675         if (cpu_isar_feature(aa64_bti, cpu)) {
13676             /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13677             if (sctlr & (current_el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13678                 flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
13679             }
13680             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
13681         }
13682     } else {
13683         *pc = env->regs[15];
13684         flags = FIELD_DP32(flags, TBFLAG_A32, THUMB, env->thumb);
13685         flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN, env->vfp.vec_len);
13686         flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE, env->vfp.vec_stride);
13687         flags = FIELD_DP32(flags, TBFLAG_A32, CONDEXEC, env->condexec_bits);
13688         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, arm_sctlr_b(env));
13689         flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
13690         if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)
13691             || arm_el_is_aa64(env, 1) || arm_feature(env, ARM_FEATURE_M)) {
13692             flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
13693         }
13694         /* Note that XSCALE_CPAR shares bits with VECSTRIDE */
13695         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13696             flags = FIELD_DP32(flags, TBFLAG_A32,
13697                                XSCALE_CPAR, env->cp15.c15_cpar);
13698         }
13699     }
13700
13701     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13702
13703     /* The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13704      * states defined in the ARM ARM for software singlestep:
13705      *  SS_ACTIVE   PSTATE.SS   State
13706      *     0            x       Inactive (the TB flag for SS is always 0)
13707      *     1            0       Active-pending
13708      *     1            1       Active-not-pending
13709      */
13710     if (arm_singlestep_active(env)) {
13711         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
13712         if (is_a64(env)) {
13713             if (env->pstate & PSTATE_SS) {
13714                 flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
13715             }
13716         } else {
13717             if (env->uncached_cpsr & PSTATE_SS) {
13718                 flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
13719             }
13720         }
13721     }
13722     if (arm_cpu_data_is_big_endian(env)) {
13723         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
13724     }
13725     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
13726
13727     if (arm_v7m_is_handler_mode(env)) {
13728         flags = FIELD_DP32(flags, TBFLAG_A32, HANDLER, 1);
13729     }
13730
13731     /* v8M always applies stack limit checks unless CCR.STKOFHFNMIGN is
13732      * suppressing them because the requested execution priority is less than 0.
13733      */
13734     if (arm_feature(env, ARM_FEATURE_V8) &&
13735         arm_feature(env, ARM_FEATURE_M) &&
13736         !((mmu_idx  & ARM_MMU_IDX_M_NEGPRI) &&
13737           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13738         flags = FIELD_DP32(flags, TBFLAG_A32, STACKCHECK, 1);
13739     }
13740
13741     if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13742         FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S) != env->v7m.secure) {
13743         flags = FIELD_DP32(flags, TBFLAG_A32, FPCCR_S_WRONG, 1);
13744     }
13745
13746     if (arm_feature(env, ARM_FEATURE_M) &&
13747         (env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13748         (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13749          (env->v7m.secure &&
13750           !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13751         /*
13752          * ASPEN is set, but FPCA/SFPA indicate that there is no active
13753          * FP context; we must create a new FP context before executing
13754          * any FP insn.
13755          */
13756         flags = FIELD_DP32(flags, TBFLAG_A32, NEW_FP_CTXT_NEEDED, 1);
13757     }
13758
13759     if (arm_feature(env, ARM_FEATURE_M)) {
13760         bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13761
13762         if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13763             flags = FIELD_DP32(flags, TBFLAG_A32, LSPACT, 1);
13764         }
13765     }
13766
13767     *pflags = flags;
13768     *cs_base = 0;
13769 }
13770
13771 #ifdef TARGET_AARCH64
13772 /*
13773  * The manual says that when SVE is enabled and VQ is widened the
13774  * implementation is allowed to zero the previously inaccessible
13775  * portion of the registers.  The corollary to that is that when
13776  * SVE is enabled and VQ is narrowed we are also allowed to zero
13777  * the now inaccessible portion of the registers.
13778  *
13779  * The intent of this is that no predicate bit beyond VQ is ever set.
13780  * Which means that some operations on predicate registers themselves
13781  * may operate on full uint64_t or even unrolled across the maximum
13782  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13783  * may well be cheaper than conditionals to restrict the operation
13784  * to the relevant portion of a uint16_t[16].
13785  */
13786 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13787 {
13788     int i, j;
13789     uint64_t pmask;
13790
13791     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13792     assert(vq <= arm_env_get_cpu(env)->sve_max_vq);
13793
13794     /* Zap the high bits of the zregs.  */
13795     for (i = 0; i < 32; i++) {
13796         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13797     }
13798
13799     /* Zap the high bits of the pregs and ffr.  */
13800     pmask = 0;
13801     if (vq & 3) {
13802         pmask = ~(-1ULL << (16 * (vq & 3)));
13803     }
13804     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13805         for (i = 0; i < 17; ++i) {
13806             env->vfp.pregs[i].p[j] &= pmask;
13807         }
13808         pmask = 0;
13809     }
13810 }
13811
13812 /*
13813  * Notice a change in SVE vector size when changing EL.
13814  */
13815 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13816                            int new_el, bool el0_a64)
13817 {
13818     ARMCPU *cpu = arm_env_get_cpu(env);
13819     int old_len, new_len;
13820     bool old_a64, new_a64;
13821
13822     /* Nothing to do if no SVE.  */
13823     if (!cpu_isar_feature(aa64_sve, cpu)) {
13824         return;
13825     }
13826
13827     /* Nothing to do if FP is disabled in either EL.  */
13828     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13829         return;
13830     }
13831
13832     /*
13833      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13834      * at ELx, or not available because the EL is in AArch32 state, then
13835      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13836      * has an effective value of 0".
13837      *
13838      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13839      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13840      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13841      * we already have the correct register contents when encountering the
13842      * vq0->vq0 transition between EL0->EL1.
13843      */
13844     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13845     old_len = (old_a64 && !sve_exception_el(env, old_el)
13846                ? sve_zcr_len_for_el(env, old_el) : 0);
13847     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13848     new_len = (new_a64 && !sve_exception_el(env, new_el)
13849                ? sve_zcr_len_for_el(env, new_el) : 0);
13850
13851     /* When changing vector length, clear inaccessible state.  */
13852     if (new_len < old_len) {
13853         aarch64_sve_narrow_vq(env, new_len + 1);
13854     }
13855 }
13856 #endif
This page took 0.791777 seconds and 4 git commands to generate.