]> Git Repo - qemu.git/blob - target/arm/helper.c
target/arm: Restrict semi-hosting to TCG
[qemu.git] / target / arm / helper.c
1 /*
2  * ARM generic helpers.
3  *
4  * This code is licensed under the GNU GPL v2 or later.
5  *
6  * SPDX-License-Identifier: GPL-2.0-or-later
7  */
8 #include "qemu/osdep.h"
9 #include "qemu/units.h"
10 #include "target/arm/idau.h"
11 #include "trace.h"
12 #include "cpu.h"
13 #include "internals.h"
14 #include "exec/gdbstub.h"
15 #include "exec/helper-proto.h"
16 #include "qemu/host-utils.h"
17 #include "sysemu/sysemu.h"
18 #include "qemu/bitops.h"
19 #include "qemu/crc32c.h"
20 #include "qemu/qemu-print.h"
21 #include "exec/exec-all.h"
22 #include "exec/cpu_ldst.h"
23 #include <zlib.h> /* For crc32 */
24 #include "hw/semihosting/semihost.h"
25 #include "sysemu/cpus.h"
26 #include "sysemu/kvm.h"
27 #include "qemu/range.h"
28 #include "qapi/qapi-commands-machine-target.h"
29 #include "qapi/error.h"
30 #include "qemu/guest-random.h"
31 #ifdef CONFIG_TCG
32 #include "arm_ldst.h"
33 #endif
34
35 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
36
37 #ifndef CONFIG_USER_ONLY
38
39 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
40                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
41                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
42                                target_ulong *page_size_ptr,
43                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
44 #endif
45
46 static void switch_mode(CPUARMState *env, int mode);
47
48 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
49 {
50     int nregs;
51
52     /* VFP data registers are always little-endian.  */
53     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
54     if (reg < nregs) {
55         stq_le_p(buf, *aa32_vfp_dreg(env, reg));
56         return 8;
57     }
58     if (arm_feature(env, ARM_FEATURE_NEON)) {
59         /* Aliases for Q regs.  */
60         nregs += 16;
61         if (reg < nregs) {
62             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
63             stq_le_p(buf, q[0]);
64             stq_le_p(buf + 8, q[1]);
65             return 16;
66         }
67     }
68     switch (reg - nregs) {
69     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
70     case 1: stl_p(buf, vfp_get_fpscr(env)); return 4;
71     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
72     }
73     return 0;
74 }
75
76 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
77 {
78     int nregs;
79
80     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
81     if (reg < nregs) {
82         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
83         return 8;
84     }
85     if (arm_feature(env, ARM_FEATURE_NEON)) {
86         nregs += 16;
87         if (reg < nregs) {
88             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
89             q[0] = ldq_le_p(buf);
90             q[1] = ldq_le_p(buf + 8);
91             return 16;
92         }
93     }
94     switch (reg - nregs) {
95     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
96     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
97     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
98     }
99     return 0;
100 }
101
102 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
103 {
104     switch (reg) {
105     case 0 ... 31:
106         /* 128 bit FP register */
107         {
108             uint64_t *q = aa64_vfp_qreg(env, reg);
109             stq_le_p(buf, q[0]);
110             stq_le_p(buf + 8, q[1]);
111             return 16;
112         }
113     case 32:
114         /* FPSR */
115         stl_p(buf, vfp_get_fpsr(env));
116         return 4;
117     case 33:
118         /* FPCR */
119         stl_p(buf, vfp_get_fpcr(env));
120         return 4;
121     default:
122         return 0;
123     }
124 }
125
126 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
127 {
128     switch (reg) {
129     case 0 ... 31:
130         /* 128 bit FP register */
131         {
132             uint64_t *q = aa64_vfp_qreg(env, reg);
133             q[0] = ldq_le_p(buf);
134             q[1] = ldq_le_p(buf + 8);
135             return 16;
136         }
137     case 32:
138         /* FPSR */
139         vfp_set_fpsr(env, ldl_p(buf));
140         return 4;
141     case 33:
142         /* FPCR */
143         vfp_set_fpcr(env, ldl_p(buf));
144         return 4;
145     default:
146         return 0;
147     }
148 }
149
150 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
151 {
152     assert(ri->fieldoffset);
153     if (cpreg_field_is_64bit(ri)) {
154         return CPREG_FIELD64(env, ri);
155     } else {
156         return CPREG_FIELD32(env, ri);
157     }
158 }
159
160 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
161                       uint64_t value)
162 {
163     assert(ri->fieldoffset);
164     if (cpreg_field_is_64bit(ri)) {
165         CPREG_FIELD64(env, ri) = value;
166     } else {
167         CPREG_FIELD32(env, ri) = value;
168     }
169 }
170
171 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
172 {
173     return (char *)env + ri->fieldoffset;
174 }
175
176 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
177 {
178     /* Raw read of a coprocessor register (as needed for migration, etc). */
179     if (ri->type & ARM_CP_CONST) {
180         return ri->resetvalue;
181     } else if (ri->raw_readfn) {
182         return ri->raw_readfn(env, ri);
183     } else if (ri->readfn) {
184         return ri->readfn(env, ri);
185     } else {
186         return raw_read(env, ri);
187     }
188 }
189
190 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
191                              uint64_t v)
192 {
193     /* Raw write of a coprocessor register (as needed for migration, etc).
194      * Note that constant registers are treated as write-ignored; the
195      * caller should check for success by whether a readback gives the
196      * value written.
197      */
198     if (ri->type & ARM_CP_CONST) {
199         return;
200     } else if (ri->raw_writefn) {
201         ri->raw_writefn(env, ri, v);
202     } else if (ri->writefn) {
203         ri->writefn(env, ri, v);
204     } else {
205         raw_write(env, ri, v);
206     }
207 }
208
209 static int arm_gdb_get_sysreg(CPUARMState *env, uint8_t *buf, int reg)
210 {
211     ARMCPU *cpu = env_archcpu(env);
212     const ARMCPRegInfo *ri;
213     uint32_t key;
214
215     key = cpu->dyn_xml.cpregs_keys[reg];
216     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
217     if (ri) {
218         if (cpreg_field_is_64bit(ri)) {
219             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
220         } else {
221             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
222         }
223     }
224     return 0;
225 }
226
227 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
228 {
229     return 0;
230 }
231
232 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
233 {
234    /* Return true if the regdef would cause an assertion if you called
235     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
236     * program bug for it not to have the NO_RAW flag).
237     * NB that returning false here doesn't necessarily mean that calling
238     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
239     * read/write access functions which are safe for raw use" from "has
240     * read/write access functions which have side effects but has forgotten
241     * to provide raw access functions".
242     * The tests here line up with the conditions in read/write_raw_cp_reg()
243     * and assertions in raw_read()/raw_write().
244     */
245     if ((ri->type & ARM_CP_CONST) ||
246         ri->fieldoffset ||
247         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
248         return false;
249     }
250     return true;
251 }
252
253 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
254 {
255     /* Write the coprocessor state from cpu->env to the (index,value) list. */
256     int i;
257     bool ok = true;
258
259     for (i = 0; i < cpu->cpreg_array_len; i++) {
260         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
261         const ARMCPRegInfo *ri;
262         uint64_t newval;
263
264         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
265         if (!ri) {
266             ok = false;
267             continue;
268         }
269         if (ri->type & ARM_CP_NO_RAW) {
270             continue;
271         }
272
273         newval = read_raw_cp_reg(&cpu->env, ri);
274         if (kvm_sync) {
275             /*
276              * Only sync if the previous list->cpustate sync succeeded.
277              * Rather than tracking the success/failure state for every
278              * item in the list, we just recheck "does the raw write we must
279              * have made in write_list_to_cpustate() read back OK" here.
280              */
281             uint64_t oldval = cpu->cpreg_values[i];
282
283             if (oldval == newval) {
284                 continue;
285             }
286
287             write_raw_cp_reg(&cpu->env, ri, oldval);
288             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
289                 continue;
290             }
291
292             write_raw_cp_reg(&cpu->env, ri, newval);
293         }
294         cpu->cpreg_values[i] = newval;
295     }
296     return ok;
297 }
298
299 bool write_list_to_cpustate(ARMCPU *cpu)
300 {
301     int i;
302     bool ok = true;
303
304     for (i = 0; i < cpu->cpreg_array_len; i++) {
305         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
306         uint64_t v = cpu->cpreg_values[i];
307         const ARMCPRegInfo *ri;
308
309         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
310         if (!ri) {
311             ok = false;
312             continue;
313         }
314         if (ri->type & ARM_CP_NO_RAW) {
315             continue;
316         }
317         /* Write value and confirm it reads back as written
318          * (to catch read-only registers and partially read-only
319          * registers where the incoming migration value doesn't match)
320          */
321         write_raw_cp_reg(&cpu->env, ri, v);
322         if (read_raw_cp_reg(&cpu->env, ri) != v) {
323             ok = false;
324         }
325     }
326     return ok;
327 }
328
329 static void add_cpreg_to_list(gpointer key, gpointer opaque)
330 {
331     ARMCPU *cpu = opaque;
332     uint64_t regidx;
333     const ARMCPRegInfo *ri;
334
335     regidx = *(uint32_t *)key;
336     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
337
338     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
339         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
340         /* The value array need not be initialized at this point */
341         cpu->cpreg_array_len++;
342     }
343 }
344
345 static void count_cpreg(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_array_len++;
356     }
357 }
358
359 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
360 {
361     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
362     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
363
364     if (aidx > bidx) {
365         return 1;
366     }
367     if (aidx < bidx) {
368         return -1;
369     }
370     return 0;
371 }
372
373 void init_cpreg_list(ARMCPU *cpu)
374 {
375     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
376      * Note that we require cpreg_tuples[] to be sorted by key ID.
377      */
378     GList *keys;
379     int arraylen;
380
381     keys = g_hash_table_get_keys(cpu->cp_regs);
382     keys = g_list_sort(keys, cpreg_key_compare);
383
384     cpu->cpreg_array_len = 0;
385
386     g_list_foreach(keys, count_cpreg, cpu);
387
388     arraylen = cpu->cpreg_array_len;
389     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
390     cpu->cpreg_values = g_new(uint64_t, arraylen);
391     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
392     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
393     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
394     cpu->cpreg_array_len = 0;
395
396     g_list_foreach(keys, add_cpreg_to_list, cpu);
397
398     assert(cpu->cpreg_array_len == arraylen);
399
400     g_list_free(keys);
401 }
402
403 /*
404  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
405  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
406  *
407  * access_el3_aa32ns: Used to check AArch32 register views.
408  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
409  */
410 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
411                                         const ARMCPRegInfo *ri,
412                                         bool isread)
413 {
414     bool secure = arm_is_secure_below_el3(env);
415
416     assert(!arm_el_is_aa64(env, 3));
417     if (secure) {
418         return CP_ACCESS_TRAP_UNCATEGORIZED;
419     }
420     return CP_ACCESS_OK;
421 }
422
423 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
424                                                 const ARMCPRegInfo *ri,
425                                                 bool isread)
426 {
427     if (!arm_el_is_aa64(env, 3)) {
428         return access_el3_aa32ns(env, ri, isread);
429     }
430     return CP_ACCESS_OK;
431 }
432
433 /* Some secure-only AArch32 registers trap to EL3 if used from
434  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
435  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
436  * We assume that the .access field is set to PL1_RW.
437  */
438 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
439                                             const ARMCPRegInfo *ri,
440                                             bool isread)
441 {
442     if (arm_current_el(env) == 3) {
443         return CP_ACCESS_OK;
444     }
445     if (arm_is_secure_below_el3(env)) {
446         return CP_ACCESS_TRAP_EL3;
447     }
448     /* This will be EL1 NS and EL2 NS, which just UNDEF */
449     return CP_ACCESS_TRAP_UNCATEGORIZED;
450 }
451
452 /* Check for traps to "powerdown debug" registers, which are controlled
453  * by MDCR.TDOSA
454  */
455 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
456                                    bool isread)
457 {
458     int el = arm_current_el(env);
459     bool mdcr_el2_tdosa = (env->cp15.mdcr_el2 & MDCR_TDOSA) ||
460         (env->cp15.mdcr_el2 & MDCR_TDE) ||
461         (arm_hcr_el2_eff(env) & HCR_TGE);
462
463     if (el < 2 && mdcr_el2_tdosa && !arm_is_secure_below_el3(env)) {
464         return CP_ACCESS_TRAP_EL2;
465     }
466     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
467         return CP_ACCESS_TRAP_EL3;
468     }
469     return CP_ACCESS_OK;
470 }
471
472 /* Check for traps to "debug ROM" registers, which are controlled
473  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
474  */
475 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
476                                   bool isread)
477 {
478     int el = arm_current_el(env);
479     bool mdcr_el2_tdra = (env->cp15.mdcr_el2 & MDCR_TDRA) ||
480         (env->cp15.mdcr_el2 & MDCR_TDE) ||
481         (arm_hcr_el2_eff(env) & HCR_TGE);
482
483     if (el < 2 && mdcr_el2_tdra && !arm_is_secure_below_el3(env)) {
484         return CP_ACCESS_TRAP_EL2;
485     }
486     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
487         return CP_ACCESS_TRAP_EL3;
488     }
489     return CP_ACCESS_OK;
490 }
491
492 /* Check for traps to general debug registers, which are controlled
493  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
494  */
495 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
496                                   bool isread)
497 {
498     int el = arm_current_el(env);
499     bool mdcr_el2_tda = (env->cp15.mdcr_el2 & MDCR_TDA) ||
500         (env->cp15.mdcr_el2 & MDCR_TDE) ||
501         (arm_hcr_el2_eff(env) & HCR_TGE);
502
503     if (el < 2 && mdcr_el2_tda && !arm_is_secure_below_el3(env)) {
504         return CP_ACCESS_TRAP_EL2;
505     }
506     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
507         return CP_ACCESS_TRAP_EL3;
508     }
509     return CP_ACCESS_OK;
510 }
511
512 /* Check for traps to performance monitor registers, which are controlled
513  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
514  */
515 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
516                                  bool isread)
517 {
518     int el = arm_current_el(env);
519
520     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
521         && !arm_is_secure_below_el3(env)) {
522         return CP_ACCESS_TRAP_EL2;
523     }
524     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
525         return CP_ACCESS_TRAP_EL3;
526     }
527     return CP_ACCESS_OK;
528 }
529
530 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
531 {
532     ARMCPU *cpu = env_archcpu(env);
533
534     raw_write(env, ri, value);
535     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
536 }
537
538 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
539 {
540     ARMCPU *cpu = env_archcpu(env);
541
542     if (raw_read(env, ri) != value) {
543         /* Unlike real hardware the qemu TLB uses virtual addresses,
544          * not modified virtual addresses, so this causes a TLB flush.
545          */
546         tlb_flush(CPU(cpu));
547         raw_write(env, ri, value);
548     }
549 }
550
551 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
552                              uint64_t value)
553 {
554     ARMCPU *cpu = env_archcpu(env);
555
556     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
557         && !extended_addresses_enabled(env)) {
558         /* For VMSA (when not using the LPAE long descriptor page table
559          * format) this register includes the ASID, so do a TLB flush.
560          * For PMSA it is purely a process ID and no action is needed.
561          */
562         tlb_flush(CPU(cpu));
563     }
564     raw_write(env, ri, value);
565 }
566
567 /* IS variants of TLB operations must affect all cores */
568 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
569                              uint64_t value)
570 {
571     CPUState *cs = env_cpu(env);
572
573     tlb_flush_all_cpus_synced(cs);
574 }
575
576 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
577                              uint64_t value)
578 {
579     CPUState *cs = env_cpu(env);
580
581     tlb_flush_all_cpus_synced(cs);
582 }
583
584 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
585                              uint64_t value)
586 {
587     CPUState *cs = env_cpu(env);
588
589     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
590 }
591
592 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
593                              uint64_t value)
594 {
595     CPUState *cs = env_cpu(env);
596
597     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
598 }
599
600 /*
601  * Non-IS variants of TLB operations are upgraded to
602  * IS versions if we are at NS EL1 and HCR_EL2.FB is set to
603  * force broadcast of these operations.
604  */
605 static bool tlb_force_broadcast(CPUARMState *env)
606 {
607     return (env->cp15.hcr_el2 & HCR_FB) &&
608         arm_current_el(env) == 1 && arm_is_secure_below_el3(env);
609 }
610
611 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
612                           uint64_t value)
613 {
614     /* Invalidate all (TLBIALL) */
615     ARMCPU *cpu = env_archcpu(env);
616
617     if (tlb_force_broadcast(env)) {
618         tlbiall_is_write(env, NULL, value);
619         return;
620     }
621
622     tlb_flush(CPU(cpu));
623 }
624
625 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
626                           uint64_t value)
627 {
628     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
629     ARMCPU *cpu = env_archcpu(env);
630
631     if (tlb_force_broadcast(env)) {
632         tlbimva_is_write(env, NULL, value);
633         return;
634     }
635
636     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
637 }
638
639 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
640                            uint64_t value)
641 {
642     /* Invalidate by ASID (TLBIASID) */
643     ARMCPU *cpu = env_archcpu(env);
644
645     if (tlb_force_broadcast(env)) {
646         tlbiasid_is_write(env, NULL, value);
647         return;
648     }
649
650     tlb_flush(CPU(cpu));
651 }
652
653 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
654                            uint64_t value)
655 {
656     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
657     ARMCPU *cpu = env_archcpu(env);
658
659     if (tlb_force_broadcast(env)) {
660         tlbimvaa_is_write(env, NULL, value);
661         return;
662     }
663
664     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
665 }
666
667 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
668                                uint64_t value)
669 {
670     CPUState *cs = env_cpu(env);
671
672     tlb_flush_by_mmuidx(cs,
673                         ARMMMUIdxBit_S12NSE1 |
674                         ARMMMUIdxBit_S12NSE0 |
675                         ARMMMUIdxBit_S2NS);
676 }
677
678 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
679                                   uint64_t value)
680 {
681     CPUState *cs = env_cpu(env);
682
683     tlb_flush_by_mmuidx_all_cpus_synced(cs,
684                                         ARMMMUIdxBit_S12NSE1 |
685                                         ARMMMUIdxBit_S12NSE0 |
686                                         ARMMMUIdxBit_S2NS);
687 }
688
689 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
690                             uint64_t value)
691 {
692     /* Invalidate by IPA. This has to invalidate any structures that
693      * contain only stage 2 translation information, but does not need
694      * to apply to structures that contain combined stage 1 and stage 2
695      * translation information.
696      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
697      */
698     CPUState *cs = env_cpu(env);
699     uint64_t pageaddr;
700
701     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
702         return;
703     }
704
705     pageaddr = sextract64(value << 12, 0, 40);
706
707     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
708 }
709
710 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
711                                uint64_t value)
712 {
713     CPUState *cs = env_cpu(env);
714     uint64_t pageaddr;
715
716     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
717         return;
718     }
719
720     pageaddr = sextract64(value << 12, 0, 40);
721
722     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
723                                              ARMMMUIdxBit_S2NS);
724 }
725
726 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
727                               uint64_t value)
728 {
729     CPUState *cs = env_cpu(env);
730
731     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
732 }
733
734 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
735                                  uint64_t value)
736 {
737     CPUState *cs = env_cpu(env);
738
739     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
740 }
741
742 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
743                               uint64_t value)
744 {
745     CPUState *cs = env_cpu(env);
746     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
747
748     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
749 }
750
751 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
752                                  uint64_t value)
753 {
754     CPUState *cs = env_cpu(env);
755     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
756
757     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
758                                              ARMMMUIdxBit_S1E2);
759 }
760
761 static const ARMCPRegInfo cp_reginfo[] = {
762     /* Define the secure and non-secure FCSE identifier CP registers
763      * separately because there is no secure bank in V8 (no _EL3).  This allows
764      * the secure register to be properly reset and migrated. There is also no
765      * v8 EL1 version of the register so the non-secure instance stands alone.
766      */
767     { .name = "FCSEIDR",
768       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
769       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
770       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
771       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
772     { .name = "FCSEIDR_S",
773       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
774       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
775       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
776       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
777     /* Define the secure and non-secure context identifier CP registers
778      * separately because there is no secure bank in V8 (no _EL3).  This allows
779      * the secure register to be properly reset and migrated.  In the
780      * non-secure case, the 32-bit register will have reset and migration
781      * disabled during registration as it is handled by the 64-bit instance.
782      */
783     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
784       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
785       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
786       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
787       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
788     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
789       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
790       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
791       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
792       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
793     REGINFO_SENTINEL
794 };
795
796 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
797     /* NB: Some of these registers exist in v8 but with more precise
798      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
799      */
800     /* MMU Domain access control / MPU write buffer control */
801     { .name = "DACR",
802       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
803       .access = PL1_RW, .resetvalue = 0,
804       .writefn = dacr_write, .raw_writefn = raw_write,
805       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
806                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
807     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
808      * For v6 and v5, these mappings are overly broad.
809      */
810     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
811       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
812     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
813       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
814     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
815       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
816     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
817       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
818     /* Cache maintenance ops; some of this space may be overridden later. */
819     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
820       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
821       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
822     REGINFO_SENTINEL
823 };
824
825 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
826     /* Not all pre-v6 cores implemented this WFI, so this is slightly
827      * over-broad.
828      */
829     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
830       .access = PL1_W, .type = ARM_CP_WFI },
831     REGINFO_SENTINEL
832 };
833
834 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
835     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
836      * is UNPREDICTABLE; we choose to NOP as most implementations do).
837      */
838     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
839       .access = PL1_W, .type = ARM_CP_WFI },
840     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
841      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
842      * OMAPCP will override this space.
843      */
844     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
845       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
846       .resetvalue = 0 },
847     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
848       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
849       .resetvalue = 0 },
850     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
851     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
852       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
853       .resetvalue = 0 },
854     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
855      * implementing it as RAZ means the "debug architecture version" bits
856      * will read as a reserved value, which should cause Linux to not try
857      * to use the debug hardware.
858      */
859     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
860       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
861     /* MMU TLB control. Note that the wildcarding means we cover not just
862      * the unified TLB ops but also the dside/iside/inner-shareable variants.
863      */
864     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
865       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
866       .type = ARM_CP_NO_RAW },
867     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
868       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
869       .type = ARM_CP_NO_RAW },
870     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
871       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
872       .type = ARM_CP_NO_RAW },
873     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
874       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
875       .type = ARM_CP_NO_RAW },
876     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
877       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
878     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
879       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
880     REGINFO_SENTINEL
881 };
882
883 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
884                         uint64_t value)
885 {
886     uint32_t mask = 0;
887
888     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
889     if (!arm_feature(env, ARM_FEATURE_V8)) {
890         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
891          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
892          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
893          */
894         if (arm_feature(env, ARM_FEATURE_VFP)) {
895             /* VFP coprocessor: cp10 & cp11 [23:20] */
896             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
897
898             if (!arm_feature(env, ARM_FEATURE_NEON)) {
899                 /* ASEDIS [31] bit is RAO/WI */
900                 value |= (1 << 31);
901             }
902
903             /* VFPv3 and upwards with NEON implement 32 double precision
904              * registers (D0-D31).
905              */
906             if (!arm_feature(env, ARM_FEATURE_NEON) ||
907                     !arm_feature(env, ARM_FEATURE_VFP3)) {
908                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
909                 value |= (1 << 30);
910             }
911         }
912         value &= mask;
913     }
914
915     /*
916      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
917      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
918      */
919     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
920         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
921         value &= ~(0xf << 20);
922         value |= env->cp15.cpacr_el1 & (0xf << 20);
923     }
924
925     env->cp15.cpacr_el1 = value;
926 }
927
928 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
929 {
930     /*
931      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
932      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
933      */
934     uint64_t value = env->cp15.cpacr_el1;
935
936     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
937         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
938         value &= ~(0xf << 20);
939     }
940     return value;
941 }
942
943
944 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
945 {
946     /* Call cpacr_write() so that we reset with the correct RAO bits set
947      * for our CPU features.
948      */
949     cpacr_write(env, ri, 0);
950 }
951
952 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
953                                    bool isread)
954 {
955     if (arm_feature(env, ARM_FEATURE_V8)) {
956         /* Check if CPACR accesses are to be trapped to EL2 */
957         if (arm_current_el(env) == 1 &&
958             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
959             return CP_ACCESS_TRAP_EL2;
960         /* Check if CPACR accesses are to be trapped to EL3 */
961         } else if (arm_current_el(env) < 3 &&
962                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
963             return CP_ACCESS_TRAP_EL3;
964         }
965     }
966
967     return CP_ACCESS_OK;
968 }
969
970 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
971                                   bool isread)
972 {
973     /* Check if CPTR accesses are set to trap to EL3 */
974     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
975         return CP_ACCESS_TRAP_EL3;
976     }
977
978     return CP_ACCESS_OK;
979 }
980
981 static const ARMCPRegInfo v6_cp_reginfo[] = {
982     /* prefetch by MVA in v6, NOP in v7 */
983     { .name = "MVA_prefetch",
984       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
985       .access = PL1_W, .type = ARM_CP_NOP },
986     /* We need to break the TB after ISB to execute self-modifying code
987      * correctly and also to take any pending interrupts immediately.
988      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
989      */
990     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
991       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
992     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
993       .access = PL0_W, .type = ARM_CP_NOP },
994     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
995       .access = PL0_W, .type = ARM_CP_NOP },
996     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
997       .access = PL1_RW,
998       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
999                              offsetof(CPUARMState, cp15.ifar_ns) },
1000       .resetvalue = 0, },
1001     /* Watchpoint Fault Address Register : should actually only be present
1002      * for 1136, 1176, 11MPCore.
1003      */
1004     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
1005       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
1006     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
1007       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
1008       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
1009       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
1010     REGINFO_SENTINEL
1011 };
1012
1013 /* Definitions for the PMU registers */
1014 #define PMCRN_MASK  0xf800
1015 #define PMCRN_SHIFT 11
1016 #define PMCRLC  0x40
1017 #define PMCRDP  0x10
1018 #define PMCRD   0x8
1019 #define PMCRC   0x4
1020 #define PMCRP   0x2
1021 #define PMCRE   0x1
1022
1023 #define PMXEVTYPER_P          0x80000000
1024 #define PMXEVTYPER_U          0x40000000
1025 #define PMXEVTYPER_NSK        0x20000000
1026 #define PMXEVTYPER_NSU        0x10000000
1027 #define PMXEVTYPER_NSH        0x08000000
1028 #define PMXEVTYPER_M          0x04000000
1029 #define PMXEVTYPER_MT         0x02000000
1030 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1031 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1032                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1033                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1034                                PMXEVTYPER_EVTCOUNT)
1035
1036 #define PMCCFILTR             0xf8000000
1037 #define PMCCFILTR_M           PMXEVTYPER_M
1038 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1039
1040 static inline uint32_t pmu_num_counters(CPUARMState *env)
1041 {
1042   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1043 }
1044
1045 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1046 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1047 {
1048   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1049 }
1050
1051 typedef struct pm_event {
1052     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1053     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1054     bool (*supported)(CPUARMState *);
1055     /*
1056      * Retrieve the current count of the underlying event. The programmed
1057      * counters hold a difference from the return value from this function
1058      */
1059     uint64_t (*get_count)(CPUARMState *);
1060     /*
1061      * Return how many nanoseconds it will take (at a minimum) for count events
1062      * to occur. A negative value indicates the counter will never overflow, or
1063      * that the counter has otherwise arranged for the overflow bit to be set
1064      * and the PMU interrupt to be raised on overflow.
1065      */
1066     int64_t (*ns_per_count)(uint64_t);
1067 } pm_event;
1068
1069 static bool event_always_supported(CPUARMState *env)
1070 {
1071     return true;
1072 }
1073
1074 static uint64_t swinc_get_count(CPUARMState *env)
1075 {
1076     /*
1077      * SW_INCR events are written directly to the pmevcntr's by writes to
1078      * PMSWINC, so there is no underlying count maintained by the PMU itself
1079      */
1080     return 0;
1081 }
1082
1083 static int64_t swinc_ns_per(uint64_t ignored)
1084 {
1085     return -1;
1086 }
1087
1088 /*
1089  * Return the underlying cycle count for the PMU cycle counters. If we're in
1090  * usermode, simply return 0.
1091  */
1092 static uint64_t cycles_get_count(CPUARMState *env)
1093 {
1094 #ifndef CONFIG_USER_ONLY
1095     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1096                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1097 #else
1098     return cpu_get_host_ticks();
1099 #endif
1100 }
1101
1102 #ifndef CONFIG_USER_ONLY
1103 static int64_t cycles_ns_per(uint64_t cycles)
1104 {
1105     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1106 }
1107
1108 static bool instructions_supported(CPUARMState *env)
1109 {
1110     return use_icount == 1 /* Precise instruction counting */;
1111 }
1112
1113 static uint64_t instructions_get_count(CPUARMState *env)
1114 {
1115     return (uint64_t)cpu_get_icount_raw();
1116 }
1117
1118 static int64_t instructions_ns_per(uint64_t icount)
1119 {
1120     return cpu_icount_to_ns((int64_t)icount);
1121 }
1122 #endif
1123
1124 static const pm_event pm_events[] = {
1125     { .number = 0x000, /* SW_INCR */
1126       .supported = event_always_supported,
1127       .get_count = swinc_get_count,
1128       .ns_per_count = swinc_ns_per,
1129     },
1130 #ifndef CONFIG_USER_ONLY
1131     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1132       .supported = instructions_supported,
1133       .get_count = instructions_get_count,
1134       .ns_per_count = instructions_ns_per,
1135     },
1136     { .number = 0x011, /* CPU_CYCLES, Cycle */
1137       .supported = event_always_supported,
1138       .get_count = cycles_get_count,
1139       .ns_per_count = cycles_ns_per,
1140     }
1141 #endif
1142 };
1143
1144 /*
1145  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1146  * events (i.e. the statistical profiling extension), this implementation
1147  * should first be updated to something sparse instead of the current
1148  * supported_event_map[] array.
1149  */
1150 #define MAX_EVENT_ID 0x11
1151 #define UNSUPPORTED_EVENT UINT16_MAX
1152 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1153
1154 /*
1155  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1156  * of ARM event numbers to indices in our pm_events array.
1157  *
1158  * Note: Events in the 0x40XX range are not currently supported.
1159  */
1160 void pmu_init(ARMCPU *cpu)
1161 {
1162     unsigned int i;
1163
1164     /*
1165      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1166      * events to them
1167      */
1168     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1169         supported_event_map[i] = UNSUPPORTED_EVENT;
1170     }
1171     cpu->pmceid0 = 0;
1172     cpu->pmceid1 = 0;
1173
1174     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1175         const pm_event *cnt = &pm_events[i];
1176         assert(cnt->number <= MAX_EVENT_ID);
1177         /* We do not currently support events in the 0x40xx range */
1178         assert(cnt->number <= 0x3f);
1179
1180         if (cnt->supported(&cpu->env)) {
1181             supported_event_map[cnt->number] = i;
1182             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1183             if (cnt->number & 0x20) {
1184                 cpu->pmceid1 |= event_mask;
1185             } else {
1186                 cpu->pmceid0 |= event_mask;
1187             }
1188         }
1189     }
1190 }
1191
1192 /*
1193  * Check at runtime whether a PMU event is supported for the current machine
1194  */
1195 static bool event_supported(uint16_t number)
1196 {
1197     if (number > MAX_EVENT_ID) {
1198         return false;
1199     }
1200     return supported_event_map[number] != UNSUPPORTED_EVENT;
1201 }
1202
1203 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1204                                    bool isread)
1205 {
1206     /* Performance monitor registers user accessibility is controlled
1207      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1208      * trapping to EL2 or EL3 for other accesses.
1209      */
1210     int el = arm_current_el(env);
1211
1212     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1213         return CP_ACCESS_TRAP;
1214     }
1215     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
1216         && !arm_is_secure_below_el3(env)) {
1217         return CP_ACCESS_TRAP_EL2;
1218     }
1219     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1220         return CP_ACCESS_TRAP_EL3;
1221     }
1222
1223     return CP_ACCESS_OK;
1224 }
1225
1226 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1227                                            const ARMCPRegInfo *ri,
1228                                            bool isread)
1229 {
1230     /* ER: event counter read trap control */
1231     if (arm_feature(env, ARM_FEATURE_V8)
1232         && arm_current_el(env) == 0
1233         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1234         && isread) {
1235         return CP_ACCESS_OK;
1236     }
1237
1238     return pmreg_access(env, ri, isread);
1239 }
1240
1241 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1242                                          const ARMCPRegInfo *ri,
1243                                          bool isread)
1244 {
1245     /* SW: software increment write trap control */
1246     if (arm_feature(env, ARM_FEATURE_V8)
1247         && arm_current_el(env) == 0
1248         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1249         && !isread) {
1250         return CP_ACCESS_OK;
1251     }
1252
1253     return pmreg_access(env, ri, isread);
1254 }
1255
1256 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1257                                         const ARMCPRegInfo *ri,
1258                                         bool isread)
1259 {
1260     /* ER: event counter read trap control */
1261     if (arm_feature(env, ARM_FEATURE_V8)
1262         && arm_current_el(env) == 0
1263         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1264         return CP_ACCESS_OK;
1265     }
1266
1267     return pmreg_access(env, ri, isread);
1268 }
1269
1270 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1271                                          const ARMCPRegInfo *ri,
1272                                          bool isread)
1273 {
1274     /* CR: cycle counter read trap control */
1275     if (arm_feature(env, ARM_FEATURE_V8)
1276         && arm_current_el(env) == 0
1277         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1278         && isread) {
1279         return CP_ACCESS_OK;
1280     }
1281
1282     return pmreg_access(env, ri, isread);
1283 }
1284
1285 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1286  * the current EL, security state, and register configuration.
1287  */
1288 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1289 {
1290     uint64_t filter;
1291     bool e, p, u, nsk, nsu, nsh, m;
1292     bool enabled, prohibited, filtered;
1293     bool secure = arm_is_secure(env);
1294     int el = arm_current_el(env);
1295     uint8_t hpmn = env->cp15.mdcr_el2 & MDCR_HPMN;
1296
1297     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1298         return false;
1299     }
1300
1301     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1302             (counter < hpmn || counter == 31)) {
1303         e = env->cp15.c9_pmcr & PMCRE;
1304     } else {
1305         e = env->cp15.mdcr_el2 & MDCR_HPME;
1306     }
1307     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1308
1309     if (!secure) {
1310         if (el == 2 && (counter < hpmn || counter == 31)) {
1311             prohibited = env->cp15.mdcr_el2 & MDCR_HPMD;
1312         } else {
1313             prohibited = false;
1314         }
1315     } else {
1316         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1317            (env->cp15.mdcr_el3 & MDCR_SPME);
1318     }
1319
1320     if (prohibited && counter == 31) {
1321         prohibited = env->cp15.c9_pmcr & PMCRDP;
1322     }
1323
1324     if (counter == 31) {
1325         filter = env->cp15.pmccfiltr_el0;
1326     } else {
1327         filter = env->cp15.c14_pmevtyper[counter];
1328     }
1329
1330     p   = filter & PMXEVTYPER_P;
1331     u   = filter & PMXEVTYPER_U;
1332     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1333     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1334     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1335     m   = arm_el_is_aa64(env, 1) &&
1336               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1337
1338     if (el == 0) {
1339         filtered = secure ? u : u != nsu;
1340     } else if (el == 1) {
1341         filtered = secure ? p : p != nsk;
1342     } else if (el == 2) {
1343         filtered = !nsh;
1344     } else { /* EL3 */
1345         filtered = m != p;
1346     }
1347
1348     if (counter != 31) {
1349         /*
1350          * If not checking PMCCNTR, ensure the counter is setup to an event we
1351          * support
1352          */
1353         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1354         if (!event_supported(event)) {
1355             return false;
1356         }
1357     }
1358
1359     return enabled && !prohibited && !filtered;
1360 }
1361
1362 static void pmu_update_irq(CPUARMState *env)
1363 {
1364     ARMCPU *cpu = env_archcpu(env);
1365     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1366             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1367 }
1368
1369 /*
1370  * Ensure c15_ccnt is the guest-visible count so that operations such as
1371  * enabling/disabling the counter or filtering, modifying the count itself,
1372  * etc. can be done logically. This is essentially a no-op if the counter is
1373  * not enabled at the time of the call.
1374  */
1375 static void pmccntr_op_start(CPUARMState *env)
1376 {
1377     uint64_t cycles = cycles_get_count(env);
1378
1379     if (pmu_counter_enabled(env, 31)) {
1380         uint64_t eff_cycles = cycles;
1381         if (env->cp15.c9_pmcr & PMCRD) {
1382             /* Increment once every 64 processor clock cycles */
1383             eff_cycles /= 64;
1384         }
1385
1386         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1387
1388         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1389                                  1ull << 63 : 1ull << 31;
1390         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1391             env->cp15.c9_pmovsr |= (1 << 31);
1392             pmu_update_irq(env);
1393         }
1394
1395         env->cp15.c15_ccnt = new_pmccntr;
1396     }
1397     env->cp15.c15_ccnt_delta = cycles;
1398 }
1399
1400 /*
1401  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1402  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1403  * pmccntr_op_start.
1404  */
1405 static void pmccntr_op_finish(CPUARMState *env)
1406 {
1407     if (pmu_counter_enabled(env, 31)) {
1408 #ifndef CONFIG_USER_ONLY
1409         /* Calculate when the counter will next overflow */
1410         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1411         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1412             remaining_cycles = (uint32_t)remaining_cycles;
1413         }
1414         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1415
1416         if (overflow_in > 0) {
1417             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1418                 overflow_in;
1419             ARMCPU *cpu = env_archcpu(env);
1420             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1421         }
1422 #endif
1423
1424         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1425         if (env->cp15.c9_pmcr & PMCRD) {
1426             /* Increment once every 64 processor clock cycles */
1427             prev_cycles /= 64;
1428         }
1429         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1430     }
1431 }
1432
1433 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1434 {
1435
1436     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1437     uint64_t count = 0;
1438     if (event_supported(event)) {
1439         uint16_t event_idx = supported_event_map[event];
1440         count = pm_events[event_idx].get_count(env);
1441     }
1442
1443     if (pmu_counter_enabled(env, counter)) {
1444         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1445
1446         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1447             env->cp15.c9_pmovsr |= (1 << counter);
1448             pmu_update_irq(env);
1449         }
1450         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1451     }
1452     env->cp15.c14_pmevcntr_delta[counter] = count;
1453 }
1454
1455 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1456 {
1457     if (pmu_counter_enabled(env, counter)) {
1458 #ifndef CONFIG_USER_ONLY
1459         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1460         uint16_t event_idx = supported_event_map[event];
1461         uint64_t delta = UINT32_MAX -
1462             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1463         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1464
1465         if (overflow_in > 0) {
1466             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1467                 overflow_in;
1468             ARMCPU *cpu = env_archcpu(env);
1469             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1470         }
1471 #endif
1472
1473         env->cp15.c14_pmevcntr_delta[counter] -=
1474             env->cp15.c14_pmevcntr[counter];
1475     }
1476 }
1477
1478 void pmu_op_start(CPUARMState *env)
1479 {
1480     unsigned int i;
1481     pmccntr_op_start(env);
1482     for (i = 0; i < pmu_num_counters(env); i++) {
1483         pmevcntr_op_start(env, i);
1484     }
1485 }
1486
1487 void pmu_op_finish(CPUARMState *env)
1488 {
1489     unsigned int i;
1490     pmccntr_op_finish(env);
1491     for (i = 0; i < pmu_num_counters(env); i++) {
1492         pmevcntr_op_finish(env, i);
1493     }
1494 }
1495
1496 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1497 {
1498     pmu_op_start(&cpu->env);
1499 }
1500
1501 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1502 {
1503     pmu_op_finish(&cpu->env);
1504 }
1505
1506 void arm_pmu_timer_cb(void *opaque)
1507 {
1508     ARMCPU *cpu = opaque;
1509
1510     /*
1511      * Update all the counter values based on the current underlying counts,
1512      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1513      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1514      * counter may expire.
1515      */
1516     pmu_op_start(&cpu->env);
1517     pmu_op_finish(&cpu->env);
1518 }
1519
1520 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1521                        uint64_t value)
1522 {
1523     pmu_op_start(env);
1524
1525     if (value & PMCRC) {
1526         /* The counter has been reset */
1527         env->cp15.c15_ccnt = 0;
1528     }
1529
1530     if (value & PMCRP) {
1531         unsigned int i;
1532         for (i = 0; i < pmu_num_counters(env); i++) {
1533             env->cp15.c14_pmevcntr[i] = 0;
1534         }
1535     }
1536
1537     /* only the DP, X, D and E bits are writable */
1538     env->cp15.c9_pmcr &= ~0x39;
1539     env->cp15.c9_pmcr |= (value & 0x39);
1540
1541     pmu_op_finish(env);
1542 }
1543
1544 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1545                           uint64_t value)
1546 {
1547     unsigned int i;
1548     for (i = 0; i < pmu_num_counters(env); i++) {
1549         /* Increment a counter's count iff: */
1550         if ((value & (1 << i)) && /* counter's bit is set */
1551                 /* counter is enabled and not filtered */
1552                 pmu_counter_enabled(env, i) &&
1553                 /* counter is SW_INCR */
1554                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1555             pmevcntr_op_start(env, i);
1556
1557             /*
1558              * Detect if this write causes an overflow since we can't predict
1559              * PMSWINC overflows like we can for other events
1560              */
1561             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1562
1563             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1564                 env->cp15.c9_pmovsr |= (1 << i);
1565                 pmu_update_irq(env);
1566             }
1567
1568             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1569
1570             pmevcntr_op_finish(env, i);
1571         }
1572     }
1573 }
1574
1575 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1576 {
1577     uint64_t ret;
1578     pmccntr_op_start(env);
1579     ret = env->cp15.c15_ccnt;
1580     pmccntr_op_finish(env);
1581     return ret;
1582 }
1583
1584 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1585                          uint64_t value)
1586 {
1587     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1588      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1589      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1590      * accessed.
1591      */
1592     env->cp15.c9_pmselr = value & 0x1f;
1593 }
1594
1595 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1596                         uint64_t value)
1597 {
1598     pmccntr_op_start(env);
1599     env->cp15.c15_ccnt = value;
1600     pmccntr_op_finish(env);
1601 }
1602
1603 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1604                             uint64_t value)
1605 {
1606     uint64_t cur_val = pmccntr_read(env, NULL);
1607
1608     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1609 }
1610
1611 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1612                             uint64_t value)
1613 {
1614     pmccntr_op_start(env);
1615     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1616     pmccntr_op_finish(env);
1617 }
1618
1619 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1620                             uint64_t value)
1621 {
1622     pmccntr_op_start(env);
1623     /* M is not accessible from AArch32 */
1624     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1625         (value & PMCCFILTR);
1626     pmccntr_op_finish(env);
1627 }
1628
1629 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1630 {
1631     /* M is not visible in AArch32 */
1632     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1633 }
1634
1635 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1636                             uint64_t value)
1637 {
1638     value &= pmu_counter_mask(env);
1639     env->cp15.c9_pmcnten |= value;
1640 }
1641
1642 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1643                              uint64_t value)
1644 {
1645     value &= pmu_counter_mask(env);
1646     env->cp15.c9_pmcnten &= ~value;
1647 }
1648
1649 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1650                          uint64_t value)
1651 {
1652     value &= pmu_counter_mask(env);
1653     env->cp15.c9_pmovsr &= ~value;
1654     pmu_update_irq(env);
1655 }
1656
1657 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1658                          uint64_t value)
1659 {
1660     value &= pmu_counter_mask(env);
1661     env->cp15.c9_pmovsr |= value;
1662     pmu_update_irq(env);
1663 }
1664
1665 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1666                              uint64_t value, const uint8_t counter)
1667 {
1668     if (counter == 31) {
1669         pmccfiltr_write(env, ri, value);
1670     } else if (counter < pmu_num_counters(env)) {
1671         pmevcntr_op_start(env, counter);
1672
1673         /*
1674          * If this counter's event type is changing, store the current
1675          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1676          * pmevcntr_op_finish has the correct baseline when it converts back to
1677          * a delta.
1678          */
1679         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1680             PMXEVTYPER_EVTCOUNT;
1681         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1682         if (old_event != new_event) {
1683             uint64_t count = 0;
1684             if (event_supported(new_event)) {
1685                 uint16_t event_idx = supported_event_map[new_event];
1686                 count = pm_events[event_idx].get_count(env);
1687             }
1688             env->cp15.c14_pmevcntr_delta[counter] = count;
1689         }
1690
1691         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1692         pmevcntr_op_finish(env, counter);
1693     }
1694     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1695      * PMSELR value is equal to or greater than the number of implemented
1696      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1697      */
1698 }
1699
1700 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1701                                const uint8_t counter)
1702 {
1703     if (counter == 31) {
1704         return env->cp15.pmccfiltr_el0;
1705     } else if (counter < pmu_num_counters(env)) {
1706         return env->cp15.c14_pmevtyper[counter];
1707     } else {
1708       /*
1709        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1710        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1711        */
1712         return 0;
1713     }
1714 }
1715
1716 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1717                               uint64_t value)
1718 {
1719     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1720     pmevtyper_write(env, ri, value, counter);
1721 }
1722
1723 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1724                                uint64_t value)
1725 {
1726     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1727     env->cp15.c14_pmevtyper[counter] = value;
1728
1729     /*
1730      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1731      * pmu_op_finish calls when loading saved state for a migration. Because
1732      * we're potentially updating the type of event here, the value written to
1733      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1734      * different counter type. Therefore, we need to set this value to the
1735      * current count for the counter type we're writing so that pmu_op_finish
1736      * has the correct count for its calculation.
1737      */
1738     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1739     if (event_supported(event)) {
1740         uint16_t event_idx = supported_event_map[event];
1741         env->cp15.c14_pmevcntr_delta[counter] =
1742             pm_events[event_idx].get_count(env);
1743     }
1744 }
1745
1746 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1747 {
1748     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1749     return pmevtyper_read(env, ri, counter);
1750 }
1751
1752 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1753                              uint64_t value)
1754 {
1755     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1756 }
1757
1758 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1759 {
1760     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1761 }
1762
1763 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1764                              uint64_t value, uint8_t counter)
1765 {
1766     if (counter < pmu_num_counters(env)) {
1767         pmevcntr_op_start(env, counter);
1768         env->cp15.c14_pmevcntr[counter] = value;
1769         pmevcntr_op_finish(env, counter);
1770     }
1771     /*
1772      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1773      * are CONSTRAINED UNPREDICTABLE.
1774      */
1775 }
1776
1777 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1778                               uint8_t counter)
1779 {
1780     if (counter < pmu_num_counters(env)) {
1781         uint64_t ret;
1782         pmevcntr_op_start(env, counter);
1783         ret = env->cp15.c14_pmevcntr[counter];
1784         pmevcntr_op_finish(env, counter);
1785         return ret;
1786     } else {
1787       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1788        * are CONSTRAINED UNPREDICTABLE. */
1789         return 0;
1790     }
1791 }
1792
1793 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1794                              uint64_t value)
1795 {
1796     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1797     pmevcntr_write(env, ri, value, counter);
1798 }
1799
1800 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1801 {
1802     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1803     return pmevcntr_read(env, ri, counter);
1804 }
1805
1806 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1807                              uint64_t value)
1808 {
1809     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1810     assert(counter < pmu_num_counters(env));
1811     env->cp15.c14_pmevcntr[counter] = value;
1812     pmevcntr_write(env, ri, value, counter);
1813 }
1814
1815 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1816 {
1817     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1818     assert(counter < pmu_num_counters(env));
1819     return env->cp15.c14_pmevcntr[counter];
1820 }
1821
1822 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1823                              uint64_t value)
1824 {
1825     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1826 }
1827
1828 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1829 {
1830     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1831 }
1832
1833 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1834                             uint64_t value)
1835 {
1836     if (arm_feature(env, ARM_FEATURE_V8)) {
1837         env->cp15.c9_pmuserenr = value & 0xf;
1838     } else {
1839         env->cp15.c9_pmuserenr = value & 1;
1840     }
1841 }
1842
1843 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1844                              uint64_t value)
1845 {
1846     /* We have no event counters so only the C bit can be changed */
1847     value &= pmu_counter_mask(env);
1848     env->cp15.c9_pminten |= value;
1849     pmu_update_irq(env);
1850 }
1851
1852 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1853                              uint64_t value)
1854 {
1855     value &= pmu_counter_mask(env);
1856     env->cp15.c9_pminten &= ~value;
1857     pmu_update_irq(env);
1858 }
1859
1860 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1861                        uint64_t value)
1862 {
1863     /* Note that even though the AArch64 view of this register has bits
1864      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1865      * architectural requirements for bits which are RES0 only in some
1866      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1867      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1868      */
1869     raw_write(env, ri, value & ~0x1FULL);
1870 }
1871
1872 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1873 {
1874     /* Begin with base v8.0 state.  */
1875     uint32_t valid_mask = 0x3fff;
1876     ARMCPU *cpu = env_archcpu(env);
1877
1878     if (arm_el_is_aa64(env, 3)) {
1879         value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1880         valid_mask &= ~SCR_NET;
1881     } else {
1882         valid_mask &= ~(SCR_RW | SCR_ST);
1883     }
1884
1885     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1886         valid_mask &= ~SCR_HCE;
1887
1888         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1889          * supported if EL2 exists. The bit is UNK/SBZP when
1890          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1891          * when EL2 is unavailable.
1892          * On ARMv8, this bit is always available.
1893          */
1894         if (arm_feature(env, ARM_FEATURE_V7) &&
1895             !arm_feature(env, ARM_FEATURE_V8)) {
1896             valid_mask &= ~SCR_SMD;
1897         }
1898     }
1899     if (cpu_isar_feature(aa64_lor, cpu)) {
1900         valid_mask |= SCR_TLOR;
1901     }
1902     if (cpu_isar_feature(aa64_pauth, cpu)) {
1903         valid_mask |= SCR_API | SCR_APK;
1904     }
1905
1906     /* Clear all-context RES0 bits.  */
1907     value &= valid_mask;
1908     raw_write(env, ri, value);
1909 }
1910
1911 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1912 {
1913     ARMCPU *cpu = env_archcpu(env);
1914
1915     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1916      * bank
1917      */
1918     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1919                                         ri->secure & ARM_CP_SECSTATE_S);
1920
1921     return cpu->ccsidr[index];
1922 }
1923
1924 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1925                          uint64_t value)
1926 {
1927     raw_write(env, ri, value & 0xf);
1928 }
1929
1930 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1931 {
1932     CPUState *cs = env_cpu(env);
1933     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
1934     uint64_t ret = 0;
1935
1936     if (hcr_el2 & HCR_IMO) {
1937         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1938             ret |= CPSR_I;
1939         }
1940     } else {
1941         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1942             ret |= CPSR_I;
1943         }
1944     }
1945
1946     if (hcr_el2 & HCR_FMO) {
1947         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1948             ret |= CPSR_F;
1949         }
1950     } else {
1951         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1952             ret |= CPSR_F;
1953         }
1954     }
1955
1956     /* External aborts are not possible in QEMU so A bit is always clear */
1957     return ret;
1958 }
1959
1960 static const ARMCPRegInfo v7_cp_reginfo[] = {
1961     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1962     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1963       .access = PL1_W, .type = ARM_CP_NOP },
1964     /* Performance monitors are implementation defined in v7,
1965      * but with an ARM recommended set of registers, which we
1966      * follow.
1967      *
1968      * Performance registers fall into three categories:
1969      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1970      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1971      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1972      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1973      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1974      */
1975     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1976       .access = PL0_RW, .type = ARM_CP_ALIAS,
1977       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1978       .writefn = pmcntenset_write,
1979       .accessfn = pmreg_access,
1980       .raw_writefn = raw_write },
1981     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1982       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1983       .access = PL0_RW, .accessfn = pmreg_access,
1984       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1985       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1986     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1987       .access = PL0_RW,
1988       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1989       .accessfn = pmreg_access,
1990       .writefn = pmcntenclr_write,
1991       .type = ARM_CP_ALIAS },
1992     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1993       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1994       .access = PL0_RW, .accessfn = pmreg_access,
1995       .type = ARM_CP_ALIAS,
1996       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1997       .writefn = pmcntenclr_write },
1998     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1999       .access = PL0_RW, .type = ARM_CP_IO,
2000       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2001       .accessfn = pmreg_access,
2002       .writefn = pmovsr_write,
2003       .raw_writefn = raw_write },
2004     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2005       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2006       .access = PL0_RW, .accessfn = pmreg_access,
2007       .type = ARM_CP_ALIAS | ARM_CP_IO,
2008       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2009       .writefn = pmovsr_write,
2010       .raw_writefn = raw_write },
2011     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2012       .access = PL0_W, .accessfn = pmreg_access_swinc,
2013       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2014       .writefn = pmswinc_write },
2015     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2016       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2017       .access = PL0_W, .accessfn = pmreg_access_swinc,
2018       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2019       .writefn = pmswinc_write },
2020     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2021       .access = PL0_RW, .type = ARM_CP_ALIAS,
2022       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2023       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2024       .raw_writefn = raw_write},
2025     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2026       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2027       .access = PL0_RW, .accessfn = pmreg_access_selr,
2028       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2029       .writefn = pmselr_write, .raw_writefn = raw_write, },
2030     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2031       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2032       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2033       .accessfn = pmreg_access_ccntr },
2034     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2035       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2036       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2037       .type = ARM_CP_IO,
2038       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2039       .readfn = pmccntr_read, .writefn = pmccntr_write,
2040       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2041     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2042       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2043       .access = PL0_RW, .accessfn = pmreg_access,
2044       .type = ARM_CP_ALIAS | ARM_CP_IO,
2045       .resetvalue = 0, },
2046     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2047       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2048       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2049       .access = PL0_RW, .accessfn = pmreg_access,
2050       .type = ARM_CP_IO,
2051       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2052       .resetvalue = 0, },
2053     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2054       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2055       .accessfn = pmreg_access,
2056       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2057     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2058       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2059       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2060       .accessfn = pmreg_access,
2061       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2062     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2063       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2064       .accessfn = pmreg_access_xevcntr,
2065       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2066     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2067       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2068       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2069       .accessfn = pmreg_access_xevcntr,
2070       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2071     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2072       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2073       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2074       .resetvalue = 0,
2075       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2076     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2077       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2078       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2079       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2080       .resetvalue = 0,
2081       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2082     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2083       .access = PL1_RW, .accessfn = access_tpm,
2084       .type = ARM_CP_ALIAS | ARM_CP_IO,
2085       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2086       .resetvalue = 0,
2087       .writefn = pmintenset_write, .raw_writefn = raw_write },
2088     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2089       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2090       .access = PL1_RW, .accessfn = access_tpm,
2091       .type = ARM_CP_IO,
2092       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2093       .writefn = pmintenset_write, .raw_writefn = raw_write,
2094       .resetvalue = 0x0 },
2095     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2096       .access = PL1_RW, .accessfn = access_tpm,
2097       .type = ARM_CP_ALIAS | ARM_CP_IO,
2098       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2099       .writefn = pmintenclr_write, },
2100     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2101       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2102       .access = PL1_RW, .accessfn = access_tpm,
2103       .type = ARM_CP_ALIAS | ARM_CP_IO,
2104       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2105       .writefn = pmintenclr_write },
2106     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2107       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2108       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2109     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2110       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2111       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
2112       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2113                              offsetof(CPUARMState, cp15.csselr_ns) } },
2114     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2115      * just RAZ for all cores:
2116      */
2117     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2118       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2119       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2120     /* Auxiliary fault status registers: these also are IMPDEF, and we
2121      * choose to RAZ/WI for all cores.
2122      */
2123     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2124       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2125       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2126     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2127       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2128       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2129     /* MAIR can just read-as-written because we don't implement caches
2130      * and so don't need to care about memory attributes.
2131      */
2132     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2133       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2134       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2135       .resetvalue = 0 },
2136     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2137       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2138       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2139       .resetvalue = 0 },
2140     /* For non-long-descriptor page tables these are PRRR and NMRR;
2141      * regardless they still act as reads-as-written for QEMU.
2142      */
2143      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2144       * allows them to assign the correct fieldoffset based on the endianness
2145       * handled in the field definitions.
2146       */
2147     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2148       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
2149       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2150                              offsetof(CPUARMState, cp15.mair0_ns) },
2151       .resetfn = arm_cp_reset_ignore },
2152     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2153       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
2154       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2155                              offsetof(CPUARMState, cp15.mair1_ns) },
2156       .resetfn = arm_cp_reset_ignore },
2157     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2158       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2159       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2160     /* 32 bit ITLB invalidates */
2161     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2162       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2163     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2164       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2165     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2166       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2167     /* 32 bit DTLB invalidates */
2168     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2169       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2170     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2171       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2172     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2173       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2174     /* 32 bit TLB invalidates */
2175     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2176       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2177     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2178       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2179     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2180       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2181     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2182       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
2183     REGINFO_SENTINEL
2184 };
2185
2186 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2187     /* 32 bit TLB invalidates, Inner Shareable */
2188     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2189       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
2190     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2191       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
2192     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2193       .type = ARM_CP_NO_RAW, .access = PL1_W,
2194       .writefn = tlbiasid_is_write },
2195     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2196       .type = ARM_CP_NO_RAW, .access = PL1_W,
2197       .writefn = tlbimvaa_is_write },
2198     REGINFO_SENTINEL
2199 };
2200
2201 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2202     /* PMOVSSET is not implemented in v7 before v7ve */
2203     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2204       .access = PL0_RW, .accessfn = pmreg_access,
2205       .type = ARM_CP_ALIAS | ARM_CP_IO,
2206       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2207       .writefn = pmovsset_write,
2208       .raw_writefn = raw_write },
2209     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2210       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2211       .access = PL0_RW, .accessfn = pmreg_access,
2212       .type = ARM_CP_ALIAS | ARM_CP_IO,
2213       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2214       .writefn = pmovsset_write,
2215       .raw_writefn = raw_write },
2216     REGINFO_SENTINEL
2217 };
2218
2219 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2220                         uint64_t value)
2221 {
2222     value &= 1;
2223     env->teecr = value;
2224 }
2225
2226 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2227                                     bool isread)
2228 {
2229     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2230         return CP_ACCESS_TRAP;
2231     }
2232     return CP_ACCESS_OK;
2233 }
2234
2235 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2236     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2237       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2238       .resetvalue = 0,
2239       .writefn = teecr_write },
2240     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2241       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2242       .accessfn = teehbr_access, .resetvalue = 0 },
2243     REGINFO_SENTINEL
2244 };
2245
2246 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2247     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2248       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2249       .access = PL0_RW,
2250       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2251     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2252       .access = PL0_RW,
2253       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2254                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2255       .resetfn = arm_cp_reset_ignore },
2256     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2257       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2258       .access = PL0_R|PL1_W,
2259       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2260       .resetvalue = 0},
2261     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2262       .access = PL0_R|PL1_W,
2263       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2264                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2265       .resetfn = arm_cp_reset_ignore },
2266     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2267       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2268       .access = PL1_RW,
2269       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2270     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2271       .access = PL1_RW,
2272       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2273                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2274       .resetvalue = 0 },
2275     REGINFO_SENTINEL
2276 };
2277
2278 #ifndef CONFIG_USER_ONLY
2279
2280 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2281                                        bool isread)
2282 {
2283     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2284      * Writable only at the highest implemented exception level.
2285      */
2286     int el = arm_current_el(env);
2287
2288     switch (el) {
2289     case 0:
2290         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
2291             return CP_ACCESS_TRAP;
2292         }
2293         break;
2294     case 1:
2295         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2296             arm_is_secure_below_el3(env)) {
2297             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2298             return CP_ACCESS_TRAP_UNCATEGORIZED;
2299         }
2300         break;
2301     case 2:
2302     case 3:
2303         break;
2304     }
2305
2306     if (!isread && el < arm_highest_el(env)) {
2307         return CP_ACCESS_TRAP_UNCATEGORIZED;
2308     }
2309
2310     return CP_ACCESS_OK;
2311 }
2312
2313 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2314                                         bool isread)
2315 {
2316     unsigned int cur_el = arm_current_el(env);
2317     bool secure = arm_is_secure(env);
2318
2319     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
2320     if (cur_el == 0 &&
2321         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2322         return CP_ACCESS_TRAP;
2323     }
2324
2325     if (arm_feature(env, ARM_FEATURE_EL2) &&
2326         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2327         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
2328         return CP_ACCESS_TRAP_EL2;
2329     }
2330     return CP_ACCESS_OK;
2331 }
2332
2333 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2334                                       bool isread)
2335 {
2336     unsigned int cur_el = arm_current_el(env);
2337     bool secure = arm_is_secure(env);
2338
2339     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
2340      * EL0[PV]TEN is zero.
2341      */
2342     if (cur_el == 0 &&
2343         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2344         return CP_ACCESS_TRAP;
2345     }
2346
2347     if (arm_feature(env, ARM_FEATURE_EL2) &&
2348         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2349         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2350         return CP_ACCESS_TRAP_EL2;
2351     }
2352     return CP_ACCESS_OK;
2353 }
2354
2355 static CPAccessResult gt_pct_access(CPUARMState *env,
2356                                     const ARMCPRegInfo *ri,
2357                                     bool isread)
2358 {
2359     return gt_counter_access(env, GTIMER_PHYS, isread);
2360 }
2361
2362 static CPAccessResult gt_vct_access(CPUARMState *env,
2363                                     const ARMCPRegInfo *ri,
2364                                     bool isread)
2365 {
2366     return gt_counter_access(env, GTIMER_VIRT, isread);
2367 }
2368
2369 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2370                                        bool isread)
2371 {
2372     return gt_timer_access(env, GTIMER_PHYS, isread);
2373 }
2374
2375 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2376                                        bool isread)
2377 {
2378     return gt_timer_access(env, GTIMER_VIRT, isread);
2379 }
2380
2381 static CPAccessResult gt_stimer_access(CPUARMState *env,
2382                                        const ARMCPRegInfo *ri,
2383                                        bool isread)
2384 {
2385     /* The AArch64 register view of the secure physical timer is
2386      * always accessible from EL3, and configurably accessible from
2387      * Secure EL1.
2388      */
2389     switch (arm_current_el(env)) {
2390     case 1:
2391         if (!arm_is_secure(env)) {
2392             return CP_ACCESS_TRAP;
2393         }
2394         if (!(env->cp15.scr_el3 & SCR_ST)) {
2395             return CP_ACCESS_TRAP_EL3;
2396         }
2397         return CP_ACCESS_OK;
2398     case 0:
2399     case 2:
2400         return CP_ACCESS_TRAP;
2401     case 3:
2402         return CP_ACCESS_OK;
2403     default:
2404         g_assert_not_reached();
2405     }
2406 }
2407
2408 static uint64_t gt_get_countervalue(CPUARMState *env)
2409 {
2410     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
2411 }
2412
2413 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2414 {
2415     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2416
2417     if (gt->ctl & 1) {
2418         /* Timer enabled: calculate and set current ISTATUS, irq, and
2419          * reset timer to when ISTATUS next has to change
2420          */
2421         uint64_t offset = timeridx == GTIMER_VIRT ?
2422                                       cpu->env.cp15.cntvoff_el2 : 0;
2423         uint64_t count = gt_get_countervalue(&cpu->env);
2424         /* Note that this must be unsigned 64 bit arithmetic: */
2425         int istatus = count - offset >= gt->cval;
2426         uint64_t nexttick;
2427         int irqstate;
2428
2429         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2430
2431         irqstate = (istatus && !(gt->ctl & 2));
2432         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2433
2434         if (istatus) {
2435             /* Next transition is when count rolls back over to zero */
2436             nexttick = UINT64_MAX;
2437         } else {
2438             /* Next transition is when we hit cval */
2439             nexttick = gt->cval + offset;
2440         }
2441         /* Note that the desired next expiry time might be beyond the
2442          * signed-64-bit range of a QEMUTimer -- in this case we just
2443          * set the timer for as far in the future as possible. When the
2444          * timer expires we will reset the timer for any remaining period.
2445          */
2446         if (nexttick > INT64_MAX / GTIMER_SCALE) {
2447             nexttick = INT64_MAX / GTIMER_SCALE;
2448         }
2449         timer_mod(cpu->gt_timer[timeridx], nexttick);
2450         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2451     } else {
2452         /* Timer disabled: ISTATUS and timer output always clear */
2453         gt->ctl &= ~4;
2454         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2455         timer_del(cpu->gt_timer[timeridx]);
2456         trace_arm_gt_recalc_disabled(timeridx);
2457     }
2458 }
2459
2460 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2461                            int timeridx)
2462 {
2463     ARMCPU *cpu = env_archcpu(env);
2464
2465     timer_del(cpu->gt_timer[timeridx]);
2466 }
2467
2468 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2469 {
2470     return gt_get_countervalue(env);
2471 }
2472
2473 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2474 {
2475     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
2476 }
2477
2478 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2479                           int timeridx,
2480                           uint64_t value)
2481 {
2482     trace_arm_gt_cval_write(timeridx, value);
2483     env->cp15.c14_timer[timeridx].cval = value;
2484     gt_recalc_timer(env_archcpu(env), timeridx);
2485 }
2486
2487 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2488                              int timeridx)
2489 {
2490     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2491
2492     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2493                       (gt_get_countervalue(env) - offset));
2494 }
2495
2496 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2497                           int timeridx,
2498                           uint64_t value)
2499 {
2500     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2501
2502     trace_arm_gt_tval_write(timeridx, value);
2503     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2504                                          sextract64(value, 0, 32);
2505     gt_recalc_timer(env_archcpu(env), timeridx);
2506 }
2507
2508 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2509                          int timeridx,
2510                          uint64_t value)
2511 {
2512     ARMCPU *cpu = env_archcpu(env);
2513     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2514
2515     trace_arm_gt_ctl_write(timeridx, value);
2516     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2517     if ((oldval ^ value) & 1) {
2518         /* Enable toggled */
2519         gt_recalc_timer(cpu, timeridx);
2520     } else if ((oldval ^ value) & 2) {
2521         /* IMASK toggled: don't need to recalculate,
2522          * just set the interrupt line based on ISTATUS
2523          */
2524         int irqstate = (oldval & 4) && !(value & 2);
2525
2526         trace_arm_gt_imask_toggle(timeridx, irqstate);
2527         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2528     }
2529 }
2530
2531 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2532 {
2533     gt_timer_reset(env, ri, GTIMER_PHYS);
2534 }
2535
2536 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2537                                uint64_t value)
2538 {
2539     gt_cval_write(env, ri, GTIMER_PHYS, value);
2540 }
2541
2542 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2543 {
2544     return gt_tval_read(env, ri, GTIMER_PHYS);
2545 }
2546
2547 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2548                                uint64_t value)
2549 {
2550     gt_tval_write(env, ri, GTIMER_PHYS, value);
2551 }
2552
2553 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2554                               uint64_t value)
2555 {
2556     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2557 }
2558
2559 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2560 {
2561     gt_timer_reset(env, ri, GTIMER_VIRT);
2562 }
2563
2564 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2565                                uint64_t value)
2566 {
2567     gt_cval_write(env, ri, GTIMER_VIRT, value);
2568 }
2569
2570 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2571 {
2572     return gt_tval_read(env, ri, GTIMER_VIRT);
2573 }
2574
2575 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2576                                uint64_t value)
2577 {
2578     gt_tval_write(env, ri, GTIMER_VIRT, value);
2579 }
2580
2581 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2582                               uint64_t value)
2583 {
2584     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2585 }
2586
2587 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2588                               uint64_t value)
2589 {
2590     ARMCPU *cpu = env_archcpu(env);
2591
2592     trace_arm_gt_cntvoff_write(value);
2593     raw_write(env, ri, value);
2594     gt_recalc_timer(cpu, GTIMER_VIRT);
2595 }
2596
2597 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2598 {
2599     gt_timer_reset(env, ri, GTIMER_HYP);
2600 }
2601
2602 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2603                               uint64_t value)
2604 {
2605     gt_cval_write(env, ri, GTIMER_HYP, value);
2606 }
2607
2608 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2609 {
2610     return gt_tval_read(env, ri, GTIMER_HYP);
2611 }
2612
2613 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2614                               uint64_t value)
2615 {
2616     gt_tval_write(env, ri, GTIMER_HYP, value);
2617 }
2618
2619 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2620                               uint64_t value)
2621 {
2622     gt_ctl_write(env, ri, GTIMER_HYP, value);
2623 }
2624
2625 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2626 {
2627     gt_timer_reset(env, ri, GTIMER_SEC);
2628 }
2629
2630 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2631                               uint64_t value)
2632 {
2633     gt_cval_write(env, ri, GTIMER_SEC, value);
2634 }
2635
2636 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2637 {
2638     return gt_tval_read(env, ri, GTIMER_SEC);
2639 }
2640
2641 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2642                               uint64_t value)
2643 {
2644     gt_tval_write(env, ri, GTIMER_SEC, value);
2645 }
2646
2647 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2648                               uint64_t value)
2649 {
2650     gt_ctl_write(env, ri, GTIMER_SEC, value);
2651 }
2652
2653 void arm_gt_ptimer_cb(void *opaque)
2654 {
2655     ARMCPU *cpu = opaque;
2656
2657     gt_recalc_timer(cpu, GTIMER_PHYS);
2658 }
2659
2660 void arm_gt_vtimer_cb(void *opaque)
2661 {
2662     ARMCPU *cpu = opaque;
2663
2664     gt_recalc_timer(cpu, GTIMER_VIRT);
2665 }
2666
2667 void arm_gt_htimer_cb(void *opaque)
2668 {
2669     ARMCPU *cpu = opaque;
2670
2671     gt_recalc_timer(cpu, GTIMER_HYP);
2672 }
2673
2674 void arm_gt_stimer_cb(void *opaque)
2675 {
2676     ARMCPU *cpu = opaque;
2677
2678     gt_recalc_timer(cpu, GTIMER_SEC);
2679 }
2680
2681 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2682     /* Note that CNTFRQ is purely reads-as-written for the benefit
2683      * of software; writing it doesn't actually change the timer frequency.
2684      * Our reset value matches the fixed frequency we implement the timer at.
2685      */
2686     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2687       .type = ARM_CP_ALIAS,
2688       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2689       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2690     },
2691     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2692       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2693       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2694       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2695       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
2696     },
2697     /* overall control: mostly access permissions */
2698     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2699       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2700       .access = PL1_RW,
2701       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2702       .resetvalue = 0,
2703     },
2704     /* per-timer control */
2705     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2706       .secure = ARM_CP_SECSTATE_NS,
2707       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2708       .accessfn = gt_ptimer_access,
2709       .fieldoffset = offsetoflow32(CPUARMState,
2710                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2711       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2712     },
2713     { .name = "CNTP_CTL_S",
2714       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2715       .secure = ARM_CP_SECSTATE_S,
2716       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2717       .accessfn = gt_ptimer_access,
2718       .fieldoffset = offsetoflow32(CPUARMState,
2719                                    cp15.c14_timer[GTIMER_SEC].ctl),
2720       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2721     },
2722     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2723       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2724       .type = ARM_CP_IO, .access = PL0_RW,
2725       .accessfn = gt_ptimer_access,
2726       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2727       .resetvalue = 0,
2728       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2729     },
2730     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2731       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2732       .accessfn = gt_vtimer_access,
2733       .fieldoffset = offsetoflow32(CPUARMState,
2734                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2735       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2736     },
2737     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2738       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2739       .type = ARM_CP_IO, .access = PL0_RW,
2740       .accessfn = gt_vtimer_access,
2741       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2742       .resetvalue = 0,
2743       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2744     },
2745     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2746     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2747       .secure = ARM_CP_SECSTATE_NS,
2748       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2749       .accessfn = gt_ptimer_access,
2750       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2751     },
2752     { .name = "CNTP_TVAL_S",
2753       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2754       .secure = ARM_CP_SECSTATE_S,
2755       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2756       .accessfn = gt_ptimer_access,
2757       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2758     },
2759     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2760       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2761       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2762       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2763       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2764     },
2765     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2766       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2767       .accessfn = gt_vtimer_access,
2768       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2769     },
2770     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2771       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2772       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2773       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2774       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2775     },
2776     /* The counter itself */
2777     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2778       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2779       .accessfn = gt_pct_access,
2780       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2781     },
2782     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2783       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2784       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2785       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2786     },
2787     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2788       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2789       .accessfn = gt_vct_access,
2790       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2791     },
2792     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2793       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2794       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2795       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2796     },
2797     /* Comparison value, indicating when the timer goes off */
2798     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2799       .secure = ARM_CP_SECSTATE_NS,
2800       .access = PL0_RW,
2801       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2802       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2803       .accessfn = gt_ptimer_access,
2804       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2805     },
2806     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
2807       .secure = ARM_CP_SECSTATE_S,
2808       .access = PL0_RW,
2809       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2810       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2811       .accessfn = gt_ptimer_access,
2812       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2813     },
2814     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2815       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2816       .access = PL0_RW,
2817       .type = ARM_CP_IO,
2818       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2819       .resetvalue = 0, .accessfn = gt_ptimer_access,
2820       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2821     },
2822     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2823       .access = PL0_RW,
2824       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2825       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2826       .accessfn = gt_vtimer_access,
2827       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2828     },
2829     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2830       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2831       .access = PL0_RW,
2832       .type = ARM_CP_IO,
2833       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2834       .resetvalue = 0, .accessfn = gt_vtimer_access,
2835       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2836     },
2837     /* Secure timer -- this is actually restricted to only EL3
2838      * and configurably Secure-EL1 via the accessfn.
2839      */
2840     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2841       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2842       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2843       .accessfn = gt_stimer_access,
2844       .readfn = gt_sec_tval_read,
2845       .writefn = gt_sec_tval_write,
2846       .resetfn = gt_sec_timer_reset,
2847     },
2848     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2849       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2850       .type = ARM_CP_IO, .access = PL1_RW,
2851       .accessfn = gt_stimer_access,
2852       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2853       .resetvalue = 0,
2854       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2855     },
2856     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2857       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2858       .type = ARM_CP_IO, .access = PL1_RW,
2859       .accessfn = gt_stimer_access,
2860       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2861       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2862     },
2863     REGINFO_SENTINEL
2864 };
2865
2866 #else
2867
2868 /* In user-mode most of the generic timer registers are inaccessible
2869  * however modern kernels (4.12+) allow access to cntvct_el0
2870  */
2871
2872 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2873 {
2874     /* Currently we have no support for QEMUTimer in linux-user so we
2875      * can't call gt_get_countervalue(env), instead we directly
2876      * call the lower level functions.
2877      */
2878     return cpu_get_clock() / GTIMER_SCALE;
2879 }
2880
2881 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2882     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2883       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2884       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
2885       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2886       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
2887     },
2888     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2889       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2890       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2891       .readfn = gt_virt_cnt_read,
2892     },
2893     REGINFO_SENTINEL
2894 };
2895
2896 #endif
2897
2898 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2899 {
2900     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2901         raw_write(env, ri, value);
2902     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2903         raw_write(env, ri, value & 0xfffff6ff);
2904     } else {
2905         raw_write(env, ri, value & 0xfffff1ff);
2906     }
2907 }
2908
2909 #ifndef CONFIG_USER_ONLY
2910 /* get_phys_addr() isn't present for user-mode-only targets */
2911
2912 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2913                                  bool isread)
2914 {
2915     if (ri->opc2 & 4) {
2916         /* The ATS12NSO* operations must trap to EL3 if executed in
2917          * Secure EL1 (which can only happen if EL3 is AArch64).
2918          * They are simply UNDEF if executed from NS EL1.
2919          * They function normally from EL2 or EL3.
2920          */
2921         if (arm_current_el(env) == 1) {
2922             if (arm_is_secure_below_el3(env)) {
2923                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2924             }
2925             return CP_ACCESS_TRAP_UNCATEGORIZED;
2926         }
2927     }
2928     return CP_ACCESS_OK;
2929 }
2930
2931 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2932                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2933 {
2934     hwaddr phys_addr;
2935     target_ulong page_size;
2936     int prot;
2937     bool ret;
2938     uint64_t par64;
2939     bool format64 = false;
2940     MemTxAttrs attrs = {};
2941     ARMMMUFaultInfo fi = {};
2942     ARMCacheAttrs cacheattrs = {};
2943
2944     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2945                         &prot, &page_size, &fi, &cacheattrs);
2946
2947     if (is_a64(env)) {
2948         format64 = true;
2949     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
2950         /*
2951          * ATS1Cxx:
2952          * * TTBCR.EAE determines whether the result is returned using the
2953          *   32-bit or the 64-bit PAR format
2954          * * Instructions executed in Hyp mode always use the 64bit format
2955          *
2956          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
2957          * * The Non-secure TTBCR.EAE bit is set to 1
2958          * * The implementation includes EL2, and the value of HCR.VM is 1
2959          *
2960          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
2961          *
2962          * ATS1Hx always uses the 64bit format.
2963          */
2964         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
2965
2966         if (arm_feature(env, ARM_FEATURE_EL2)) {
2967             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
2968                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
2969             } else {
2970                 format64 |= arm_current_el(env) == 2;
2971             }
2972         }
2973     }
2974
2975     if (format64) {
2976         /* Create a 64-bit PAR */
2977         par64 = (1 << 11); /* LPAE bit always set */
2978         if (!ret) {
2979             par64 |= phys_addr & ~0xfffULL;
2980             if (!attrs.secure) {
2981                 par64 |= (1 << 9); /* NS */
2982             }
2983             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
2984             par64 |= cacheattrs.shareability << 7; /* SH */
2985         } else {
2986             uint32_t fsr = arm_fi_to_lfsc(&fi);
2987
2988             par64 |= 1; /* F */
2989             par64 |= (fsr & 0x3f) << 1; /* FS */
2990             if (fi.stage2) {
2991                 par64 |= (1 << 9); /* S */
2992             }
2993             if (fi.s1ptw) {
2994                 par64 |= (1 << 8); /* PTW */
2995             }
2996         }
2997     } else {
2998         /* fsr is a DFSR/IFSR value for the short descriptor
2999          * translation table format (with WnR always clear).
3000          * Convert it to a 32-bit PAR.
3001          */
3002         if (!ret) {
3003             /* We do not set any attribute bits in the PAR */
3004             if (page_size == (1 << 24)
3005                 && arm_feature(env, ARM_FEATURE_V7)) {
3006                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3007             } else {
3008                 par64 = phys_addr & 0xfffff000;
3009             }
3010             if (!attrs.secure) {
3011                 par64 |= (1 << 9); /* NS */
3012             }
3013         } else {
3014             uint32_t fsr = arm_fi_to_sfsc(&fi);
3015
3016             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3017                     ((fsr & 0xf) << 1) | 1;
3018         }
3019     }
3020     return par64;
3021 }
3022
3023 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3024 {
3025     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3026     uint64_t par64;
3027     ARMMMUIdx mmu_idx;
3028     int el = arm_current_el(env);
3029     bool secure = arm_is_secure_below_el3(env);
3030
3031     switch (ri->opc2 & 6) {
3032     case 0:
3033         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
3034         switch (el) {
3035         case 3:
3036             mmu_idx = ARMMMUIdx_S1E3;
3037             break;
3038         case 2:
3039             mmu_idx = ARMMMUIdx_S1NSE1;
3040             break;
3041         case 1:
3042             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3043             break;
3044         default:
3045             g_assert_not_reached();
3046         }
3047         break;
3048     case 2:
3049         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3050         switch (el) {
3051         case 3:
3052             mmu_idx = ARMMMUIdx_S1SE0;
3053             break;
3054         case 2:
3055             mmu_idx = ARMMMUIdx_S1NSE0;
3056             break;
3057         case 1:
3058             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3059             break;
3060         default:
3061             g_assert_not_reached();
3062         }
3063         break;
3064     case 4:
3065         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3066         mmu_idx = ARMMMUIdx_S12NSE1;
3067         break;
3068     case 6:
3069         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3070         mmu_idx = ARMMMUIdx_S12NSE0;
3071         break;
3072     default:
3073         g_assert_not_reached();
3074     }
3075
3076     par64 = do_ats_write(env, value, access_type, mmu_idx);
3077
3078     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3079 }
3080
3081 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3082                         uint64_t value)
3083 {
3084     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3085     uint64_t par64;
3086
3087     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S1E2);
3088
3089     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3090 }
3091
3092 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3093                                      bool isread)
3094 {
3095     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
3096         return CP_ACCESS_TRAP;
3097     }
3098     return CP_ACCESS_OK;
3099 }
3100
3101 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3102                         uint64_t value)
3103 {
3104     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3105     ARMMMUIdx mmu_idx;
3106     int secure = arm_is_secure_below_el3(env);
3107
3108     switch (ri->opc2 & 6) {
3109     case 0:
3110         switch (ri->opc1) {
3111         case 0: /* AT S1E1R, AT S1E1W */
3112             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3113             break;
3114         case 4: /* AT S1E2R, AT S1E2W */
3115             mmu_idx = ARMMMUIdx_S1E2;
3116             break;
3117         case 6: /* AT S1E3R, AT S1E3W */
3118             mmu_idx = ARMMMUIdx_S1E3;
3119             break;
3120         default:
3121             g_assert_not_reached();
3122         }
3123         break;
3124     case 2: /* AT S1E0R, AT S1E0W */
3125         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3126         break;
3127     case 4: /* AT S12E1R, AT S12E1W */
3128         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
3129         break;
3130     case 6: /* AT S12E0R, AT S12E0W */
3131         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
3132         break;
3133     default:
3134         g_assert_not_reached();
3135     }
3136
3137     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3138 }
3139 #endif
3140
3141 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3142     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3143       .access = PL1_RW, .resetvalue = 0,
3144       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3145                              offsetoflow32(CPUARMState, cp15.par_ns) },
3146       .writefn = par_write },
3147 #ifndef CONFIG_USER_ONLY
3148     /* This underdecoding is safe because the reginfo is NO_RAW. */
3149     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3150       .access = PL1_W, .accessfn = ats_access,
3151       .writefn = ats_write, .type = ARM_CP_NO_RAW },
3152 #endif
3153     REGINFO_SENTINEL
3154 };
3155
3156 /* Return basic MPU access permission bits.  */
3157 static uint32_t simple_mpu_ap_bits(uint32_t val)
3158 {
3159     uint32_t ret;
3160     uint32_t mask;
3161     int i;
3162     ret = 0;
3163     mask = 3;
3164     for (i = 0; i < 16; i += 2) {
3165         ret |= (val >> i) & mask;
3166         mask <<= 2;
3167     }
3168     return ret;
3169 }
3170
3171 /* Pad basic MPU access permission bits to extended format.  */
3172 static uint32_t extended_mpu_ap_bits(uint32_t val)
3173 {
3174     uint32_t ret;
3175     uint32_t mask;
3176     int i;
3177     ret = 0;
3178     mask = 3;
3179     for (i = 0; i < 16; i += 2) {
3180         ret |= (val & mask) << i;
3181         mask <<= 2;
3182     }
3183     return ret;
3184 }
3185
3186 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3187                                  uint64_t value)
3188 {
3189     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3190 }
3191
3192 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3193 {
3194     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3195 }
3196
3197 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3198                                  uint64_t value)
3199 {
3200     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3201 }
3202
3203 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3204 {
3205     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3206 }
3207
3208 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3209 {
3210     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3211
3212     if (!u32p) {
3213         return 0;
3214     }
3215
3216     u32p += env->pmsav7.rnr[M_REG_NS];
3217     return *u32p;
3218 }
3219
3220 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3221                          uint64_t value)
3222 {
3223     ARMCPU *cpu = env_archcpu(env);
3224     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3225
3226     if (!u32p) {
3227         return;
3228     }
3229
3230     u32p += env->pmsav7.rnr[M_REG_NS];
3231     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3232     *u32p = value;
3233 }
3234
3235 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3236                               uint64_t value)
3237 {
3238     ARMCPU *cpu = env_archcpu(env);
3239     uint32_t nrgs = cpu->pmsav7_dregion;
3240
3241     if (value >= nrgs) {
3242         qemu_log_mask(LOG_GUEST_ERROR,
3243                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3244                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3245         return;
3246     }
3247
3248     raw_write(env, ri, value);
3249 }
3250
3251 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3252     /* Reset for all these registers is handled in arm_cpu_reset(),
3253      * because the PMSAv7 is also used by M-profile CPUs, which do
3254      * not register cpregs but still need the state to be reset.
3255      */
3256     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3257       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3258       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3259       .readfn = pmsav7_read, .writefn = pmsav7_write,
3260       .resetfn = arm_cp_reset_ignore },
3261     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3262       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3263       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3264       .readfn = pmsav7_read, .writefn = pmsav7_write,
3265       .resetfn = arm_cp_reset_ignore },
3266     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3267       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3268       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3269       .readfn = pmsav7_read, .writefn = pmsav7_write,
3270       .resetfn = arm_cp_reset_ignore },
3271     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3272       .access = PL1_RW,
3273       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3274       .writefn = pmsav7_rgnr_write,
3275       .resetfn = arm_cp_reset_ignore },
3276     REGINFO_SENTINEL
3277 };
3278
3279 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3280     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3281       .access = PL1_RW, .type = ARM_CP_ALIAS,
3282       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3283       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3284     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3285       .access = PL1_RW, .type = ARM_CP_ALIAS,
3286       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3287       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3288     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3289       .access = PL1_RW,
3290       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3291       .resetvalue = 0, },
3292     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3293       .access = PL1_RW,
3294       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3295       .resetvalue = 0, },
3296     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3297       .access = PL1_RW,
3298       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3299     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3300       .access = PL1_RW,
3301       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3302     /* Protection region base and size registers */
3303     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3304       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3305       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3306     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3307       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3308       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3309     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3310       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3311       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3312     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3313       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3314       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3315     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3316       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3317       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3318     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3319       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3320       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3321     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3322       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3323       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3324     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3325       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3326       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3327     REGINFO_SENTINEL
3328 };
3329
3330 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3331                                  uint64_t value)
3332 {
3333     TCR *tcr = raw_ptr(env, ri);
3334     int maskshift = extract32(value, 0, 3);
3335
3336     if (!arm_feature(env, ARM_FEATURE_V8)) {
3337         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3338             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3339              * using Long-desciptor translation table format */
3340             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3341         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3342             /* In an implementation that includes the Security Extensions
3343              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3344              * Short-descriptor translation table format.
3345              */
3346             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3347         } else {
3348             value &= TTBCR_N;
3349         }
3350     }
3351
3352     /* Update the masks corresponding to the TCR bank being written
3353      * Note that we always calculate mask and base_mask, but
3354      * they are only used for short-descriptor tables (ie if EAE is 0);
3355      * for long-descriptor tables the TCR fields are used differently
3356      * and the mask and base_mask values are meaningless.
3357      */
3358     tcr->raw_tcr = value;
3359     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3360     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3361 }
3362
3363 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3364                              uint64_t value)
3365 {
3366     ARMCPU *cpu = env_archcpu(env);
3367     TCR *tcr = raw_ptr(env, ri);
3368
3369     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3370         /* With LPAE the TTBCR could result in a change of ASID
3371          * via the TTBCR.A1 bit, so do a TLB flush.
3372          */
3373         tlb_flush(CPU(cpu));
3374     }
3375     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3376     value = deposit64(tcr->raw_tcr, 0, 32, value);
3377     vmsa_ttbcr_raw_write(env, ri, value);
3378 }
3379
3380 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3381 {
3382     TCR *tcr = raw_ptr(env, ri);
3383
3384     /* Reset both the TCR as well as the masks corresponding to the bank of
3385      * the TCR being reset.
3386      */
3387     tcr->raw_tcr = 0;
3388     tcr->mask = 0;
3389     tcr->base_mask = 0xffffc000u;
3390 }
3391
3392 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3393                                uint64_t value)
3394 {
3395     ARMCPU *cpu = env_archcpu(env);
3396     TCR *tcr = raw_ptr(env, ri);
3397
3398     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3399     tlb_flush(CPU(cpu));
3400     tcr->raw_tcr = value;
3401 }
3402
3403 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3404                             uint64_t value)
3405 {
3406     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3407     if (cpreg_field_is_64bit(ri) &&
3408         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3409         ARMCPU *cpu = env_archcpu(env);
3410         tlb_flush(CPU(cpu));
3411     }
3412     raw_write(env, ri, value);
3413 }
3414
3415 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3416                         uint64_t value)
3417 {
3418     ARMCPU *cpu = env_archcpu(env);
3419     CPUState *cs = CPU(cpu);
3420
3421     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
3422     if (raw_read(env, ri) != value) {
3423         tlb_flush_by_mmuidx(cs,
3424                             ARMMMUIdxBit_S12NSE1 |
3425                             ARMMMUIdxBit_S12NSE0 |
3426                             ARMMMUIdxBit_S2NS);
3427         raw_write(env, ri, value);
3428     }
3429 }
3430
3431 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3432     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3433       .access = PL1_RW, .type = ARM_CP_ALIAS,
3434       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3435                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3436     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3437       .access = PL1_RW, .resetvalue = 0,
3438       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3439                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3440     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3441       .access = PL1_RW, .resetvalue = 0,
3442       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3443                              offsetof(CPUARMState, cp15.dfar_ns) } },
3444     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3445       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3446       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3447       .resetvalue = 0, },
3448     REGINFO_SENTINEL
3449 };
3450
3451 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3452     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3453       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3454       .access = PL1_RW,
3455       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3456     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3457       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3458       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3459       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3460                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3461     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3462       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3463       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3464       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3465                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3466     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3467       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3468       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
3469       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3470       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3471     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3472       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3473       .raw_writefn = vmsa_ttbcr_raw_write,
3474       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
3475                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
3476     REGINFO_SENTINEL
3477 };
3478
3479 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3480  * qemu tlbs nor adjusting cached masks.
3481  */
3482 static const ARMCPRegInfo ttbcr2_reginfo = {
3483     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3484     .access = PL1_RW, .type = ARM_CP_ALIAS,
3485     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
3486                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
3487 };
3488
3489 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3490                                 uint64_t value)
3491 {
3492     env->cp15.c15_ticonfig = value & 0xe7;
3493     /* The OS_TYPE bit in this register changes the reported CPUID! */
3494     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3495         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3496 }
3497
3498 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3499                                 uint64_t value)
3500 {
3501     env->cp15.c15_threadid = value & 0xffff;
3502 }
3503
3504 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3505                            uint64_t value)
3506 {
3507     /* Wait-for-interrupt (deprecated) */
3508     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
3509 }
3510
3511 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3512                                   uint64_t value)
3513 {
3514     /* On OMAP there are registers indicating the max/min index of dcache lines
3515      * containing a dirty line; cache flush operations have to reset these.
3516      */
3517     env->cp15.c15_i_max = 0x000;
3518     env->cp15.c15_i_min = 0xff0;
3519 }
3520
3521 static const ARMCPRegInfo omap_cp_reginfo[] = {
3522     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3523       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3524       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3525       .resetvalue = 0, },
3526     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3527       .access = PL1_RW, .type = ARM_CP_NOP },
3528     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3529       .access = PL1_RW,
3530       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3531       .writefn = omap_ticonfig_write },
3532     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3533       .access = PL1_RW,
3534       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3535     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3536       .access = PL1_RW, .resetvalue = 0xff0,
3537       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3538     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3539       .access = PL1_RW,
3540       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3541       .writefn = omap_threadid_write },
3542     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3543       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3544       .type = ARM_CP_NO_RAW,
3545       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3546     /* TODO: Peripheral port remap register:
3547      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3548      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3549      * when MMU is off.
3550      */
3551     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3552       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3553       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3554       .writefn = omap_cachemaint_write },
3555     { .name = "C9", .cp = 15, .crn = 9,
3556       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3557       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3558     REGINFO_SENTINEL
3559 };
3560
3561 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3562                               uint64_t value)
3563 {
3564     env->cp15.c15_cpar = value & 0x3fff;
3565 }
3566
3567 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3568     { .name = "XSCALE_CPAR",
3569       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3570       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3571       .writefn = xscale_cpar_write, },
3572     { .name = "XSCALE_AUXCR",
3573       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3574       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3575       .resetvalue = 0, },
3576     /* XScale specific cache-lockdown: since we have no cache we NOP these
3577      * and hope the guest does not really rely on cache behaviour.
3578      */
3579     { .name = "XSCALE_LOCK_ICACHE_LINE",
3580       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3581       .access = PL1_W, .type = ARM_CP_NOP },
3582     { .name = "XSCALE_UNLOCK_ICACHE",
3583       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3584       .access = PL1_W, .type = ARM_CP_NOP },
3585     { .name = "XSCALE_DCACHE_LOCK",
3586       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3587       .access = PL1_RW, .type = ARM_CP_NOP },
3588     { .name = "XSCALE_UNLOCK_DCACHE",
3589       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3590       .access = PL1_W, .type = ARM_CP_NOP },
3591     REGINFO_SENTINEL
3592 };
3593
3594 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3595     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3596      * implementation of this implementation-defined space.
3597      * Ideally this should eventually disappear in favour of actually
3598      * implementing the correct behaviour for all cores.
3599      */
3600     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3601       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3602       .access = PL1_RW,
3603       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3604       .resetvalue = 0 },
3605     REGINFO_SENTINEL
3606 };
3607
3608 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3609     /* Cache status: RAZ because we have no cache so it's always clean */
3610     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3611       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3612       .resetvalue = 0 },
3613     REGINFO_SENTINEL
3614 };
3615
3616 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
3617     /* We never have a a block transfer operation in progress */
3618     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
3619       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3620       .resetvalue = 0 },
3621     /* The cache ops themselves: these all NOP for QEMU */
3622     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
3623       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3624     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
3625       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3626     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
3627       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3628     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
3629       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3630     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
3631       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3632     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
3633       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3634     REGINFO_SENTINEL
3635 };
3636
3637 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
3638     /* The cache test-and-clean instructions always return (1 << 30)
3639      * to indicate that there are no dirty cache lines.
3640      */
3641     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
3642       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3643       .resetvalue = (1 << 30) },
3644     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
3645       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3646       .resetvalue = (1 << 30) },
3647     REGINFO_SENTINEL
3648 };
3649
3650 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
3651     /* Ignore ReadBuffer accesses */
3652     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
3653       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3654       .access = PL1_RW, .resetvalue = 0,
3655       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
3656     REGINFO_SENTINEL
3657 };
3658
3659 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3660 {
3661     ARMCPU *cpu = env_archcpu(env);
3662     unsigned int cur_el = arm_current_el(env);
3663     bool secure = arm_is_secure(env);
3664
3665     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3666         return env->cp15.vpidr_el2;
3667     }
3668     return raw_read(env, ri);
3669 }
3670
3671 static uint64_t mpidr_read_val(CPUARMState *env)
3672 {
3673     ARMCPU *cpu = env_archcpu(env);
3674     uint64_t mpidr = cpu->mp_affinity;
3675
3676     if (arm_feature(env, ARM_FEATURE_V7MP)) {
3677         mpidr |= (1U << 31);
3678         /* Cores which are uniprocessor (non-coherent)
3679          * but still implement the MP extensions set
3680          * bit 30. (For instance, Cortex-R5).
3681          */
3682         if (cpu->mp_is_up) {
3683             mpidr |= (1u << 30);
3684         }
3685     }
3686     return mpidr;
3687 }
3688
3689 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3690 {
3691     unsigned int cur_el = arm_current_el(env);
3692     bool secure = arm_is_secure(env);
3693
3694     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3695         return env->cp15.vmpidr_el2;
3696     }
3697     return mpidr_read_val(env);
3698 }
3699
3700 static const ARMCPRegInfo lpae_cp_reginfo[] = {
3701     /* NOP AMAIR0/1 */
3702     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
3703       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
3704       .access = PL1_RW, .type = ARM_CP_CONST,
3705       .resetvalue = 0 },
3706     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
3707     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
3708       .access = PL1_RW, .type = ARM_CP_CONST,
3709       .resetvalue = 0 },
3710     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
3711       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
3712       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
3713                              offsetof(CPUARMState, cp15.par_ns)} },
3714     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
3715       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3716       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3717                              offsetof(CPUARMState, cp15.ttbr0_ns) },
3718       .writefn = vmsa_ttbr_write, },
3719     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
3720       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3721       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3722                              offsetof(CPUARMState, cp15.ttbr1_ns) },
3723       .writefn = vmsa_ttbr_write, },
3724     REGINFO_SENTINEL
3725 };
3726
3727 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3728 {
3729     return vfp_get_fpcr(env);
3730 }
3731
3732 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3733                             uint64_t value)
3734 {
3735     vfp_set_fpcr(env, value);
3736 }
3737
3738 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3739 {
3740     return vfp_get_fpsr(env);
3741 }
3742
3743 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3744                             uint64_t value)
3745 {
3746     vfp_set_fpsr(env, value);
3747 }
3748
3749 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
3750                                        bool isread)
3751 {
3752     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
3753         return CP_ACCESS_TRAP;
3754     }
3755     return CP_ACCESS_OK;
3756 }
3757
3758 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3759                             uint64_t value)
3760 {
3761     env->daif = value & PSTATE_DAIF;
3762 }
3763
3764 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3765                                           const ARMCPRegInfo *ri,
3766                                           bool isread)
3767 {
3768     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3769      * SCTLR_EL1.UCI is set.
3770      */
3771     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3772         return CP_ACCESS_TRAP;
3773     }
3774     return CP_ACCESS_OK;
3775 }
3776
3777 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3778  * Page D4-1736 (DDI0487A.b)
3779  */
3780
3781 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3782                                       uint64_t value)
3783 {
3784     CPUState *cs = env_cpu(env);
3785     bool sec = arm_is_secure_below_el3(env);
3786
3787     if (sec) {
3788         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3789                                             ARMMMUIdxBit_S1SE1 |
3790                                             ARMMMUIdxBit_S1SE0);
3791     } else {
3792         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3793                                             ARMMMUIdxBit_S12NSE1 |
3794                                             ARMMMUIdxBit_S12NSE0);
3795     }
3796 }
3797
3798 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3799                                     uint64_t value)
3800 {
3801     CPUState *cs = env_cpu(env);
3802
3803     if (tlb_force_broadcast(env)) {
3804         tlbi_aa64_vmalle1is_write(env, NULL, value);
3805         return;
3806     }
3807
3808     if (arm_is_secure_below_el3(env)) {
3809         tlb_flush_by_mmuidx(cs,
3810                             ARMMMUIdxBit_S1SE1 |
3811                             ARMMMUIdxBit_S1SE0);
3812     } else {
3813         tlb_flush_by_mmuidx(cs,
3814                             ARMMMUIdxBit_S12NSE1 |
3815                             ARMMMUIdxBit_S12NSE0);
3816     }
3817 }
3818
3819 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3820                                   uint64_t value)
3821 {
3822     /* Note that the 'ALL' scope must invalidate both stage 1 and
3823      * stage 2 translations, whereas most other scopes only invalidate
3824      * stage 1 translations.
3825      */
3826     ARMCPU *cpu = env_archcpu(env);
3827     CPUState *cs = CPU(cpu);
3828
3829     if (arm_is_secure_below_el3(env)) {
3830         tlb_flush_by_mmuidx(cs,
3831                             ARMMMUIdxBit_S1SE1 |
3832                             ARMMMUIdxBit_S1SE0);
3833     } else {
3834         if (arm_feature(env, ARM_FEATURE_EL2)) {
3835             tlb_flush_by_mmuidx(cs,
3836                                 ARMMMUIdxBit_S12NSE1 |
3837                                 ARMMMUIdxBit_S12NSE0 |
3838                                 ARMMMUIdxBit_S2NS);
3839         } else {
3840             tlb_flush_by_mmuidx(cs,
3841                                 ARMMMUIdxBit_S12NSE1 |
3842                                 ARMMMUIdxBit_S12NSE0);
3843         }
3844     }
3845 }
3846
3847 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3848                                   uint64_t value)
3849 {
3850     ARMCPU *cpu = env_archcpu(env);
3851     CPUState *cs = CPU(cpu);
3852
3853     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3854 }
3855
3856 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3857                                   uint64_t value)
3858 {
3859     ARMCPU *cpu = env_archcpu(env);
3860     CPUState *cs = CPU(cpu);
3861
3862     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3863 }
3864
3865 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3866                                     uint64_t value)
3867 {
3868     /* Note that the 'ALL' scope must invalidate both stage 1 and
3869      * stage 2 translations, whereas most other scopes only invalidate
3870      * stage 1 translations.
3871      */
3872     CPUState *cs = env_cpu(env);
3873     bool sec = arm_is_secure_below_el3(env);
3874     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3875
3876     if (sec) {
3877         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3878                                             ARMMMUIdxBit_S1SE1 |
3879                                             ARMMMUIdxBit_S1SE0);
3880     } else if (has_el2) {
3881         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3882                                             ARMMMUIdxBit_S12NSE1 |
3883                                             ARMMMUIdxBit_S12NSE0 |
3884                                             ARMMMUIdxBit_S2NS);
3885     } else {
3886           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3887                                               ARMMMUIdxBit_S12NSE1 |
3888                                               ARMMMUIdxBit_S12NSE0);
3889     }
3890 }
3891
3892 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3893                                     uint64_t value)
3894 {
3895     CPUState *cs = env_cpu(env);
3896
3897     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3898 }
3899
3900 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3901                                     uint64_t value)
3902 {
3903     CPUState *cs = env_cpu(env);
3904
3905     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3906 }
3907
3908 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3909                                  uint64_t value)
3910 {
3911     /* Invalidate by VA, EL2
3912      * Currently handles both VAE2 and VALE2, since we don't support
3913      * flush-last-level-only.
3914      */
3915     ARMCPU *cpu = env_archcpu(env);
3916     CPUState *cs = CPU(cpu);
3917     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3918
3919     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3920 }
3921
3922 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3923                                  uint64_t value)
3924 {
3925     /* Invalidate by VA, EL3
3926      * Currently handles both VAE3 and VALE3, since we don't support
3927      * flush-last-level-only.
3928      */
3929     ARMCPU *cpu = env_archcpu(env);
3930     CPUState *cs = CPU(cpu);
3931     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3932
3933     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
3934 }
3935
3936 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3937                                    uint64_t value)
3938 {
3939     ARMCPU *cpu = env_archcpu(env);
3940     CPUState *cs = CPU(cpu);
3941     bool sec = arm_is_secure_below_el3(env);
3942     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3943
3944     if (sec) {
3945         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3946                                                  ARMMMUIdxBit_S1SE1 |
3947                                                  ARMMMUIdxBit_S1SE0);
3948     } else {
3949         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3950                                                  ARMMMUIdxBit_S12NSE1 |
3951                                                  ARMMMUIdxBit_S12NSE0);
3952     }
3953 }
3954
3955 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3956                                  uint64_t value)
3957 {
3958     /* Invalidate by VA, EL1&0 (AArch64 version).
3959      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3960      * since we don't support flush-for-specific-ASID-only or
3961      * flush-last-level-only.
3962      */
3963     ARMCPU *cpu = env_archcpu(env);
3964     CPUState *cs = CPU(cpu);
3965     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3966
3967     if (tlb_force_broadcast(env)) {
3968         tlbi_aa64_vae1is_write(env, NULL, value);
3969         return;
3970     }
3971
3972     if (arm_is_secure_below_el3(env)) {
3973         tlb_flush_page_by_mmuidx(cs, pageaddr,
3974                                  ARMMMUIdxBit_S1SE1 |
3975                                  ARMMMUIdxBit_S1SE0);
3976     } else {
3977         tlb_flush_page_by_mmuidx(cs, pageaddr,
3978                                  ARMMMUIdxBit_S12NSE1 |
3979                                  ARMMMUIdxBit_S12NSE0);
3980     }
3981 }
3982
3983 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3984                                    uint64_t value)
3985 {
3986     CPUState *cs = env_cpu(env);
3987     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3988
3989     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3990                                              ARMMMUIdxBit_S1E2);
3991 }
3992
3993 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3994                                    uint64_t value)
3995 {
3996     CPUState *cs = env_cpu(env);
3997     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3998
3999     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4000                                              ARMMMUIdxBit_S1E3);
4001 }
4002
4003 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4004                                     uint64_t value)
4005 {
4006     /* Invalidate by IPA. This has to invalidate any structures that
4007      * contain only stage 2 translation information, but does not need
4008      * to apply to structures that contain combined stage 1 and stage 2
4009      * translation information.
4010      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
4011      */
4012     ARMCPU *cpu = env_archcpu(env);
4013     CPUState *cs = CPU(cpu);
4014     uint64_t pageaddr;
4015
4016     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4017         return;
4018     }
4019
4020     pageaddr = sextract64(value << 12, 0, 48);
4021
4022     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
4023 }
4024
4025 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4026                                       uint64_t value)
4027 {
4028     CPUState *cs = env_cpu(env);
4029     uint64_t pageaddr;
4030
4031     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4032         return;
4033     }
4034
4035     pageaddr = sextract64(value << 12, 0, 48);
4036
4037     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4038                                              ARMMMUIdxBit_S2NS);
4039 }
4040
4041 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4042                                       bool isread)
4043 {
4044     /* We don't implement EL2, so the only control on DC ZVA is the
4045      * bit in the SCTLR which can prohibit access for EL0.
4046      */
4047     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4048         return CP_ACCESS_TRAP;
4049     }
4050     return CP_ACCESS_OK;
4051 }
4052
4053 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4054 {
4055     ARMCPU *cpu = env_archcpu(env);
4056     int dzp_bit = 1 << 4;
4057
4058     /* DZP indicates whether DC ZVA access is allowed */
4059     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4060         dzp_bit = 0;
4061     }
4062     return cpu->dcz_blocksize | dzp_bit;
4063 }
4064
4065 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4066                                     bool isread)
4067 {
4068     if (!(env->pstate & PSTATE_SP)) {
4069         /* Access to SP_EL0 is undefined if it's being used as
4070          * the stack pointer.
4071          */
4072         return CP_ACCESS_TRAP_UNCATEGORIZED;
4073     }
4074     return CP_ACCESS_OK;
4075 }
4076
4077 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4078 {
4079     return env->pstate & PSTATE_SP;
4080 }
4081
4082 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4083 {
4084     update_spsel(env, val);
4085 }
4086
4087 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4088                         uint64_t value)
4089 {
4090     ARMCPU *cpu = env_archcpu(env);
4091
4092     if (raw_read(env, ri) == value) {
4093         /* Skip the TLB flush if nothing actually changed; Linux likes
4094          * to do a lot of pointless SCTLR writes.
4095          */
4096         return;
4097     }
4098
4099     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4100         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4101         value &= ~SCTLR_M;
4102     }
4103
4104     raw_write(env, ri, value);
4105     /* ??? Lots of these bits are not implemented.  */
4106     /* This may enable/disable the MMU, so do a TLB flush.  */
4107     tlb_flush(CPU(cpu));
4108 }
4109
4110 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4111                                      bool isread)
4112 {
4113     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4114         return CP_ACCESS_TRAP_FP_EL2;
4115     }
4116     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4117         return CP_ACCESS_TRAP_FP_EL3;
4118     }
4119     return CP_ACCESS_OK;
4120 }
4121
4122 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4123                        uint64_t value)
4124 {
4125     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4126 }
4127
4128 static const ARMCPRegInfo v8_cp_reginfo[] = {
4129     /* Minimal set of EL0-visible registers. This will need to be expanded
4130      * significantly for system emulation of AArch64 CPUs.
4131      */
4132     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4133       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4134       .access = PL0_RW, .type = ARM_CP_NZCV },
4135     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4136       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4137       .type = ARM_CP_NO_RAW,
4138       .access = PL0_RW, .accessfn = aa64_daif_access,
4139       .fieldoffset = offsetof(CPUARMState, daif),
4140       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4141     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4142       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4143       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4144       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4145     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4146       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4147       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4148       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4149     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4150       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4151       .access = PL0_R, .type = ARM_CP_NO_RAW,
4152       .readfn = aa64_dczid_read },
4153     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4154       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4155       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4156 #ifndef CONFIG_USER_ONLY
4157       /* Avoid overhead of an access check that always passes in user-mode */
4158       .accessfn = aa64_zva_access,
4159 #endif
4160     },
4161     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4162       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4163       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4164     /* Cache ops: all NOPs since we don't emulate caches */
4165     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4166       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4167       .access = PL1_W, .type = ARM_CP_NOP },
4168     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4169       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4170       .access = PL1_W, .type = ARM_CP_NOP },
4171     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4172       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4173       .access = PL0_W, .type = ARM_CP_NOP,
4174       .accessfn = aa64_cacheop_access },
4175     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4176       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4177       .access = PL1_W, .type = ARM_CP_NOP },
4178     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4179       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4180       .access = PL1_W, .type = ARM_CP_NOP },
4181     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4182       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4183       .access = PL0_W, .type = ARM_CP_NOP,
4184       .accessfn = aa64_cacheop_access },
4185     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4186       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4187       .access = PL1_W, .type = ARM_CP_NOP },
4188     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4189       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4190       .access = PL0_W, .type = ARM_CP_NOP,
4191       .accessfn = aa64_cacheop_access },
4192     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4193       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4194       .access = PL0_W, .type = ARM_CP_NOP,
4195       .accessfn = aa64_cacheop_access },
4196     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4197       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4198       .access = PL1_W, .type = ARM_CP_NOP },
4199     /* TLBI operations */
4200     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4201       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4202       .access = PL1_W, .type = ARM_CP_NO_RAW,
4203       .writefn = tlbi_aa64_vmalle1is_write },
4204     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4205       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4206       .access = PL1_W, .type = ARM_CP_NO_RAW,
4207       .writefn = tlbi_aa64_vae1is_write },
4208     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4209       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4210       .access = PL1_W, .type = ARM_CP_NO_RAW,
4211       .writefn = tlbi_aa64_vmalle1is_write },
4212     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4213       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4214       .access = PL1_W, .type = ARM_CP_NO_RAW,
4215       .writefn = tlbi_aa64_vae1is_write },
4216     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4217       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4218       .access = PL1_W, .type = ARM_CP_NO_RAW,
4219       .writefn = tlbi_aa64_vae1is_write },
4220     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4221       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4222       .access = PL1_W, .type = ARM_CP_NO_RAW,
4223       .writefn = tlbi_aa64_vae1is_write },
4224     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4225       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4226       .access = PL1_W, .type = ARM_CP_NO_RAW,
4227       .writefn = tlbi_aa64_vmalle1_write },
4228     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4229       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4230       .access = PL1_W, .type = ARM_CP_NO_RAW,
4231       .writefn = tlbi_aa64_vae1_write },
4232     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4233       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4234       .access = PL1_W, .type = ARM_CP_NO_RAW,
4235       .writefn = tlbi_aa64_vmalle1_write },
4236     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4237       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4238       .access = PL1_W, .type = ARM_CP_NO_RAW,
4239       .writefn = tlbi_aa64_vae1_write },
4240     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4241       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4242       .access = PL1_W, .type = ARM_CP_NO_RAW,
4243       .writefn = tlbi_aa64_vae1_write },
4244     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4245       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4246       .access = PL1_W, .type = ARM_CP_NO_RAW,
4247       .writefn = tlbi_aa64_vae1_write },
4248     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4249       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4250       .access = PL2_W, .type = ARM_CP_NO_RAW,
4251       .writefn = tlbi_aa64_ipas2e1is_write },
4252     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4253       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4254       .access = PL2_W, .type = ARM_CP_NO_RAW,
4255       .writefn = tlbi_aa64_ipas2e1is_write },
4256     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4257       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4258       .access = PL2_W, .type = ARM_CP_NO_RAW,
4259       .writefn = tlbi_aa64_alle1is_write },
4260     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4261       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4262       .access = PL2_W, .type = ARM_CP_NO_RAW,
4263       .writefn = tlbi_aa64_alle1is_write },
4264     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4265       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4266       .access = PL2_W, .type = ARM_CP_NO_RAW,
4267       .writefn = tlbi_aa64_ipas2e1_write },
4268     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4269       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4270       .access = PL2_W, .type = ARM_CP_NO_RAW,
4271       .writefn = tlbi_aa64_ipas2e1_write },
4272     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4273       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4274       .access = PL2_W, .type = ARM_CP_NO_RAW,
4275       .writefn = tlbi_aa64_alle1_write },
4276     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4277       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4278       .access = PL2_W, .type = ARM_CP_NO_RAW,
4279       .writefn = tlbi_aa64_alle1is_write },
4280 #ifndef CONFIG_USER_ONLY
4281     /* 64 bit address translation operations */
4282     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4283       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4284       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4285     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4286       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4287       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4288     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4289       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4290       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4291     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4292       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4293       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4294     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4295       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4296       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4297     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4298       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4299       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4300     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4301       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4302       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4303     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4304       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4305       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4306     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4307     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4308       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4309       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4310     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4311       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4312       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4313     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4314       .type = ARM_CP_ALIAS,
4315       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4316       .access = PL1_RW, .resetvalue = 0,
4317       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4318       .writefn = par_write },
4319 #endif
4320     /* TLB invalidate last level of translation table walk */
4321     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4322       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
4323     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4324       .type = ARM_CP_NO_RAW, .access = PL1_W,
4325       .writefn = tlbimvaa_is_write },
4326     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4327       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
4328     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4329       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
4330     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4331       .type = ARM_CP_NO_RAW, .access = PL2_W,
4332       .writefn = tlbimva_hyp_write },
4333     { .name = "TLBIMVALHIS",
4334       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4335       .type = ARM_CP_NO_RAW, .access = PL2_W,
4336       .writefn = tlbimva_hyp_is_write },
4337     { .name = "TLBIIPAS2",
4338       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4339       .type = ARM_CP_NO_RAW, .access = PL2_W,
4340       .writefn = tlbiipas2_write },
4341     { .name = "TLBIIPAS2IS",
4342       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4343       .type = ARM_CP_NO_RAW, .access = PL2_W,
4344       .writefn = tlbiipas2_is_write },
4345     { .name = "TLBIIPAS2L",
4346       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4347       .type = ARM_CP_NO_RAW, .access = PL2_W,
4348       .writefn = tlbiipas2_write },
4349     { .name = "TLBIIPAS2LIS",
4350       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4351       .type = ARM_CP_NO_RAW, .access = PL2_W,
4352       .writefn = tlbiipas2_is_write },
4353     /* 32 bit cache operations */
4354     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4355       .type = ARM_CP_NOP, .access = PL1_W },
4356     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
4357       .type = ARM_CP_NOP, .access = PL1_W },
4358     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4359       .type = ARM_CP_NOP, .access = PL1_W },
4360     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
4361       .type = ARM_CP_NOP, .access = PL1_W },
4362     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
4363       .type = ARM_CP_NOP, .access = PL1_W },
4364     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
4365       .type = ARM_CP_NOP, .access = PL1_W },
4366     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4367       .type = ARM_CP_NOP, .access = PL1_W },
4368     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4369       .type = ARM_CP_NOP, .access = PL1_W },
4370     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
4371       .type = ARM_CP_NOP, .access = PL1_W },
4372     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4373       .type = ARM_CP_NOP, .access = PL1_W },
4374     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
4375       .type = ARM_CP_NOP, .access = PL1_W },
4376     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
4377       .type = ARM_CP_NOP, .access = PL1_W },
4378     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4379       .type = ARM_CP_NOP, .access = PL1_W },
4380     /* MMU Domain access control / MPU write buffer control */
4381     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
4382       .access = PL1_RW, .resetvalue = 0,
4383       .writefn = dacr_write, .raw_writefn = raw_write,
4384       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
4385                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
4386     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
4387       .type = ARM_CP_ALIAS,
4388       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
4389       .access = PL1_RW,
4390       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
4391     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
4392       .type = ARM_CP_ALIAS,
4393       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
4394       .access = PL1_RW,
4395       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
4396     /* We rely on the access checks not allowing the guest to write to the
4397      * state field when SPSel indicates that it's being used as the stack
4398      * pointer.
4399      */
4400     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
4401       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
4402       .access = PL1_RW, .accessfn = sp_el0_access,
4403       .type = ARM_CP_ALIAS,
4404       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
4405     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
4406       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
4407       .access = PL2_RW, .type = ARM_CP_ALIAS,
4408       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
4409     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
4410       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
4411       .type = ARM_CP_NO_RAW,
4412       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
4413     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
4414       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
4415       .type = ARM_CP_ALIAS,
4416       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
4417       .access = PL2_RW, .accessfn = fpexc32_access },
4418     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
4419       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
4420       .access = PL2_RW, .resetvalue = 0,
4421       .writefn = dacr_write, .raw_writefn = raw_write,
4422       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
4423     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
4424       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
4425       .access = PL2_RW, .resetvalue = 0,
4426       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
4427     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
4428       .type = ARM_CP_ALIAS,
4429       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
4430       .access = PL2_RW,
4431       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
4432     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
4433       .type = ARM_CP_ALIAS,
4434       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
4435       .access = PL2_RW,
4436       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
4437     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
4438       .type = ARM_CP_ALIAS,
4439       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
4440       .access = PL2_RW,
4441       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
4442     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
4443       .type = ARM_CP_ALIAS,
4444       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
4445       .access = PL2_RW,
4446       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
4447     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
4448       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
4449       .resetvalue = 0,
4450       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
4451     { .name = "SDCR", .type = ARM_CP_ALIAS,
4452       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
4453       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4454       .writefn = sdcr_write,
4455       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
4456     REGINFO_SENTINEL
4457 };
4458
4459 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
4460 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
4461     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4462       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4463       .access = PL2_RW,
4464       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
4465     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
4466       .type = ARM_CP_NO_RAW,
4467       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4468       .access = PL2_RW,
4469       .type = ARM_CP_CONST, .resetvalue = 0 },
4470     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4471       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4472       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4473     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4474       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4475       .access = PL2_RW,
4476       .type = ARM_CP_CONST, .resetvalue = 0 },
4477     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4478       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4479       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4480     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4481       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4482       .access = PL2_RW, .type = ARM_CP_CONST,
4483       .resetvalue = 0 },
4484     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4485       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4486       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4487     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4488       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4489       .access = PL2_RW, .type = ARM_CP_CONST,
4490       .resetvalue = 0 },
4491     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4492       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4493       .access = PL2_RW, .type = ARM_CP_CONST,
4494       .resetvalue = 0 },
4495     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4496       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4497       .access = PL2_RW, .type = ARM_CP_CONST,
4498       .resetvalue = 0 },
4499     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4500       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4501       .access = PL2_RW, .type = ARM_CP_CONST,
4502       .resetvalue = 0 },
4503     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4504       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4505       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4506     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
4507       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4508       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4509       .type = ARM_CP_CONST, .resetvalue = 0 },
4510     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4511       .cp = 15, .opc1 = 6, .crm = 2,
4512       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4513       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
4514     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4515       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4516       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4517     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4518       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4519       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4520     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4521       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4522       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4523     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4524       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4525       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4526     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4527       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4528       .resetvalue = 0 },
4529     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4530       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4531       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4532     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4533       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4534       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4535     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4536       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4537       .resetvalue = 0 },
4538     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4539       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4540       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4541     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4542       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4543       .resetvalue = 0 },
4544     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4545       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4546       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4547     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4548       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4549       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4550     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4551       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4552       .access = PL2_RW, .accessfn = access_tda,
4553       .type = ARM_CP_CONST, .resetvalue = 0 },
4554     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
4555       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4556       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4557       .type = ARM_CP_CONST, .resetvalue = 0 },
4558     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4559       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4560       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4561     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4562       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4563       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4564     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4565       .type = ARM_CP_CONST,
4566       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4567       .access = PL2_RW, .resetvalue = 0 },
4568     REGINFO_SENTINEL
4569 };
4570
4571 /* Ditto, but for registers which exist in ARMv8 but not v7 */
4572 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
4573     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4574       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4575       .access = PL2_RW,
4576       .type = ARM_CP_CONST, .resetvalue = 0 },
4577     REGINFO_SENTINEL
4578 };
4579
4580 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
4581 {
4582     ARMCPU *cpu = env_archcpu(env);
4583     uint64_t valid_mask = HCR_MASK;
4584
4585     if (arm_feature(env, ARM_FEATURE_EL3)) {
4586         valid_mask &= ~HCR_HCD;
4587     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
4588         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
4589          * However, if we're using the SMC PSCI conduit then QEMU is
4590          * effectively acting like EL3 firmware and so the guest at
4591          * EL2 should retain the ability to prevent EL1 from being
4592          * able to make SMC calls into the ersatz firmware, so in
4593          * that case HCR.TSC should be read/write.
4594          */
4595         valid_mask &= ~HCR_TSC;
4596     }
4597     if (cpu_isar_feature(aa64_lor, cpu)) {
4598         valid_mask |= HCR_TLOR;
4599     }
4600     if (cpu_isar_feature(aa64_pauth, cpu)) {
4601         valid_mask |= HCR_API | HCR_APK;
4602     }
4603
4604     /* Clear RES0 bits.  */
4605     value &= valid_mask;
4606
4607     /* These bits change the MMU setup:
4608      * HCR_VM enables stage 2 translation
4609      * HCR_PTW forbids certain page-table setups
4610      * HCR_DC Disables stage1 and enables stage2 translation
4611      */
4612     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
4613         tlb_flush(CPU(cpu));
4614     }
4615     env->cp15.hcr_el2 = value;
4616
4617     /*
4618      * Updates to VI and VF require us to update the status of
4619      * virtual interrupts, which are the logical OR of these bits
4620      * and the state of the input lines from the GIC. (This requires
4621      * that we have the iothread lock, which is done by marking the
4622      * reginfo structs as ARM_CP_IO.)
4623      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
4624      * possible for it to be taken immediately, because VIRQ and
4625      * VFIQ are masked unless running at EL0 or EL1, and HCR
4626      * can only be written at EL2.
4627      */
4628     g_assert(qemu_mutex_iothread_locked());
4629     arm_cpu_update_virq(cpu);
4630     arm_cpu_update_vfiq(cpu);
4631 }
4632
4633 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
4634                           uint64_t value)
4635 {
4636     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
4637     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
4638     hcr_write(env, NULL, value);
4639 }
4640
4641 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
4642                          uint64_t value)
4643 {
4644     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
4645     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
4646     hcr_write(env, NULL, value);
4647 }
4648
4649 /*
4650  * Return the effective value of HCR_EL2.
4651  * Bits that are not included here:
4652  * RW       (read from SCR_EL3.RW as needed)
4653  */
4654 uint64_t arm_hcr_el2_eff(CPUARMState *env)
4655 {
4656     uint64_t ret = env->cp15.hcr_el2;
4657
4658     if (arm_is_secure_below_el3(env)) {
4659         /*
4660          * "This register has no effect if EL2 is not enabled in the
4661          * current Security state".  This is ARMv8.4-SecEL2 speak for
4662          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
4663          *
4664          * Prior to that, the language was "In an implementation that
4665          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
4666          * as if this field is 0 for all purposes other than a direct
4667          * read or write access of HCR_EL2".  With lots of enumeration
4668          * on a per-field basis.  In current QEMU, this is condition
4669          * is arm_is_secure_below_el3.
4670          *
4671          * Since the v8.4 language applies to the entire register, and
4672          * appears to be backward compatible, use that.
4673          */
4674         ret = 0;
4675     } else if (ret & HCR_TGE) {
4676         /* These bits are up-to-date as of ARMv8.4.  */
4677         if (ret & HCR_E2H) {
4678             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
4679                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
4680                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
4681                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE);
4682         } else {
4683             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
4684         }
4685         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
4686                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
4687                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
4688                  HCR_TLOR);
4689     }
4690
4691     return ret;
4692 }
4693
4694 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4695                            uint64_t value)
4696 {
4697     /*
4698      * For A-profile AArch32 EL3, if NSACR.CP10
4699      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
4700      */
4701     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
4702         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
4703         value &= ~(0x3 << 10);
4704         value |= env->cp15.cptr_el[2] & (0x3 << 10);
4705     }
4706     env->cp15.cptr_el[2] = value;
4707 }
4708
4709 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
4710 {
4711     /*
4712      * For A-profile AArch32 EL3, if NSACR.CP10
4713      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
4714      */
4715     uint64_t value = env->cp15.cptr_el[2];
4716
4717     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
4718         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
4719         value |= 0x3 << 10;
4720     }
4721     return value;
4722 }
4723
4724 static const ARMCPRegInfo el2_cp_reginfo[] = {
4725     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
4726       .type = ARM_CP_IO,
4727       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4728       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4729       .writefn = hcr_write },
4730     { .name = "HCR", .state = ARM_CP_STATE_AA32,
4731       .type = ARM_CP_ALIAS | ARM_CP_IO,
4732       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4733       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4734       .writefn = hcr_writelow },
4735     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4736       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4737       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4738     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
4739       .type = ARM_CP_ALIAS,
4740       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
4741       .access = PL2_RW,
4742       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
4743     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4744       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4745       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
4746     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4747       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4748       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
4749     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4750       .type = ARM_CP_ALIAS,
4751       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4752       .access = PL2_RW,
4753       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
4754     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
4755       .type = ARM_CP_ALIAS,
4756       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
4757       .access = PL2_RW,
4758       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
4759     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4760       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4761       .access = PL2_RW, .writefn = vbar_write,
4762       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
4763       .resetvalue = 0 },
4764     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
4765       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
4766       .access = PL3_RW, .type = ARM_CP_ALIAS,
4767       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
4768     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4769       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4770       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
4771       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
4772       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
4773     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4774       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4775       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
4776       .resetvalue = 0 },
4777     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4778       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4779       .access = PL2_RW, .type = ARM_CP_ALIAS,
4780       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
4781     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4782       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4783       .access = PL2_RW, .type = ARM_CP_CONST,
4784       .resetvalue = 0 },
4785     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
4786     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4787       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4788       .access = PL2_RW, .type = ARM_CP_CONST,
4789       .resetvalue = 0 },
4790     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4791       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4792       .access = PL2_RW, .type = ARM_CP_CONST,
4793       .resetvalue = 0 },
4794     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4795       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4796       .access = PL2_RW, .type = ARM_CP_CONST,
4797       .resetvalue = 0 },
4798     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4799       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4800       .access = PL2_RW,
4801       /* no .writefn needed as this can't cause an ASID change;
4802        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4803        */
4804       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
4805     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
4806       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4807       .type = ARM_CP_ALIAS,
4808       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4809       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4810     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
4811       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4812       .access = PL2_RW,
4813       /* no .writefn needed as this can't cause an ASID change;
4814        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4815        */
4816       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4817     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4818       .cp = 15, .opc1 = 6, .crm = 2,
4819       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4820       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4821       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
4822       .writefn = vttbr_write },
4823     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4824       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4825       .access = PL2_RW, .writefn = vttbr_write,
4826       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
4827     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4828       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4829       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
4830       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
4831     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4832       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4833       .access = PL2_RW, .resetvalue = 0,
4834       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
4835     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4836       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4837       .access = PL2_RW, .resetvalue = 0,
4838       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4839     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4840       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4841       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4842     { .name = "TLBIALLNSNH",
4843       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4844       .type = ARM_CP_NO_RAW, .access = PL2_W,
4845       .writefn = tlbiall_nsnh_write },
4846     { .name = "TLBIALLNSNHIS",
4847       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4848       .type = ARM_CP_NO_RAW, .access = PL2_W,
4849       .writefn = tlbiall_nsnh_is_write },
4850     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4851       .type = ARM_CP_NO_RAW, .access = PL2_W,
4852       .writefn = tlbiall_hyp_write },
4853     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4854       .type = ARM_CP_NO_RAW, .access = PL2_W,
4855       .writefn = tlbiall_hyp_is_write },
4856     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4857       .type = ARM_CP_NO_RAW, .access = PL2_W,
4858       .writefn = tlbimva_hyp_write },
4859     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4860       .type = ARM_CP_NO_RAW, .access = PL2_W,
4861       .writefn = tlbimva_hyp_is_write },
4862     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
4863       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4864       .type = ARM_CP_NO_RAW, .access = PL2_W,
4865       .writefn = tlbi_aa64_alle2_write },
4866     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
4867       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4868       .type = ARM_CP_NO_RAW, .access = PL2_W,
4869       .writefn = tlbi_aa64_vae2_write },
4870     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
4871       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4872       .access = PL2_W, .type = ARM_CP_NO_RAW,
4873       .writefn = tlbi_aa64_vae2_write },
4874     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
4875       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4876       .access = PL2_W, .type = ARM_CP_NO_RAW,
4877       .writefn = tlbi_aa64_alle2is_write },
4878     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
4879       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4880       .type = ARM_CP_NO_RAW, .access = PL2_W,
4881       .writefn = tlbi_aa64_vae2is_write },
4882     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
4883       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4884       .access = PL2_W, .type = ARM_CP_NO_RAW,
4885       .writefn = tlbi_aa64_vae2is_write },
4886 #ifndef CONFIG_USER_ONLY
4887     /* Unlike the other EL2-related AT operations, these must
4888      * UNDEF from EL3 if EL2 is not implemented, which is why we
4889      * define them here rather than with the rest of the AT ops.
4890      */
4891     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
4892       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4893       .access = PL2_W, .accessfn = at_s1e2_access,
4894       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4895     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
4896       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4897       .access = PL2_W, .accessfn = at_s1e2_access,
4898       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4899     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
4900      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
4901      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
4902      * to behave as if SCR.NS was 1.
4903      */
4904     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4905       .access = PL2_W,
4906       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4907     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4908       .access = PL2_W,
4909       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4910     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4911       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4912       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
4913        * reset values as IMPDEF. We choose to reset to 3 to comply with
4914        * both ARMv7 and ARMv8.
4915        */
4916       .access = PL2_RW, .resetvalue = 3,
4917       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
4918     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4919       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4920       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
4921       .writefn = gt_cntvoff_write,
4922       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4923     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4924       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
4925       .writefn = gt_cntvoff_write,
4926       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4927     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4928       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4929       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4930       .type = ARM_CP_IO, .access = PL2_RW,
4931       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4932     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4933       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4934       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
4935       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4936     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4937       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4938       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
4939       .resetfn = gt_hyp_timer_reset,
4940       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
4941     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4942       .type = ARM_CP_IO,
4943       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4944       .access = PL2_RW,
4945       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
4946       .resetvalue = 0,
4947       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
4948 #endif
4949     /* The only field of MDCR_EL2 that has a defined architectural reset value
4950      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
4951      * don't implement any PMU event counters, so using zero as a reset
4952      * value for MDCR_EL2 is okay
4953      */
4954     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4955       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4956       .access = PL2_RW, .resetvalue = 0,
4957       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
4958     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
4959       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4960       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4961       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4962     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
4963       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4964       .access = PL2_RW,
4965       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4966     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4967       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4968       .access = PL2_RW,
4969       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
4970     REGINFO_SENTINEL
4971 };
4972
4973 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
4974     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4975       .type = ARM_CP_ALIAS | ARM_CP_IO,
4976       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4977       .access = PL2_RW,
4978       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
4979       .writefn = hcr_writehigh },
4980     REGINFO_SENTINEL
4981 };
4982
4983 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
4984                                    bool isread)
4985 {
4986     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
4987      * At Secure EL1 it traps to EL3.
4988      */
4989     if (arm_current_el(env) == 3) {
4990         return CP_ACCESS_OK;
4991     }
4992     if (arm_is_secure_below_el3(env)) {
4993         return CP_ACCESS_TRAP_EL3;
4994     }
4995     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
4996     if (isread) {
4997         return CP_ACCESS_OK;
4998     }
4999     return CP_ACCESS_TRAP_UNCATEGORIZED;
5000 }
5001
5002 static const ARMCPRegInfo el3_cp_reginfo[] = {
5003     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5004       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5005       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5006       .resetvalue = 0, .writefn = scr_write },
5007     { .name = "SCR",  .type = ARM_CP_ALIAS,
5008       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5009       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5010       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5011       .writefn = scr_write },
5012     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5013       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5014       .access = PL3_RW, .resetvalue = 0,
5015       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5016     { .name = "SDER",
5017       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5018       .access = PL3_RW, .resetvalue = 0,
5019       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5020     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5021       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5022       .writefn = vbar_write, .resetvalue = 0,
5023       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5024     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5025       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5026       .access = PL3_RW, .resetvalue = 0,
5027       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5028     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5029       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5030       .access = PL3_RW,
5031       /* no .writefn needed as this can't cause an ASID change;
5032        * we must provide a .raw_writefn and .resetfn because we handle
5033        * reset and migration for the AArch32 TTBCR(S), which might be
5034        * using mask and base_mask.
5035        */
5036       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5037       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5038     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5039       .type = ARM_CP_ALIAS,
5040       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5041       .access = PL3_RW,
5042       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5043     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5044       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5045       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5046     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5047       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5048       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5049     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5050       .type = ARM_CP_ALIAS,
5051       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5052       .access = PL3_RW,
5053       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5054     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5055       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5056       .access = PL3_RW, .writefn = vbar_write,
5057       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5058       .resetvalue = 0 },
5059     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5060       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5061       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5062       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5063     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5064       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5065       .access = PL3_RW, .resetvalue = 0,
5066       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5067     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5068       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5069       .access = PL3_RW, .type = ARM_CP_CONST,
5070       .resetvalue = 0 },
5071     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5072       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5073       .access = PL3_RW, .type = ARM_CP_CONST,
5074       .resetvalue = 0 },
5075     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5076       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5077       .access = PL3_RW, .type = ARM_CP_CONST,
5078       .resetvalue = 0 },
5079     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5080       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5081       .access = PL3_W, .type = ARM_CP_NO_RAW,
5082       .writefn = tlbi_aa64_alle3is_write },
5083     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5084       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5085       .access = PL3_W, .type = ARM_CP_NO_RAW,
5086       .writefn = tlbi_aa64_vae3is_write },
5087     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5088       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5089       .access = PL3_W, .type = ARM_CP_NO_RAW,
5090       .writefn = tlbi_aa64_vae3is_write },
5091     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5092       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5093       .access = PL3_W, .type = ARM_CP_NO_RAW,
5094       .writefn = tlbi_aa64_alle3_write },
5095     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5096       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5097       .access = PL3_W, .type = ARM_CP_NO_RAW,
5098       .writefn = tlbi_aa64_vae3_write },
5099     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5100       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5101       .access = PL3_W, .type = ARM_CP_NO_RAW,
5102       .writefn = tlbi_aa64_vae3_write },
5103     REGINFO_SENTINEL
5104 };
5105
5106 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5107                                      bool isread)
5108 {
5109     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
5110      * but the AArch32 CTR has its own reginfo struct)
5111      */
5112     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5113         return CP_ACCESS_TRAP;
5114     }
5115     return CP_ACCESS_OK;
5116 }
5117
5118 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5119                         uint64_t value)
5120 {
5121     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5122      * read via a bit in OSLSR_EL1.
5123      */
5124     int oslock;
5125
5126     if (ri->state == ARM_CP_STATE_AA32) {
5127         oslock = (value == 0xC5ACCE55);
5128     } else {
5129         oslock = value & 1;
5130     }
5131
5132     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5133 }
5134
5135 static const ARMCPRegInfo debug_cp_reginfo[] = {
5136     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5137      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5138      * unlike DBGDRAR it is never accessible from EL0.
5139      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5140      * accessor.
5141      */
5142     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5143       .access = PL0_R, .accessfn = access_tdra,
5144       .type = ARM_CP_CONST, .resetvalue = 0 },
5145     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5146       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5147       .access = PL1_R, .accessfn = access_tdra,
5148       .type = ARM_CP_CONST, .resetvalue = 0 },
5149     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5150       .access = PL0_R, .accessfn = access_tdra,
5151       .type = ARM_CP_CONST, .resetvalue = 0 },
5152     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5153     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5154       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5155       .access = PL1_RW, .accessfn = access_tda,
5156       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5157       .resetvalue = 0 },
5158     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
5159      * We don't implement the configurable EL0 access.
5160      */
5161     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
5162       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5163       .type = ARM_CP_ALIAS,
5164       .access = PL1_R, .accessfn = access_tda,
5165       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
5166     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
5167       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
5168       .access = PL1_W, .type = ARM_CP_NO_RAW,
5169       .accessfn = access_tdosa,
5170       .writefn = oslar_write },
5171     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
5172       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
5173       .access = PL1_R, .resetvalue = 10,
5174       .accessfn = access_tdosa,
5175       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
5176     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
5177     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
5178       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
5179       .access = PL1_RW, .accessfn = access_tdosa,
5180       .type = ARM_CP_NOP },
5181     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
5182      * implement vector catch debug events yet.
5183      */
5184     { .name = "DBGVCR",
5185       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5186       .access = PL1_RW, .accessfn = access_tda,
5187       .type = ARM_CP_NOP },
5188     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
5189      * to save and restore a 32-bit guest's DBGVCR)
5190      */
5191     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
5192       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
5193       .access = PL2_RW, .accessfn = access_tda,
5194       .type = ARM_CP_NOP },
5195     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
5196      * Channel but Linux may try to access this register. The 32-bit
5197      * alias is DBGDCCINT.
5198      */
5199     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
5200       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5201       .access = PL1_RW, .accessfn = access_tda,
5202       .type = ARM_CP_NOP },
5203     REGINFO_SENTINEL
5204 };
5205
5206 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
5207     /* 64 bit access versions of the (dummy) debug registers */
5208     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
5209       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5210     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
5211       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5212     REGINFO_SENTINEL
5213 };
5214
5215 /* Return the exception level to which exceptions should be taken
5216  * via SVEAccessTrap.  If an exception should be routed through
5217  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
5218  * take care of raising that exception.
5219  * C.f. the ARM pseudocode function CheckSVEEnabled.
5220  */
5221 int sve_exception_el(CPUARMState *env, int el)
5222 {
5223 #ifndef CONFIG_USER_ONLY
5224     if (el <= 1) {
5225         bool disabled = false;
5226
5227         /* The CPACR.ZEN controls traps to EL1:
5228          * 0, 2 : trap EL0 and EL1 accesses
5229          * 1    : trap only EL0 accesses
5230          * 3    : trap no accesses
5231          */
5232         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
5233             disabled = true;
5234         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
5235             disabled = el == 0;
5236         }
5237         if (disabled) {
5238             /* route_to_el2 */
5239             return (arm_feature(env, ARM_FEATURE_EL2)
5240                     && (arm_hcr_el2_eff(env) & HCR_TGE) ? 2 : 1);
5241         }
5242
5243         /* Check CPACR.FPEN.  */
5244         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
5245             disabled = true;
5246         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
5247             disabled = el == 0;
5248         }
5249         if (disabled) {
5250             return 0;
5251         }
5252     }
5253
5254     /* CPTR_EL2.  Since TZ and TFP are positive,
5255      * they will be zero when EL2 is not present.
5256      */
5257     if (el <= 2 && !arm_is_secure_below_el3(env)) {
5258         if (env->cp15.cptr_el[2] & CPTR_TZ) {
5259             return 2;
5260         }
5261         if (env->cp15.cptr_el[2] & CPTR_TFP) {
5262             return 0;
5263         }
5264     }
5265
5266     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
5267     if (arm_feature(env, ARM_FEATURE_EL3)
5268         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
5269         return 3;
5270     }
5271 #endif
5272     return 0;
5273 }
5274
5275 /*
5276  * Given that SVE is enabled, return the vector length for EL.
5277  */
5278 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
5279 {
5280     ARMCPU *cpu = env_archcpu(env);
5281     uint32_t zcr_len = cpu->sve_max_vq - 1;
5282
5283     if (el <= 1) {
5284         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
5285     }
5286     if (el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
5287         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
5288     }
5289     if (el < 3 && arm_feature(env, ARM_FEATURE_EL3)) {
5290         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
5291     }
5292     return zcr_len;
5293 }
5294
5295 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5296                       uint64_t value)
5297 {
5298     int cur_el = arm_current_el(env);
5299     int old_len = sve_zcr_len_for_el(env, cur_el);
5300     int new_len;
5301
5302     /* Bits other than [3:0] are RAZ/WI.  */
5303     raw_write(env, ri, value & 0xf);
5304
5305     /*
5306      * Because we arrived here, we know both FP and SVE are enabled;
5307      * otherwise we would have trapped access to the ZCR_ELn register.
5308      */
5309     new_len = sve_zcr_len_for_el(env, cur_el);
5310     if (new_len < old_len) {
5311         aarch64_sve_narrow_vq(env, new_len + 1);
5312     }
5313 }
5314
5315 static const ARMCPRegInfo zcr_el1_reginfo = {
5316     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
5317     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
5318     .access = PL1_RW, .type = ARM_CP_SVE,
5319     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
5320     .writefn = zcr_write, .raw_writefn = raw_write
5321 };
5322
5323 static const ARMCPRegInfo zcr_el2_reginfo = {
5324     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5325     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5326     .access = PL2_RW, .type = ARM_CP_SVE,
5327     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
5328     .writefn = zcr_write, .raw_writefn = raw_write
5329 };
5330
5331 static const ARMCPRegInfo zcr_no_el2_reginfo = {
5332     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5333     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5334     .access = PL2_RW, .type = ARM_CP_SVE,
5335     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
5336 };
5337
5338 static const ARMCPRegInfo zcr_el3_reginfo = {
5339     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
5340     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
5341     .access = PL3_RW, .type = ARM_CP_SVE,
5342     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
5343     .writefn = zcr_write, .raw_writefn = raw_write
5344 };
5345
5346 void hw_watchpoint_update(ARMCPU *cpu, int n)
5347 {
5348     CPUARMState *env = &cpu->env;
5349     vaddr len = 0;
5350     vaddr wvr = env->cp15.dbgwvr[n];
5351     uint64_t wcr = env->cp15.dbgwcr[n];
5352     int mask;
5353     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
5354
5355     if (env->cpu_watchpoint[n]) {
5356         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
5357         env->cpu_watchpoint[n] = NULL;
5358     }
5359
5360     if (!extract64(wcr, 0, 1)) {
5361         /* E bit clear : watchpoint disabled */
5362         return;
5363     }
5364
5365     switch (extract64(wcr, 3, 2)) {
5366     case 0:
5367         /* LSC 00 is reserved and must behave as if the wp is disabled */
5368         return;
5369     case 1:
5370         flags |= BP_MEM_READ;
5371         break;
5372     case 2:
5373         flags |= BP_MEM_WRITE;
5374         break;
5375     case 3:
5376         flags |= BP_MEM_ACCESS;
5377         break;
5378     }
5379
5380     /* Attempts to use both MASK and BAS fields simultaneously are
5381      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
5382      * thus generating a watchpoint for every byte in the masked region.
5383      */
5384     mask = extract64(wcr, 24, 4);
5385     if (mask == 1 || mask == 2) {
5386         /* Reserved values of MASK; we must act as if the mask value was
5387          * some non-reserved value, or as if the watchpoint were disabled.
5388          * We choose the latter.
5389          */
5390         return;
5391     } else if (mask) {
5392         /* Watchpoint covers an aligned area up to 2GB in size */
5393         len = 1ULL << mask;
5394         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
5395          * whether the watchpoint fires when the unmasked bits match; we opt
5396          * to generate the exceptions.
5397          */
5398         wvr &= ~(len - 1);
5399     } else {
5400         /* Watchpoint covers bytes defined by the byte address select bits */
5401         int bas = extract64(wcr, 5, 8);
5402         int basstart;
5403
5404         if (bas == 0) {
5405             /* This must act as if the watchpoint is disabled */
5406             return;
5407         }
5408
5409         if (extract64(wvr, 2, 1)) {
5410             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
5411              * ignored, and BAS[3:0] define which bytes to watch.
5412              */
5413             bas &= 0xf;
5414         }
5415         /* The BAS bits are supposed to be programmed to indicate a contiguous
5416          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
5417          * we fire for each byte in the word/doubleword addressed by the WVR.
5418          * We choose to ignore any non-zero bits after the first range of 1s.
5419          */
5420         basstart = ctz32(bas);
5421         len = cto32(bas >> basstart);
5422         wvr += basstart;
5423     }
5424
5425     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
5426                           &env->cpu_watchpoint[n]);
5427 }
5428
5429 void hw_watchpoint_update_all(ARMCPU *cpu)
5430 {
5431     int i;
5432     CPUARMState *env = &cpu->env;
5433
5434     /* Completely clear out existing QEMU watchpoints and our array, to
5435      * avoid possible stale entries following migration load.
5436      */
5437     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
5438     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
5439
5440     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
5441         hw_watchpoint_update(cpu, i);
5442     }
5443 }
5444
5445 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5446                          uint64_t value)
5447 {
5448     ARMCPU *cpu = env_archcpu(env);
5449     int i = ri->crm;
5450
5451     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
5452      * register reads and behaves as if values written are sign extended.
5453      * Bits [1:0] are RES0.
5454      */
5455     value = sextract64(value, 0, 49) & ~3ULL;
5456
5457     raw_write(env, ri, value);
5458     hw_watchpoint_update(cpu, i);
5459 }
5460
5461 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5462                          uint64_t value)
5463 {
5464     ARMCPU *cpu = env_archcpu(env);
5465     int i = ri->crm;
5466
5467     raw_write(env, ri, value);
5468     hw_watchpoint_update(cpu, i);
5469 }
5470
5471 void hw_breakpoint_update(ARMCPU *cpu, int n)
5472 {
5473     CPUARMState *env = &cpu->env;
5474     uint64_t bvr = env->cp15.dbgbvr[n];
5475     uint64_t bcr = env->cp15.dbgbcr[n];
5476     vaddr addr;
5477     int bt;
5478     int flags = BP_CPU;
5479
5480     if (env->cpu_breakpoint[n]) {
5481         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
5482         env->cpu_breakpoint[n] = NULL;
5483     }
5484
5485     if (!extract64(bcr, 0, 1)) {
5486         /* E bit clear : watchpoint disabled */
5487         return;
5488     }
5489
5490     bt = extract64(bcr, 20, 4);
5491
5492     switch (bt) {
5493     case 4: /* unlinked address mismatch (reserved if AArch64) */
5494     case 5: /* linked address mismatch (reserved if AArch64) */
5495         qemu_log_mask(LOG_UNIMP,
5496                       "arm: address mismatch breakpoint types not implemented\n");
5497         return;
5498     case 0: /* unlinked address match */
5499     case 1: /* linked address match */
5500     {
5501         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
5502          * we behave as if the register was sign extended. Bits [1:0] are
5503          * RES0. The BAS field is used to allow setting breakpoints on 16
5504          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
5505          * a bp will fire if the addresses covered by the bp and the addresses
5506          * covered by the insn overlap but the insn doesn't start at the
5507          * start of the bp address range. We choose to require the insn and
5508          * the bp to have the same address. The constraints on writing to
5509          * BAS enforced in dbgbcr_write mean we have only four cases:
5510          *  0b0000  => no breakpoint
5511          *  0b0011  => breakpoint on addr
5512          *  0b1100  => breakpoint on addr + 2
5513          *  0b1111  => breakpoint on addr
5514          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
5515          */
5516         int bas = extract64(bcr, 5, 4);
5517         addr = sextract64(bvr, 0, 49) & ~3ULL;
5518         if (bas == 0) {
5519             return;
5520         }
5521         if (bas == 0xc) {
5522             addr += 2;
5523         }
5524         break;
5525     }
5526     case 2: /* unlinked context ID match */
5527     case 8: /* unlinked VMID match (reserved if no EL2) */
5528     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
5529         qemu_log_mask(LOG_UNIMP,
5530                       "arm: unlinked context breakpoint types not implemented\n");
5531         return;
5532     case 9: /* linked VMID match (reserved if no EL2) */
5533     case 11: /* linked context ID and VMID match (reserved if no EL2) */
5534     case 3: /* linked context ID match */
5535     default:
5536         /* We must generate no events for Linked context matches (unless
5537          * they are linked to by some other bp/wp, which is handled in
5538          * updates for the linking bp/wp). We choose to also generate no events
5539          * for reserved values.
5540          */
5541         return;
5542     }
5543
5544     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
5545 }
5546
5547 void hw_breakpoint_update_all(ARMCPU *cpu)
5548 {
5549     int i;
5550     CPUARMState *env = &cpu->env;
5551
5552     /* Completely clear out existing QEMU breakpoints and our array, to
5553      * avoid possible stale entries following migration load.
5554      */
5555     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
5556     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
5557
5558     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
5559         hw_breakpoint_update(cpu, i);
5560     }
5561 }
5562
5563 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5564                          uint64_t value)
5565 {
5566     ARMCPU *cpu = env_archcpu(env);
5567     int i = ri->crm;
5568
5569     raw_write(env, ri, value);
5570     hw_breakpoint_update(cpu, i);
5571 }
5572
5573 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5574                          uint64_t value)
5575 {
5576     ARMCPU *cpu = env_archcpu(env);
5577     int i = ri->crm;
5578
5579     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
5580      * copy of BAS[0].
5581      */
5582     value = deposit64(value, 6, 1, extract64(value, 5, 1));
5583     value = deposit64(value, 8, 1, extract64(value, 7, 1));
5584
5585     raw_write(env, ri, value);
5586     hw_breakpoint_update(cpu, i);
5587 }
5588
5589 static void define_debug_regs(ARMCPU *cpu)
5590 {
5591     /* Define v7 and v8 architectural debug registers.
5592      * These are just dummy implementations for now.
5593      */
5594     int i;
5595     int wrps, brps, ctx_cmps;
5596     ARMCPRegInfo dbgdidr = {
5597         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
5598         .access = PL0_R, .accessfn = access_tda,
5599         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
5600     };
5601
5602     /* Note that all these register fields hold "number of Xs minus 1". */
5603     brps = extract32(cpu->dbgdidr, 24, 4);
5604     wrps = extract32(cpu->dbgdidr, 28, 4);
5605     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
5606
5607     assert(ctx_cmps <= brps);
5608
5609     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
5610      * of the debug registers such as number of breakpoints;
5611      * check that if they both exist then they agree.
5612      */
5613     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
5614         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
5615         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
5616         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
5617     }
5618
5619     define_one_arm_cp_reg(cpu, &dbgdidr);
5620     define_arm_cp_regs(cpu, debug_cp_reginfo);
5621
5622     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
5623         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
5624     }
5625
5626     for (i = 0; i < brps + 1; i++) {
5627         ARMCPRegInfo dbgregs[] = {
5628             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
5629               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
5630               .access = PL1_RW, .accessfn = access_tda,
5631               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
5632               .writefn = dbgbvr_write, .raw_writefn = raw_write
5633             },
5634             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
5635               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
5636               .access = PL1_RW, .accessfn = access_tda,
5637               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
5638               .writefn = dbgbcr_write, .raw_writefn = raw_write
5639             },
5640             REGINFO_SENTINEL
5641         };
5642         define_arm_cp_regs(cpu, dbgregs);
5643     }
5644
5645     for (i = 0; i < wrps + 1; i++) {
5646         ARMCPRegInfo dbgregs[] = {
5647             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
5648               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
5649               .access = PL1_RW, .accessfn = access_tda,
5650               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
5651               .writefn = dbgwvr_write, .raw_writefn = raw_write
5652             },
5653             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
5654               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
5655               .access = PL1_RW, .accessfn = access_tda,
5656               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
5657               .writefn = dbgwcr_write, .raw_writefn = raw_write
5658             },
5659             REGINFO_SENTINEL
5660         };
5661         define_arm_cp_regs(cpu, dbgregs);
5662     }
5663 }
5664
5665 /* We don't know until after realize whether there's a GICv3
5666  * attached, and that is what registers the gicv3 sysregs.
5667  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
5668  * at runtime.
5669  */
5670 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
5671 {
5672     ARMCPU *cpu = env_archcpu(env);
5673     uint64_t pfr1 = cpu->id_pfr1;
5674
5675     if (env->gicv3state) {
5676         pfr1 |= 1 << 28;
5677     }
5678     return pfr1;
5679 }
5680
5681 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
5682 {
5683     ARMCPU *cpu = env_archcpu(env);
5684     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
5685
5686     if (env->gicv3state) {
5687         pfr0 |= 1 << 24;
5688     }
5689     return pfr0;
5690 }
5691
5692 /* Shared logic between LORID and the rest of the LOR* registers.
5693  * Secure state has already been delt with.
5694  */
5695 static CPAccessResult access_lor_ns(CPUARMState *env)
5696 {
5697     int el = arm_current_el(env);
5698
5699     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
5700         return CP_ACCESS_TRAP_EL2;
5701     }
5702     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
5703         return CP_ACCESS_TRAP_EL3;
5704     }
5705     return CP_ACCESS_OK;
5706 }
5707
5708 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
5709                                    bool isread)
5710 {
5711     if (arm_is_secure_below_el3(env)) {
5712         /* Access ok in secure mode.  */
5713         return CP_ACCESS_OK;
5714     }
5715     return access_lor_ns(env);
5716 }
5717
5718 static CPAccessResult access_lor_other(CPUARMState *env,
5719                                        const ARMCPRegInfo *ri, bool isread)
5720 {
5721     if (arm_is_secure_below_el3(env)) {
5722         /* Access denied in secure mode.  */
5723         return CP_ACCESS_TRAP;
5724     }
5725     return access_lor_ns(env);
5726 }
5727
5728 #ifdef TARGET_AARCH64
5729 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
5730                                    bool isread)
5731 {
5732     int el = arm_current_el(env);
5733
5734     if (el < 2 &&
5735         arm_feature(env, ARM_FEATURE_EL2) &&
5736         !(arm_hcr_el2_eff(env) & HCR_APK)) {
5737         return CP_ACCESS_TRAP_EL2;
5738     }
5739     if (el < 3 &&
5740         arm_feature(env, ARM_FEATURE_EL3) &&
5741         !(env->cp15.scr_el3 & SCR_APK)) {
5742         return CP_ACCESS_TRAP_EL3;
5743     }
5744     return CP_ACCESS_OK;
5745 }
5746
5747 static const ARMCPRegInfo pauth_reginfo[] = {
5748     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5749       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
5750       .access = PL1_RW, .accessfn = access_pauth,
5751       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
5752     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5753       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
5754       .access = PL1_RW, .accessfn = access_pauth,
5755       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
5756     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5757       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
5758       .access = PL1_RW, .accessfn = access_pauth,
5759       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
5760     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5761       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
5762       .access = PL1_RW, .accessfn = access_pauth,
5763       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
5764     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5765       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
5766       .access = PL1_RW, .accessfn = access_pauth,
5767       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
5768     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5769       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
5770       .access = PL1_RW, .accessfn = access_pauth,
5771       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
5772     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5773       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
5774       .access = PL1_RW, .accessfn = access_pauth,
5775       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
5776     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5777       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
5778       .access = PL1_RW, .accessfn = access_pauth,
5779       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
5780     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5781       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
5782       .access = PL1_RW, .accessfn = access_pauth,
5783       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
5784     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5785       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
5786       .access = PL1_RW, .accessfn = access_pauth,
5787       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
5788     REGINFO_SENTINEL
5789 };
5790
5791 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
5792 {
5793     Error *err = NULL;
5794     uint64_t ret;
5795
5796     /* Success sets NZCV = 0000.  */
5797     env->NF = env->CF = env->VF = 0, env->ZF = 1;
5798
5799     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
5800         /*
5801          * ??? Failed, for unknown reasons in the crypto subsystem.
5802          * The best we can do is log the reason and return the
5803          * timed-out indication to the guest.  There is no reason
5804          * we know to expect this failure to be transitory, so the
5805          * guest may well hang retrying the operation.
5806          */
5807         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
5808                       ri->name, error_get_pretty(err));
5809         error_free(err);
5810
5811         env->ZF = 0; /* NZCF = 0100 */
5812         return 0;
5813     }
5814     return ret;
5815 }
5816
5817 /* We do not support re-seeding, so the two registers operate the same.  */
5818 static const ARMCPRegInfo rndr_reginfo[] = {
5819     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
5820       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5821       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
5822       .access = PL0_R, .readfn = rndr_readfn },
5823     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
5824       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5825       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
5826       .access = PL0_R, .readfn = rndr_readfn },
5827     REGINFO_SENTINEL
5828 };
5829 #endif
5830
5831 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
5832                                      bool isread)
5833 {
5834     int el = arm_current_el(env);
5835
5836     if (el == 0) {
5837         uint64_t sctlr = arm_sctlr(env, el);
5838         if (!(sctlr & SCTLR_EnRCTX)) {
5839             return CP_ACCESS_TRAP;
5840         }
5841     } else if (el == 1) {
5842         uint64_t hcr = arm_hcr_el2_eff(env);
5843         if (hcr & HCR_NV) {
5844             return CP_ACCESS_TRAP_EL2;
5845         }
5846     }
5847     return CP_ACCESS_OK;
5848 }
5849
5850 static const ARMCPRegInfo predinv_reginfo[] = {
5851     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
5852       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
5853       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5854     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
5855       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
5856       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5857     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
5858       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
5859       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5860     /*
5861      * Note the AArch32 opcodes have a different OPC1.
5862      */
5863     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
5864       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
5865       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5866     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
5867       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
5868       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5869     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
5870       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
5871       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5872     REGINFO_SENTINEL
5873 };
5874
5875 void register_cp_regs_for_features(ARMCPU *cpu)
5876 {
5877     /* Register all the coprocessor registers based on feature bits */
5878     CPUARMState *env = &cpu->env;
5879     if (arm_feature(env, ARM_FEATURE_M)) {
5880         /* M profile has no coprocessor registers */
5881         return;
5882     }
5883
5884     define_arm_cp_regs(cpu, cp_reginfo);
5885     if (!arm_feature(env, ARM_FEATURE_V8)) {
5886         /* Must go early as it is full of wildcards that may be
5887          * overridden by later definitions.
5888          */
5889         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
5890     }
5891
5892     if (arm_feature(env, ARM_FEATURE_V6)) {
5893         /* The ID registers all have impdef reset values */
5894         ARMCPRegInfo v6_idregs[] = {
5895             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
5896               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5897               .access = PL1_R, .type = ARM_CP_CONST,
5898               .resetvalue = cpu->id_pfr0 },
5899             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
5900              * the value of the GIC field until after we define these regs.
5901              */
5902             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
5903               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
5904               .access = PL1_R, .type = ARM_CP_NO_RAW,
5905               .readfn = id_pfr1_read,
5906               .writefn = arm_cp_write_ignore },
5907             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
5908               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
5909               .access = PL1_R, .type = ARM_CP_CONST,
5910               .resetvalue = cpu->id_dfr0 },
5911             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
5912               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
5913               .access = PL1_R, .type = ARM_CP_CONST,
5914               .resetvalue = cpu->id_afr0 },
5915             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
5916               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
5917               .access = PL1_R, .type = ARM_CP_CONST,
5918               .resetvalue = cpu->id_mmfr0 },
5919             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
5920               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
5921               .access = PL1_R, .type = ARM_CP_CONST,
5922               .resetvalue = cpu->id_mmfr1 },
5923             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
5924               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
5925               .access = PL1_R, .type = ARM_CP_CONST,
5926               .resetvalue = cpu->id_mmfr2 },
5927             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
5928               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
5929               .access = PL1_R, .type = ARM_CP_CONST,
5930               .resetvalue = cpu->id_mmfr3 },
5931             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
5932               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5933               .access = PL1_R, .type = ARM_CP_CONST,
5934               .resetvalue = cpu->isar.id_isar0 },
5935             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
5936               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
5937               .access = PL1_R, .type = ARM_CP_CONST,
5938               .resetvalue = cpu->isar.id_isar1 },
5939             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
5940               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5941               .access = PL1_R, .type = ARM_CP_CONST,
5942               .resetvalue = cpu->isar.id_isar2 },
5943             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
5944               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
5945               .access = PL1_R, .type = ARM_CP_CONST,
5946               .resetvalue = cpu->isar.id_isar3 },
5947             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
5948               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
5949               .access = PL1_R, .type = ARM_CP_CONST,
5950               .resetvalue = cpu->isar.id_isar4 },
5951             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
5952               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
5953               .access = PL1_R, .type = ARM_CP_CONST,
5954               .resetvalue = cpu->isar.id_isar5 },
5955             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
5956               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
5957               .access = PL1_R, .type = ARM_CP_CONST,
5958               .resetvalue = cpu->id_mmfr4 },
5959             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
5960               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
5961               .access = PL1_R, .type = ARM_CP_CONST,
5962               .resetvalue = cpu->isar.id_isar6 },
5963             REGINFO_SENTINEL
5964         };
5965         define_arm_cp_regs(cpu, v6_idregs);
5966         define_arm_cp_regs(cpu, v6_cp_reginfo);
5967     } else {
5968         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
5969     }
5970     if (arm_feature(env, ARM_FEATURE_V6K)) {
5971         define_arm_cp_regs(cpu, v6k_cp_reginfo);
5972     }
5973     if (arm_feature(env, ARM_FEATURE_V7MP) &&
5974         !arm_feature(env, ARM_FEATURE_PMSA)) {
5975         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
5976     }
5977     if (arm_feature(env, ARM_FEATURE_V7VE)) {
5978         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
5979     }
5980     if (arm_feature(env, ARM_FEATURE_V7)) {
5981         /* v7 performance monitor control register: same implementor
5982          * field as main ID register, and we implement four counters in
5983          * addition to the cycle count register.
5984          */
5985         unsigned int i, pmcrn = 4;
5986         ARMCPRegInfo pmcr = {
5987             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
5988             .access = PL0_RW,
5989             .type = ARM_CP_IO | ARM_CP_ALIAS,
5990             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
5991             .accessfn = pmreg_access, .writefn = pmcr_write,
5992             .raw_writefn = raw_write,
5993         };
5994         ARMCPRegInfo pmcr64 = {
5995             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
5996             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
5997             .access = PL0_RW, .accessfn = pmreg_access,
5998             .type = ARM_CP_IO,
5999             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6000             .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT),
6001             .writefn = pmcr_write, .raw_writefn = raw_write,
6002         };
6003         define_one_arm_cp_reg(cpu, &pmcr);
6004         define_one_arm_cp_reg(cpu, &pmcr64);
6005         for (i = 0; i < pmcrn; i++) {
6006             char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6007             char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6008             char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6009             char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6010             ARMCPRegInfo pmev_regs[] = {
6011                 { .name = pmevcntr_name, .cp = 15, .crn = 14,
6012                   .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6013                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6014                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6015                   .accessfn = pmreg_access },
6016                 { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6017                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6018                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6019                   .type = ARM_CP_IO,
6020                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6021                   .raw_readfn = pmevcntr_rawread,
6022                   .raw_writefn = pmevcntr_rawwrite },
6023                 { .name = pmevtyper_name, .cp = 15, .crn = 14,
6024                   .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6025                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6026                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6027                   .accessfn = pmreg_access },
6028                 { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6029                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6030                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6031                   .type = ARM_CP_IO,
6032                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6033                   .raw_writefn = pmevtyper_rawwrite },
6034                 REGINFO_SENTINEL
6035             };
6036             define_arm_cp_regs(cpu, pmev_regs);
6037             g_free(pmevcntr_name);
6038             g_free(pmevcntr_el0_name);
6039             g_free(pmevtyper_name);
6040             g_free(pmevtyper_el0_name);
6041         }
6042         ARMCPRegInfo clidr = {
6043             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
6044             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
6045             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
6046         };
6047         define_one_arm_cp_reg(cpu, &clidr);
6048         define_arm_cp_regs(cpu, v7_cp_reginfo);
6049         define_debug_regs(cpu);
6050     } else {
6051         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
6052     }
6053     if (FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) >= 4 &&
6054             FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) != 0xf) {
6055         ARMCPRegInfo v81_pmu_regs[] = {
6056             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6057               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6058               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6059               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6060             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6061               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6062               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6063               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6064             REGINFO_SENTINEL
6065         };
6066         define_arm_cp_regs(cpu, v81_pmu_regs);
6067     }
6068     if (arm_feature(env, ARM_FEATURE_V8)) {
6069         /* AArch64 ID registers, which all have impdef reset values.
6070          * Note that within the ID register ranges the unused slots
6071          * must all RAZ, not UNDEF; future architecture versions may
6072          * define new registers here.
6073          */
6074         ARMCPRegInfo v8_idregs[] = {
6075             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
6076              * know the right value for the GIC field until after we
6077              * define these regs.
6078              */
6079             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
6080               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
6081               .access = PL1_R, .type = ARM_CP_NO_RAW,
6082               .readfn = id_aa64pfr0_read,
6083               .writefn = arm_cp_write_ignore },
6084             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
6085               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
6086               .access = PL1_R, .type = ARM_CP_CONST,
6087               .resetvalue = cpu->isar.id_aa64pfr1},
6088             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6089               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
6090               .access = PL1_R, .type = ARM_CP_CONST,
6091               .resetvalue = 0 },
6092             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6093               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
6094               .access = PL1_R, .type = ARM_CP_CONST,
6095               .resetvalue = 0 },
6096             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
6097               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
6098               .access = PL1_R, .type = ARM_CP_CONST,
6099               /* At present, only SVEver == 0 is defined anyway.  */
6100               .resetvalue = 0 },
6101             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6102               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
6103               .access = PL1_R, .type = ARM_CP_CONST,
6104               .resetvalue = 0 },
6105             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6106               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
6107               .access = PL1_R, .type = ARM_CP_CONST,
6108               .resetvalue = 0 },
6109             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6110               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
6111               .access = PL1_R, .type = ARM_CP_CONST,
6112               .resetvalue = 0 },
6113             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
6114               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
6115               .access = PL1_R, .type = ARM_CP_CONST,
6116               .resetvalue = cpu->id_aa64dfr0 },
6117             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
6118               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
6119               .access = PL1_R, .type = ARM_CP_CONST,
6120               .resetvalue = cpu->id_aa64dfr1 },
6121             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6122               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
6123               .access = PL1_R, .type = ARM_CP_CONST,
6124               .resetvalue = 0 },
6125             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6126               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
6127               .access = PL1_R, .type = ARM_CP_CONST,
6128               .resetvalue = 0 },
6129             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
6130               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
6131               .access = PL1_R, .type = ARM_CP_CONST,
6132               .resetvalue = cpu->id_aa64afr0 },
6133             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
6134               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
6135               .access = PL1_R, .type = ARM_CP_CONST,
6136               .resetvalue = cpu->id_aa64afr1 },
6137             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6138               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
6139               .access = PL1_R, .type = ARM_CP_CONST,
6140               .resetvalue = 0 },
6141             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6142               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
6143               .access = PL1_R, .type = ARM_CP_CONST,
6144               .resetvalue = 0 },
6145             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
6146               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
6147               .access = PL1_R, .type = ARM_CP_CONST,
6148               .resetvalue = cpu->isar.id_aa64isar0 },
6149             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
6150               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
6151               .access = PL1_R, .type = ARM_CP_CONST,
6152               .resetvalue = cpu->isar.id_aa64isar1 },
6153             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6154               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
6155               .access = PL1_R, .type = ARM_CP_CONST,
6156               .resetvalue = 0 },
6157             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6158               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
6159               .access = PL1_R, .type = ARM_CP_CONST,
6160               .resetvalue = 0 },
6161             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6162               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
6163               .access = PL1_R, .type = ARM_CP_CONST,
6164               .resetvalue = 0 },
6165             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6166               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
6167               .access = PL1_R, .type = ARM_CP_CONST,
6168               .resetvalue = 0 },
6169             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6170               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
6171               .access = PL1_R, .type = ARM_CP_CONST,
6172               .resetvalue = 0 },
6173             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6174               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
6175               .access = PL1_R, .type = ARM_CP_CONST,
6176               .resetvalue = 0 },
6177             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
6178               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6179               .access = PL1_R, .type = ARM_CP_CONST,
6180               .resetvalue = cpu->isar.id_aa64mmfr0 },
6181             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
6182               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
6183               .access = PL1_R, .type = ARM_CP_CONST,
6184               .resetvalue = cpu->isar.id_aa64mmfr1 },
6185             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6186               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
6187               .access = PL1_R, .type = ARM_CP_CONST,
6188               .resetvalue = 0 },
6189             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6190               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
6191               .access = PL1_R, .type = ARM_CP_CONST,
6192               .resetvalue = 0 },
6193             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6194               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
6195               .access = PL1_R, .type = ARM_CP_CONST,
6196               .resetvalue = 0 },
6197             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6198               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
6199               .access = PL1_R, .type = ARM_CP_CONST,
6200               .resetvalue = 0 },
6201             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6202               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
6203               .access = PL1_R, .type = ARM_CP_CONST,
6204               .resetvalue = 0 },
6205             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6206               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
6207               .access = PL1_R, .type = ARM_CP_CONST,
6208               .resetvalue = 0 },
6209             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
6210               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
6211               .access = PL1_R, .type = ARM_CP_CONST,
6212               .resetvalue = cpu->isar.mvfr0 },
6213             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
6214               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
6215               .access = PL1_R, .type = ARM_CP_CONST,
6216               .resetvalue = cpu->isar.mvfr1 },
6217             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
6218               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
6219               .access = PL1_R, .type = ARM_CP_CONST,
6220               .resetvalue = cpu->isar.mvfr2 },
6221             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6222               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
6223               .access = PL1_R, .type = ARM_CP_CONST,
6224               .resetvalue = 0 },
6225             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6226               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
6227               .access = PL1_R, .type = ARM_CP_CONST,
6228               .resetvalue = 0 },
6229             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6230               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
6231               .access = PL1_R, .type = ARM_CP_CONST,
6232               .resetvalue = 0 },
6233             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6234               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
6235               .access = PL1_R, .type = ARM_CP_CONST,
6236               .resetvalue = 0 },
6237             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6238               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
6239               .access = PL1_R, .type = ARM_CP_CONST,
6240               .resetvalue = 0 },
6241             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
6242               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
6243               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6244               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
6245             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
6246               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
6247               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6248               .resetvalue = cpu->pmceid0 },
6249             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
6250               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
6251               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6252               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
6253             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
6254               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
6255               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6256               .resetvalue = cpu->pmceid1 },
6257             REGINFO_SENTINEL
6258         };
6259 #ifdef CONFIG_USER_ONLY
6260         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
6261             { .name = "ID_AA64PFR0_EL1",
6262               .exported_bits = 0x000f000f00ff0000,
6263               .fixed_bits    = 0x0000000000000011 },
6264             { .name = "ID_AA64PFR1_EL1",
6265               .exported_bits = 0x00000000000000f0 },
6266             { .name = "ID_AA64PFR*_EL1_RESERVED",
6267               .is_glob = true                     },
6268             { .name = "ID_AA64ZFR0_EL1"           },
6269             { .name = "ID_AA64MMFR0_EL1",
6270               .fixed_bits    = 0x00000000ff000000 },
6271             { .name = "ID_AA64MMFR1_EL1"          },
6272             { .name = "ID_AA64MMFR*_EL1_RESERVED",
6273               .is_glob = true                     },
6274             { .name = "ID_AA64DFR0_EL1",
6275               .fixed_bits    = 0x0000000000000006 },
6276             { .name = "ID_AA64DFR1_EL1"           },
6277             { .name = "ID_AA64DFR*_EL1_RESERVED",
6278               .is_glob = true                     },
6279             { .name = "ID_AA64AFR*",
6280               .is_glob = true                     },
6281             { .name = "ID_AA64ISAR0_EL1",
6282               .exported_bits = 0x00fffffff0fffff0 },
6283             { .name = "ID_AA64ISAR1_EL1",
6284               .exported_bits = 0x000000f0ffffffff },
6285             { .name = "ID_AA64ISAR*_EL1_RESERVED",
6286               .is_glob = true                     },
6287             REGUSERINFO_SENTINEL
6288         };
6289         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
6290 #endif
6291         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
6292         if (!arm_feature(env, ARM_FEATURE_EL3) &&
6293             !arm_feature(env, ARM_FEATURE_EL2)) {
6294             ARMCPRegInfo rvbar = {
6295                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
6296                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
6297                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
6298             };
6299             define_one_arm_cp_reg(cpu, &rvbar);
6300         }
6301         define_arm_cp_regs(cpu, v8_idregs);
6302         define_arm_cp_regs(cpu, v8_cp_reginfo);
6303     }
6304     if (arm_feature(env, ARM_FEATURE_EL2)) {
6305         uint64_t vmpidr_def = mpidr_read_val(env);
6306         ARMCPRegInfo vpidr_regs[] = {
6307             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
6308               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6309               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6310               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
6311               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
6312             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
6313               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6314               .access = PL2_RW, .resetvalue = cpu->midr,
6315               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6316             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
6317               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6318               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6319               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
6320               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
6321             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
6322               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6323               .access = PL2_RW,
6324               .resetvalue = vmpidr_def,
6325               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
6326             REGINFO_SENTINEL
6327         };
6328         define_arm_cp_regs(cpu, vpidr_regs);
6329         define_arm_cp_regs(cpu, el2_cp_reginfo);
6330         if (arm_feature(env, ARM_FEATURE_V8)) {
6331             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
6332         }
6333         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
6334         if (!arm_feature(env, ARM_FEATURE_EL3)) {
6335             ARMCPRegInfo rvbar = {
6336                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
6337                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
6338                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
6339             };
6340             define_one_arm_cp_reg(cpu, &rvbar);
6341         }
6342     } else {
6343         /* If EL2 is missing but higher ELs are enabled, we need to
6344          * register the no_el2 reginfos.
6345          */
6346         if (arm_feature(env, ARM_FEATURE_EL3)) {
6347             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
6348              * of MIDR_EL1 and MPIDR_EL1.
6349              */
6350             ARMCPRegInfo vpidr_regs[] = {
6351                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6352                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6353                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6354                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
6355                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6356                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6357                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6358                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6359                   .type = ARM_CP_NO_RAW,
6360                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
6361                 REGINFO_SENTINEL
6362             };
6363             define_arm_cp_regs(cpu, vpidr_regs);
6364             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
6365             if (arm_feature(env, ARM_FEATURE_V8)) {
6366                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
6367             }
6368         }
6369     }
6370     if (arm_feature(env, ARM_FEATURE_EL3)) {
6371         define_arm_cp_regs(cpu, el3_cp_reginfo);
6372         ARMCPRegInfo el3_regs[] = {
6373             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
6374               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
6375               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
6376             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
6377               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
6378               .access = PL3_RW,
6379               .raw_writefn = raw_write, .writefn = sctlr_write,
6380               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
6381               .resetvalue = cpu->reset_sctlr },
6382             REGINFO_SENTINEL
6383         };
6384
6385         define_arm_cp_regs(cpu, el3_regs);
6386     }
6387     /* The behaviour of NSACR is sufficiently various that we don't
6388      * try to describe it in a single reginfo:
6389      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
6390      *     reads as constant 0xc00 from NS EL1 and NS EL2
6391      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
6392      *  if v7 without EL3, register doesn't exist
6393      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
6394      */
6395     if (arm_feature(env, ARM_FEATURE_EL3)) {
6396         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6397             ARMCPRegInfo nsacr = {
6398                 .name = "NSACR", .type = ARM_CP_CONST,
6399                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6400                 .access = PL1_RW, .accessfn = nsacr_access,
6401                 .resetvalue = 0xc00
6402             };
6403             define_one_arm_cp_reg(cpu, &nsacr);
6404         } else {
6405             ARMCPRegInfo nsacr = {
6406                 .name = "NSACR",
6407                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6408                 .access = PL3_RW | PL1_R,
6409                 .resetvalue = 0,
6410                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
6411             };
6412             define_one_arm_cp_reg(cpu, &nsacr);
6413         }
6414     } else {
6415         if (arm_feature(env, ARM_FEATURE_V8)) {
6416             ARMCPRegInfo nsacr = {
6417                 .name = "NSACR", .type = ARM_CP_CONST,
6418                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6419                 .access = PL1_R,
6420                 .resetvalue = 0xc00
6421             };
6422             define_one_arm_cp_reg(cpu, &nsacr);
6423         }
6424     }
6425
6426     if (arm_feature(env, ARM_FEATURE_PMSA)) {
6427         if (arm_feature(env, ARM_FEATURE_V6)) {
6428             /* PMSAv6 not implemented */
6429             assert(arm_feature(env, ARM_FEATURE_V7));
6430             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6431             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
6432         } else {
6433             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
6434         }
6435     } else {
6436         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6437         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
6438         /* TTCBR2 is introduced with ARMv8.2-A32HPD.  */
6439         if (FIELD_EX32(cpu->id_mmfr4, ID_MMFR4, HPDS) != 0) {
6440             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
6441         }
6442     }
6443     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
6444         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
6445     }
6446     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
6447         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
6448     }
6449     if (arm_feature(env, ARM_FEATURE_VAPA)) {
6450         define_arm_cp_regs(cpu, vapa_cp_reginfo);
6451     }
6452     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
6453         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
6454     }
6455     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
6456         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
6457     }
6458     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
6459         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
6460     }
6461     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
6462         define_arm_cp_regs(cpu, omap_cp_reginfo);
6463     }
6464     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
6465         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
6466     }
6467     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6468         define_arm_cp_regs(cpu, xscale_cp_reginfo);
6469     }
6470     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
6471         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
6472     }
6473     if (arm_feature(env, ARM_FEATURE_LPAE)) {
6474         define_arm_cp_regs(cpu, lpae_cp_reginfo);
6475     }
6476     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
6477      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
6478      * be read-only (ie write causes UNDEF exception).
6479      */
6480     {
6481         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
6482             /* Pre-v8 MIDR space.
6483              * Note that the MIDR isn't a simple constant register because
6484              * of the TI925 behaviour where writes to another register can
6485              * cause the MIDR value to change.
6486              *
6487              * Unimplemented registers in the c15 0 0 0 space default to
6488              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
6489              * and friends override accordingly.
6490              */
6491             { .name = "MIDR",
6492               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
6493               .access = PL1_R, .resetvalue = cpu->midr,
6494               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
6495               .readfn = midr_read,
6496               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6497               .type = ARM_CP_OVERRIDE },
6498             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
6499             { .name = "DUMMY",
6500               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
6501               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6502             { .name = "DUMMY",
6503               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
6504               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6505             { .name = "DUMMY",
6506               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
6507               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6508             { .name = "DUMMY",
6509               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
6510               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6511             { .name = "DUMMY",
6512               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
6513               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6514             REGINFO_SENTINEL
6515         };
6516         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
6517             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
6518               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
6519               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
6520               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6521               .readfn = midr_read },
6522             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
6523             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6524               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6525               .access = PL1_R, .resetvalue = cpu->midr },
6526             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6527               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
6528               .access = PL1_R, .resetvalue = cpu->midr },
6529             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
6530               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
6531               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
6532             REGINFO_SENTINEL
6533         };
6534         ARMCPRegInfo id_cp_reginfo[] = {
6535             /* These are common to v8 and pre-v8 */
6536             { .name = "CTR",
6537               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
6538               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6539             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
6540               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
6541               .access = PL0_R, .accessfn = ctr_el0_access,
6542               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6543             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
6544             { .name = "TCMTR",
6545               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
6546               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6547             REGINFO_SENTINEL
6548         };
6549         /* TLBTR is specific to VMSA */
6550         ARMCPRegInfo id_tlbtr_reginfo = {
6551               .name = "TLBTR",
6552               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
6553               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
6554         };
6555         /* MPUIR is specific to PMSA V6+ */
6556         ARMCPRegInfo id_mpuir_reginfo = {
6557               .name = "MPUIR",
6558               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6559               .access = PL1_R, .type = ARM_CP_CONST,
6560               .resetvalue = cpu->pmsav7_dregion << 8
6561         };
6562         ARMCPRegInfo crn0_wi_reginfo = {
6563             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
6564             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
6565             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
6566         };
6567 #ifdef CONFIG_USER_ONLY
6568         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
6569             { .name = "MIDR_EL1",
6570               .exported_bits = 0x00000000ffffffff },
6571             { .name = "REVIDR_EL1"                },
6572             REGUSERINFO_SENTINEL
6573         };
6574         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
6575 #endif
6576         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
6577             arm_feature(env, ARM_FEATURE_STRONGARM)) {
6578             ARMCPRegInfo *r;
6579             /* Register the blanket "writes ignored" value first to cover the
6580              * whole space. Then update the specific ID registers to allow write
6581              * access, so that they ignore writes rather than causing them to
6582              * UNDEF.
6583              */
6584             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
6585             for (r = id_pre_v8_midr_cp_reginfo;
6586                  r->type != ARM_CP_SENTINEL; r++) {
6587                 r->access = PL1_RW;
6588             }
6589             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
6590                 r->access = PL1_RW;
6591             }
6592             id_mpuir_reginfo.access = PL1_RW;
6593             id_tlbtr_reginfo.access = PL1_RW;
6594         }
6595         if (arm_feature(env, ARM_FEATURE_V8)) {
6596             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
6597         } else {
6598             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
6599         }
6600         define_arm_cp_regs(cpu, id_cp_reginfo);
6601         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
6602             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
6603         } else if (arm_feature(env, ARM_FEATURE_V7)) {
6604             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
6605         }
6606     }
6607
6608     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
6609         ARMCPRegInfo mpidr_cp_reginfo[] = {
6610             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
6611               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
6612               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
6613             REGINFO_SENTINEL
6614         };
6615 #ifdef CONFIG_USER_ONLY
6616         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
6617             { .name = "MPIDR_EL1",
6618               .fixed_bits = 0x0000000080000000 },
6619             REGUSERINFO_SENTINEL
6620         };
6621         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
6622 #endif
6623         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
6624     }
6625
6626     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
6627         ARMCPRegInfo auxcr_reginfo[] = {
6628             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
6629               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
6630               .access = PL1_RW, .type = ARM_CP_CONST,
6631               .resetvalue = cpu->reset_auxcr },
6632             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
6633               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
6634               .access = PL2_RW, .type = ARM_CP_CONST,
6635               .resetvalue = 0 },
6636             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
6637               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
6638               .access = PL3_RW, .type = ARM_CP_CONST,
6639               .resetvalue = 0 },
6640             REGINFO_SENTINEL
6641         };
6642         define_arm_cp_regs(cpu, auxcr_reginfo);
6643         if (arm_feature(env, ARM_FEATURE_V8)) {
6644             /* HACTLR2 maps to ACTLR_EL2[63:32] and is not in ARMv7 */
6645             ARMCPRegInfo hactlr2_reginfo = {
6646                 .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
6647                 .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
6648                 .access = PL2_RW, .type = ARM_CP_CONST,
6649                 .resetvalue = 0
6650             };
6651             define_one_arm_cp_reg(cpu, &hactlr2_reginfo);
6652         }
6653     }
6654
6655     if (arm_feature(env, ARM_FEATURE_CBAR)) {
6656         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6657             /* 32 bit view is [31:18] 0...0 [43:32]. */
6658             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
6659                 | extract64(cpu->reset_cbar, 32, 12);
6660             ARMCPRegInfo cbar_reginfo[] = {
6661                 { .name = "CBAR",
6662                   .type = ARM_CP_CONST,
6663                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
6664                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
6665                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
6666                   .type = ARM_CP_CONST,
6667                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
6668                   .access = PL1_R, .resetvalue = cbar32 },
6669                 REGINFO_SENTINEL
6670             };
6671             /* We don't implement a r/w 64 bit CBAR currently */
6672             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
6673             define_arm_cp_regs(cpu, cbar_reginfo);
6674         } else {
6675             ARMCPRegInfo cbar = {
6676                 .name = "CBAR",
6677                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
6678                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
6679                 .fieldoffset = offsetof(CPUARMState,
6680                                         cp15.c15_config_base_address)
6681             };
6682             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
6683                 cbar.access = PL1_R;
6684                 cbar.fieldoffset = 0;
6685                 cbar.type = ARM_CP_CONST;
6686             }
6687             define_one_arm_cp_reg(cpu, &cbar);
6688         }
6689     }
6690
6691     if (arm_feature(env, ARM_FEATURE_VBAR)) {
6692         ARMCPRegInfo vbar_cp_reginfo[] = {
6693             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
6694               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
6695               .access = PL1_RW, .writefn = vbar_write,
6696               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
6697                                      offsetof(CPUARMState, cp15.vbar_ns) },
6698               .resetvalue = 0 },
6699             REGINFO_SENTINEL
6700         };
6701         define_arm_cp_regs(cpu, vbar_cp_reginfo);
6702     }
6703
6704     /* Generic registers whose values depend on the implementation */
6705     {
6706         ARMCPRegInfo sctlr = {
6707             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
6708             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6709             .access = PL1_RW,
6710             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
6711                                    offsetof(CPUARMState, cp15.sctlr_ns) },
6712             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
6713             .raw_writefn = raw_write,
6714         };
6715         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6716             /* Normally we would always end the TB on an SCTLR write, but Linux
6717              * arch/arm/mach-pxa/sleep.S expects two instructions following
6718              * an MMU enable to execute from cache.  Imitate this behaviour.
6719              */
6720             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
6721         }
6722         define_one_arm_cp_reg(cpu, &sctlr);
6723     }
6724
6725     if (cpu_isar_feature(aa64_lor, cpu)) {
6726         /*
6727          * A trivial implementation of ARMv8.1-LOR leaves all of these
6728          * registers fixed at 0, which indicates that there are zero
6729          * supported Limited Ordering regions.
6730          */
6731         static const ARMCPRegInfo lor_reginfo[] = {
6732             { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6733               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6734               .access = PL1_RW, .accessfn = access_lor_other,
6735               .type = ARM_CP_CONST, .resetvalue = 0 },
6736             { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6737               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6738               .access = PL1_RW, .accessfn = access_lor_other,
6739               .type = ARM_CP_CONST, .resetvalue = 0 },
6740             { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6741               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6742               .access = PL1_RW, .accessfn = access_lor_other,
6743               .type = ARM_CP_CONST, .resetvalue = 0 },
6744             { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6745               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6746               .access = PL1_RW, .accessfn = access_lor_other,
6747               .type = ARM_CP_CONST, .resetvalue = 0 },
6748             { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6749               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6750               .access = PL1_R, .accessfn = access_lorid,
6751               .type = ARM_CP_CONST, .resetvalue = 0 },
6752             REGINFO_SENTINEL
6753         };
6754         define_arm_cp_regs(cpu, lor_reginfo);
6755     }
6756
6757     if (cpu_isar_feature(aa64_sve, cpu)) {
6758         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
6759         if (arm_feature(env, ARM_FEATURE_EL2)) {
6760             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
6761         } else {
6762             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
6763         }
6764         if (arm_feature(env, ARM_FEATURE_EL3)) {
6765             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
6766         }
6767     }
6768
6769 #ifdef TARGET_AARCH64
6770     if (cpu_isar_feature(aa64_pauth, cpu)) {
6771         define_arm_cp_regs(cpu, pauth_reginfo);
6772     }
6773     if (cpu_isar_feature(aa64_rndr, cpu)) {
6774         define_arm_cp_regs(cpu, rndr_reginfo);
6775     }
6776 #endif
6777
6778     /*
6779      * While all v8.0 cpus support aarch64, QEMU does have configurations
6780      * that do not set ID_AA64ISAR1, e.g. user-only qemu-arm -cpu max,
6781      * which will set ID_ISAR6.
6782      */
6783     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)
6784         ? cpu_isar_feature(aa64_predinv, cpu)
6785         : cpu_isar_feature(aa32_predinv, cpu)) {
6786         define_arm_cp_regs(cpu, predinv_reginfo);
6787     }
6788 }
6789
6790 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
6791 {
6792     CPUState *cs = CPU(cpu);
6793     CPUARMState *env = &cpu->env;
6794
6795     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6796         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
6797                                  aarch64_fpu_gdb_set_reg,
6798                                  34, "aarch64-fpu.xml", 0);
6799     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
6800         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6801                                  51, "arm-neon.xml", 0);
6802     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
6803         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6804                                  35, "arm-vfp3.xml", 0);
6805     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
6806         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6807                                  19, "arm-vfp.xml", 0);
6808     }
6809     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
6810                              arm_gen_dynamic_xml(cs),
6811                              "system-registers.xml", 0);
6812 }
6813
6814 /* Sort alphabetically by type name, except for "any". */
6815 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
6816 {
6817     ObjectClass *class_a = (ObjectClass *)a;
6818     ObjectClass *class_b = (ObjectClass *)b;
6819     const char *name_a, *name_b;
6820
6821     name_a = object_class_get_name(class_a);
6822     name_b = object_class_get_name(class_b);
6823     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
6824         return 1;
6825     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
6826         return -1;
6827     } else {
6828         return strcmp(name_a, name_b);
6829     }
6830 }
6831
6832 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
6833 {
6834     ObjectClass *oc = data;
6835     const char *typename;
6836     char *name;
6837
6838     typename = object_class_get_name(oc);
6839     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
6840     qemu_printf("  %s\n", name);
6841     g_free(name);
6842 }
6843
6844 void arm_cpu_list(void)
6845 {
6846     GSList *list;
6847
6848     list = object_class_get_list(TYPE_ARM_CPU, false);
6849     list = g_slist_sort(list, arm_cpu_list_compare);
6850     qemu_printf("Available CPUs:\n");
6851     g_slist_foreach(list, arm_cpu_list_entry, NULL);
6852     g_slist_free(list);
6853 }
6854
6855 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
6856 {
6857     ObjectClass *oc = data;
6858     CpuDefinitionInfoList **cpu_list = user_data;
6859     CpuDefinitionInfoList *entry;
6860     CpuDefinitionInfo *info;
6861     const char *typename;
6862
6863     typename = object_class_get_name(oc);
6864     info = g_malloc0(sizeof(*info));
6865     info->name = g_strndup(typename,
6866                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
6867     info->q_typename = g_strdup(typename);
6868
6869     entry = g_malloc0(sizeof(*entry));
6870     entry->value = info;
6871     entry->next = *cpu_list;
6872     *cpu_list = entry;
6873 }
6874
6875 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
6876 {
6877     CpuDefinitionInfoList *cpu_list = NULL;
6878     GSList *list;
6879
6880     list = object_class_get_list(TYPE_ARM_CPU, false);
6881     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
6882     g_slist_free(list);
6883
6884     return cpu_list;
6885 }
6886
6887 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
6888                                    void *opaque, int state, int secstate,
6889                                    int crm, int opc1, int opc2,
6890                                    const char *name)
6891 {
6892     /* Private utility function for define_one_arm_cp_reg_with_opaque():
6893      * add a single reginfo struct to the hash table.
6894      */
6895     uint32_t *key = g_new(uint32_t, 1);
6896     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
6897     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
6898     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
6899
6900     r2->name = g_strdup(name);
6901     /* Reset the secure state to the specific incoming state.  This is
6902      * necessary as the register may have been defined with both states.
6903      */
6904     r2->secure = secstate;
6905
6906     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
6907         /* Register is banked (using both entries in array).
6908          * Overwriting fieldoffset as the array is only used to define
6909          * banked registers but later only fieldoffset is used.
6910          */
6911         r2->fieldoffset = r->bank_fieldoffsets[ns];
6912     }
6913
6914     if (state == ARM_CP_STATE_AA32) {
6915         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
6916             /* If the register is banked then we don't need to migrate or
6917              * reset the 32-bit instance in certain cases:
6918              *
6919              * 1) If the register has both 32-bit and 64-bit instances then we
6920              *    can count on the 64-bit instance taking care of the
6921              *    non-secure bank.
6922              * 2) If ARMv8 is enabled then we can count on a 64-bit version
6923              *    taking care of the secure bank.  This requires that separate
6924              *    32 and 64-bit definitions are provided.
6925              */
6926             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
6927                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
6928                 r2->type |= ARM_CP_ALIAS;
6929             }
6930         } else if ((secstate != r->secure) && !ns) {
6931             /* The register is not banked so we only want to allow migration of
6932              * the non-secure instance.
6933              */
6934             r2->type |= ARM_CP_ALIAS;
6935         }
6936
6937         if (r->state == ARM_CP_STATE_BOTH) {
6938             /* We assume it is a cp15 register if the .cp field is left unset.
6939              */
6940             if (r2->cp == 0) {
6941                 r2->cp = 15;
6942             }
6943
6944 #ifdef HOST_WORDS_BIGENDIAN
6945             if (r2->fieldoffset) {
6946                 r2->fieldoffset += sizeof(uint32_t);
6947             }
6948 #endif
6949         }
6950     }
6951     if (state == ARM_CP_STATE_AA64) {
6952         /* To allow abbreviation of ARMCPRegInfo
6953          * definitions, we treat cp == 0 as equivalent to
6954          * the value for "standard guest-visible sysreg".
6955          * STATE_BOTH definitions are also always "standard
6956          * sysreg" in their AArch64 view (the .cp value may
6957          * be non-zero for the benefit of the AArch32 view).
6958          */
6959         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
6960             r2->cp = CP_REG_ARM64_SYSREG_CP;
6961         }
6962         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
6963                                   r2->opc0, opc1, opc2);
6964     } else {
6965         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
6966     }
6967     if (opaque) {
6968         r2->opaque = opaque;
6969     }
6970     /* reginfo passed to helpers is correct for the actual access,
6971      * and is never ARM_CP_STATE_BOTH:
6972      */
6973     r2->state = state;
6974     /* Make sure reginfo passed to helpers for wildcarded regs
6975      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
6976      */
6977     r2->crm = crm;
6978     r2->opc1 = opc1;
6979     r2->opc2 = opc2;
6980     /* By convention, for wildcarded registers only the first
6981      * entry is used for migration; the others are marked as
6982      * ALIAS so we don't try to transfer the register
6983      * multiple times. Special registers (ie NOP/WFI) are
6984      * never migratable and not even raw-accessible.
6985      */
6986     if ((r->type & ARM_CP_SPECIAL)) {
6987         r2->type |= ARM_CP_NO_RAW;
6988     }
6989     if (((r->crm == CP_ANY) && crm != 0) ||
6990         ((r->opc1 == CP_ANY) && opc1 != 0) ||
6991         ((r->opc2 == CP_ANY) && opc2 != 0)) {
6992         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
6993     }
6994
6995     /* Check that raw accesses are either forbidden or handled. Note that
6996      * we can't assert this earlier because the setup of fieldoffset for
6997      * banked registers has to be done first.
6998      */
6999     if (!(r2->type & ARM_CP_NO_RAW)) {
7000         assert(!raw_accessors_invalid(r2));
7001     }
7002
7003     /* Overriding of an existing definition must be explicitly
7004      * requested.
7005      */
7006     if (!(r->type & ARM_CP_OVERRIDE)) {
7007         ARMCPRegInfo *oldreg;
7008         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
7009         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
7010             fprintf(stderr, "Register redefined: cp=%d %d bit "
7011                     "crn=%d crm=%d opc1=%d opc2=%d, "
7012                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
7013                     r2->crn, r2->crm, r2->opc1, r2->opc2,
7014                     oldreg->name, r2->name);
7015             g_assert_not_reached();
7016         }
7017     }
7018     g_hash_table_insert(cpu->cp_regs, key, r2);
7019 }
7020
7021
7022 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
7023                                        const ARMCPRegInfo *r, void *opaque)
7024 {
7025     /* Define implementations of coprocessor registers.
7026      * We store these in a hashtable because typically
7027      * there are less than 150 registers in a space which
7028      * is 16*16*16*8*8 = 262144 in size.
7029      * Wildcarding is supported for the crm, opc1 and opc2 fields.
7030      * If a register is defined twice then the second definition is
7031      * used, so this can be used to define some generic registers and
7032      * then override them with implementation specific variations.
7033      * At least one of the original and the second definition should
7034      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
7035      * against accidental use.
7036      *
7037      * The state field defines whether the register is to be
7038      * visible in the AArch32 or AArch64 execution state. If the
7039      * state is set to ARM_CP_STATE_BOTH then we synthesise a
7040      * reginfo structure for the AArch32 view, which sees the lower
7041      * 32 bits of the 64 bit register.
7042      *
7043      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
7044      * be wildcarded. AArch64 registers are always considered to be 64
7045      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
7046      * the register, if any.
7047      */
7048     int crm, opc1, opc2, state;
7049     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
7050     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
7051     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
7052     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
7053     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
7054     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
7055     /* 64 bit registers have only CRm and Opc1 fields */
7056     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
7057     /* op0 only exists in the AArch64 encodings */
7058     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
7059     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
7060     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
7061     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
7062      * encodes a minimum access level for the register. We roll this
7063      * runtime check into our general permission check code, so check
7064      * here that the reginfo's specified permissions are strict enough
7065      * to encompass the generic architectural permission check.
7066      */
7067     if (r->state != ARM_CP_STATE_AA32) {
7068         int mask = 0;
7069         switch (r->opc1) {
7070         case 0:
7071             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
7072             mask = PL0U_R | PL1_RW;
7073             break;
7074         case 1: case 2:
7075             /* min_EL EL1 */
7076             mask = PL1_RW;
7077             break;
7078         case 3:
7079             /* min_EL EL0 */
7080             mask = PL0_RW;
7081             break;
7082         case 4:
7083             /* min_EL EL2 */
7084             mask = PL2_RW;
7085             break;
7086         case 5:
7087             /* unallocated encoding, so not possible */
7088             assert(false);
7089             break;
7090         case 6:
7091             /* min_EL EL3 */
7092             mask = PL3_RW;
7093             break;
7094         case 7:
7095             /* min_EL EL1, secure mode only (we don't check the latter) */
7096             mask = PL1_RW;
7097             break;
7098         default:
7099             /* broken reginfo with out-of-range opc1 */
7100             assert(false);
7101             break;
7102         }
7103         /* assert our permissions are not too lax (stricter is fine) */
7104         assert((r->access & ~mask) == 0);
7105     }
7106
7107     /* Check that the register definition has enough info to handle
7108      * reads and writes if they are permitted.
7109      */
7110     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
7111         if (r->access & PL3_R) {
7112             assert((r->fieldoffset ||
7113                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7114                    r->readfn);
7115         }
7116         if (r->access & PL3_W) {
7117             assert((r->fieldoffset ||
7118                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7119                    r->writefn);
7120         }
7121     }
7122     /* Bad type field probably means missing sentinel at end of reg list */
7123     assert(cptype_valid(r->type));
7124     for (crm = crmmin; crm <= crmmax; crm++) {
7125         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
7126             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
7127                 for (state = ARM_CP_STATE_AA32;
7128                      state <= ARM_CP_STATE_AA64; state++) {
7129                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
7130                         continue;
7131                     }
7132                     if (state == ARM_CP_STATE_AA32) {
7133                         /* Under AArch32 CP registers can be common
7134                          * (same for secure and non-secure world) or banked.
7135                          */
7136                         char *name;
7137
7138                         switch (r->secure) {
7139                         case ARM_CP_SECSTATE_S:
7140                         case ARM_CP_SECSTATE_NS:
7141                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7142                                                    r->secure, crm, opc1, opc2,
7143                                                    r->name);
7144                             break;
7145                         default:
7146                             name = g_strdup_printf("%s_S", r->name);
7147                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7148                                                    ARM_CP_SECSTATE_S,
7149                                                    crm, opc1, opc2, name);
7150                             g_free(name);
7151                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7152                                                    ARM_CP_SECSTATE_NS,
7153                                                    crm, opc1, opc2, r->name);
7154                             break;
7155                         }
7156                     } else {
7157                         /* AArch64 registers get mapped to non-secure instance
7158                          * of AArch32 */
7159                         add_cpreg_to_hashtable(cpu, r, opaque, state,
7160                                                ARM_CP_SECSTATE_NS,
7161                                                crm, opc1, opc2, r->name);
7162                     }
7163                 }
7164             }
7165         }
7166     }
7167 }
7168
7169 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
7170                                     const ARMCPRegInfo *regs, void *opaque)
7171 {
7172     /* Define a whole list of registers */
7173     const ARMCPRegInfo *r;
7174     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7175         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
7176     }
7177 }
7178
7179 /*
7180  * Modify ARMCPRegInfo for access from userspace.
7181  *
7182  * This is a data driven modification directed by
7183  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
7184  * user-space cannot alter any values and dynamic values pertaining to
7185  * execution state are hidden from user space view anyway.
7186  */
7187 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
7188 {
7189     const ARMCPRegUserSpaceInfo *m;
7190     ARMCPRegInfo *r;
7191
7192     for (m = mods; m->name; m++) {
7193         GPatternSpec *pat = NULL;
7194         if (m->is_glob) {
7195             pat = g_pattern_spec_new(m->name);
7196         }
7197         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7198             if (pat && g_pattern_match_string(pat, r->name)) {
7199                 r->type = ARM_CP_CONST;
7200                 r->access = PL0U_R;
7201                 r->resetvalue = 0;
7202                 /* continue */
7203             } else if (strcmp(r->name, m->name) == 0) {
7204                 r->type = ARM_CP_CONST;
7205                 r->access = PL0U_R;
7206                 r->resetvalue &= m->exported_bits;
7207                 r->resetvalue |= m->fixed_bits;
7208                 break;
7209             }
7210         }
7211         if (pat) {
7212             g_pattern_spec_free(pat);
7213         }
7214     }
7215 }
7216
7217 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
7218 {
7219     return g_hash_table_lookup(cpregs, &encoded_cp);
7220 }
7221
7222 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
7223                          uint64_t value)
7224 {
7225     /* Helper coprocessor write function for write-ignore registers */
7226 }
7227
7228 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
7229 {
7230     /* Helper coprocessor write function for read-as-zero registers */
7231     return 0;
7232 }
7233
7234 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
7235 {
7236     /* Helper coprocessor reset function for do-nothing-on-reset registers */
7237 }
7238
7239 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
7240 {
7241     /* Return true if it is not valid for us to switch to
7242      * this CPU mode (ie all the UNPREDICTABLE cases in
7243      * the ARM ARM CPSRWriteByInstr pseudocode).
7244      */
7245
7246     /* Changes to or from Hyp via MSR and CPS are illegal. */
7247     if (write_type == CPSRWriteByInstr &&
7248         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
7249          mode == ARM_CPU_MODE_HYP)) {
7250         return 1;
7251     }
7252
7253     switch (mode) {
7254     case ARM_CPU_MODE_USR:
7255         return 0;
7256     case ARM_CPU_MODE_SYS:
7257     case ARM_CPU_MODE_SVC:
7258     case ARM_CPU_MODE_ABT:
7259     case ARM_CPU_MODE_UND:
7260     case ARM_CPU_MODE_IRQ:
7261     case ARM_CPU_MODE_FIQ:
7262         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
7263          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
7264          */
7265         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
7266          * and CPS are treated as illegal mode changes.
7267          */
7268         if (write_type == CPSRWriteByInstr &&
7269             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
7270             (arm_hcr_el2_eff(env) & HCR_TGE)) {
7271             return 1;
7272         }
7273         return 0;
7274     case ARM_CPU_MODE_HYP:
7275         return !arm_feature(env, ARM_FEATURE_EL2)
7276             || arm_current_el(env) < 2 || arm_is_secure_below_el3(env);
7277     case ARM_CPU_MODE_MON:
7278         return arm_current_el(env) < 3;
7279     default:
7280         return 1;
7281     }
7282 }
7283
7284 uint32_t cpsr_read(CPUARMState *env)
7285 {
7286     int ZF;
7287     ZF = (env->ZF == 0);
7288     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
7289         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
7290         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
7291         | ((env->condexec_bits & 0xfc) << 8)
7292         | (env->GE << 16) | (env->daif & CPSR_AIF);
7293 }
7294
7295 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
7296                 CPSRWriteType write_type)
7297 {
7298     uint32_t changed_daif;
7299
7300     if (mask & CPSR_NZCV) {
7301         env->ZF = (~val) & CPSR_Z;
7302         env->NF = val;
7303         env->CF = (val >> 29) & 1;
7304         env->VF = (val << 3) & 0x80000000;
7305     }
7306     if (mask & CPSR_Q)
7307         env->QF = ((val & CPSR_Q) != 0);
7308     if (mask & CPSR_T)
7309         env->thumb = ((val & CPSR_T) != 0);
7310     if (mask & CPSR_IT_0_1) {
7311         env->condexec_bits &= ~3;
7312         env->condexec_bits |= (val >> 25) & 3;
7313     }
7314     if (mask & CPSR_IT_2_7) {
7315         env->condexec_bits &= 3;
7316         env->condexec_bits |= (val >> 8) & 0xfc;
7317     }
7318     if (mask & CPSR_GE) {
7319         env->GE = (val >> 16) & 0xf;
7320     }
7321
7322     /* In a V7 implementation that includes the security extensions but does
7323      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
7324      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
7325      * bits respectively.
7326      *
7327      * In a V8 implementation, it is permitted for privileged software to
7328      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
7329      */
7330     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
7331         arm_feature(env, ARM_FEATURE_EL3) &&
7332         !arm_feature(env, ARM_FEATURE_EL2) &&
7333         !arm_is_secure(env)) {
7334
7335         changed_daif = (env->daif ^ val) & mask;
7336
7337         if (changed_daif & CPSR_A) {
7338             /* Check to see if we are allowed to change the masking of async
7339              * abort exceptions from a non-secure state.
7340              */
7341             if (!(env->cp15.scr_el3 & SCR_AW)) {
7342                 qemu_log_mask(LOG_GUEST_ERROR,
7343                               "Ignoring attempt to switch CPSR_A flag from "
7344                               "non-secure world with SCR.AW bit clear\n");
7345                 mask &= ~CPSR_A;
7346             }
7347         }
7348
7349         if (changed_daif & CPSR_F) {
7350             /* Check to see if we are allowed to change the masking of FIQ
7351              * exceptions from a non-secure state.
7352              */
7353             if (!(env->cp15.scr_el3 & SCR_FW)) {
7354                 qemu_log_mask(LOG_GUEST_ERROR,
7355                               "Ignoring attempt to switch CPSR_F flag from "
7356                               "non-secure world with SCR.FW bit clear\n");
7357                 mask &= ~CPSR_F;
7358             }
7359
7360             /* Check whether non-maskable FIQ (NMFI) support is enabled.
7361              * If this bit is set software is not allowed to mask
7362              * FIQs, but is allowed to set CPSR_F to 0.
7363              */
7364             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
7365                 (val & CPSR_F)) {
7366                 qemu_log_mask(LOG_GUEST_ERROR,
7367                               "Ignoring attempt to enable CPSR_F flag "
7368                               "(non-maskable FIQ [NMFI] support enabled)\n");
7369                 mask &= ~CPSR_F;
7370             }
7371         }
7372     }
7373
7374     env->daif &= ~(CPSR_AIF & mask);
7375     env->daif |= val & CPSR_AIF & mask;
7376
7377     if (write_type != CPSRWriteRaw &&
7378         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
7379         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
7380             /* Note that we can only get here in USR mode if this is a
7381              * gdb stub write; for this case we follow the architectural
7382              * behaviour for guest writes in USR mode of ignoring an attempt
7383              * to switch mode. (Those are caught by translate.c for writes
7384              * triggered by guest instructions.)
7385              */
7386             mask &= ~CPSR_M;
7387         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
7388             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
7389              * v7, and has defined behaviour in v8:
7390              *  + leave CPSR.M untouched
7391              *  + allow changes to the other CPSR fields
7392              *  + set PSTATE.IL
7393              * For user changes via the GDB stub, we don't set PSTATE.IL,
7394              * as this would be unnecessarily harsh for a user error.
7395              */
7396             mask &= ~CPSR_M;
7397             if (write_type != CPSRWriteByGDBStub &&
7398                 arm_feature(env, ARM_FEATURE_V8)) {
7399                 mask |= CPSR_IL;
7400                 val |= CPSR_IL;
7401             }
7402             qemu_log_mask(LOG_GUEST_ERROR,
7403                           "Illegal AArch32 mode switch attempt from %s to %s\n",
7404                           aarch32_mode_name(env->uncached_cpsr),
7405                           aarch32_mode_name(val));
7406         } else {
7407             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
7408                           write_type == CPSRWriteExceptionReturn ?
7409                           "Exception return from AArch32" :
7410                           "AArch32 mode switch from",
7411                           aarch32_mode_name(env->uncached_cpsr),
7412                           aarch32_mode_name(val), env->regs[15]);
7413             switch_mode(env, val & CPSR_M);
7414         }
7415     }
7416     mask &= ~CACHED_CPSR_BITS;
7417     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
7418 }
7419
7420 /* Sign/zero extend */
7421 uint32_t HELPER(sxtb16)(uint32_t x)
7422 {
7423     uint32_t res;
7424     res = (uint16_t)(int8_t)x;
7425     res |= (uint32_t)(int8_t)(x >> 16) << 16;
7426     return res;
7427 }
7428
7429 uint32_t HELPER(uxtb16)(uint32_t x)
7430 {
7431     uint32_t res;
7432     res = (uint16_t)(uint8_t)x;
7433     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
7434     return res;
7435 }
7436
7437 int32_t HELPER(sdiv)(int32_t num, int32_t den)
7438 {
7439     if (den == 0)
7440       return 0;
7441     if (num == INT_MIN && den == -1)
7442       return INT_MIN;
7443     return num / den;
7444 }
7445
7446 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
7447 {
7448     if (den == 0)
7449       return 0;
7450     return num / den;
7451 }
7452
7453 uint32_t HELPER(rbit)(uint32_t x)
7454 {
7455     return revbit32(x);
7456 }
7457
7458 #ifdef CONFIG_USER_ONLY
7459
7460 /* These should probably raise undefined insn exceptions.  */
7461 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
7462 {
7463     ARMCPU *cpu = env_archcpu(env);
7464
7465     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
7466 }
7467
7468 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
7469 {
7470     ARMCPU *cpu = env_archcpu(env);
7471
7472     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
7473     return 0;
7474 }
7475
7476 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
7477 {
7478     /* translate.c should never generate calls here in user-only mode */
7479     g_assert_not_reached();
7480 }
7481
7482 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
7483 {
7484     /* translate.c should never generate calls here in user-only mode */
7485     g_assert_not_reached();
7486 }
7487
7488 void HELPER(v7m_preserve_fp_state)(CPUARMState *env)
7489 {
7490     /* translate.c should never generate calls here in user-only mode */
7491     g_assert_not_reached();
7492 }
7493
7494 void HELPER(v7m_vlstm)(CPUARMState *env, uint32_t fptr)
7495 {
7496     /* translate.c should never generate calls here in user-only mode */
7497     g_assert_not_reached();
7498 }
7499
7500 void HELPER(v7m_vlldm)(CPUARMState *env, uint32_t fptr)
7501 {
7502     /* translate.c should never generate calls here in user-only mode */
7503     g_assert_not_reached();
7504 }
7505
7506 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
7507 {
7508     /*
7509      * The TT instructions can be used by unprivileged code, but in
7510      * user-only emulation we don't have the MPU.
7511      * Luckily since we know we are NonSecure unprivileged (and that in
7512      * turn means that the A flag wasn't specified), all the bits in the
7513      * register must be zero:
7514      *  IREGION: 0 because IRVALID is 0
7515      *  IRVALID: 0 because NS
7516      *  S: 0 because NS
7517      *  NSRW: 0 because NS
7518      *  NSR: 0 because NS
7519      *  RW: 0 because unpriv and A flag not set
7520      *  R: 0 because unpriv and A flag not set
7521      *  SRVALID: 0 because NS
7522      *  MRVALID: 0 because unpriv and A flag not set
7523      *  SREGION: 0 becaus SRVALID is 0
7524      *  MREGION: 0 because MRVALID is 0
7525      */
7526     return 0;
7527 }
7528
7529 static void switch_mode(CPUARMState *env, int mode)
7530 {
7531     ARMCPU *cpu = env_archcpu(env);
7532
7533     if (mode != ARM_CPU_MODE_USR) {
7534         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
7535     }
7536 }
7537
7538 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7539                                  uint32_t cur_el, bool secure)
7540 {
7541     return 1;
7542 }
7543
7544 void aarch64_sync_64_to_32(CPUARMState *env)
7545 {
7546     g_assert_not_reached();
7547 }
7548
7549 #else
7550
7551 static void switch_mode(CPUARMState *env, int mode)
7552 {
7553     int old_mode;
7554     int i;
7555
7556     old_mode = env->uncached_cpsr & CPSR_M;
7557     if (mode == old_mode)
7558         return;
7559
7560     if (old_mode == ARM_CPU_MODE_FIQ) {
7561         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
7562         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
7563     } else if (mode == ARM_CPU_MODE_FIQ) {
7564         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
7565         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
7566     }
7567
7568     i = bank_number(old_mode);
7569     env->banked_r13[i] = env->regs[13];
7570     env->banked_spsr[i] = env->spsr;
7571
7572     i = bank_number(mode);
7573     env->regs[13] = env->banked_r13[i];
7574     env->spsr = env->banked_spsr[i];
7575
7576     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
7577     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
7578 }
7579
7580 /* Physical Interrupt Target EL Lookup Table
7581  *
7582  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
7583  *
7584  * The below multi-dimensional table is used for looking up the target
7585  * exception level given numerous condition criteria.  Specifically, the
7586  * target EL is based on SCR and HCR routing controls as well as the
7587  * currently executing EL and secure state.
7588  *
7589  *    Dimensions:
7590  *    target_el_table[2][2][2][2][2][4]
7591  *                    |  |  |  |  |  +--- Current EL
7592  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
7593  *                    |  |  |  +--------- HCR mask override
7594  *                    |  |  +------------ SCR exec state control
7595  *                    |  +--------------- SCR mask override
7596  *                    +------------------ 32-bit(0)/64-bit(1) EL3
7597  *
7598  *    The table values are as such:
7599  *    0-3 = EL0-EL3
7600  *     -1 = Cannot occur
7601  *
7602  * The ARM ARM target EL table includes entries indicating that an "exception
7603  * is not taken".  The two cases where this is applicable are:
7604  *    1) An exception is taken from EL3 but the SCR does not have the exception
7605  *    routed to EL3.
7606  *    2) An exception is taken from EL2 but the HCR does not have the exception
7607  *    routed to EL2.
7608  * In these two cases, the below table contain a target of EL1.  This value is
7609  * returned as it is expected that the consumer of the table data will check
7610  * for "target EL >= current EL" to ensure the exception is not taken.
7611  *
7612  *            SCR     HCR
7613  *         64  EA     AMO                 From
7614  *        BIT IRQ     IMO      Non-secure         Secure
7615  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
7616  */
7617 static const int8_t target_el_table[2][2][2][2][2][4] = {
7618     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7619        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
7620       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7621        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
7622      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7623        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
7624       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7625        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
7626     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
7627        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
7628       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
7629        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
7630      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7631        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
7632       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7633        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
7634 };
7635
7636 /*
7637  * Determine the target EL for physical exceptions
7638  */
7639 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7640                                  uint32_t cur_el, bool secure)
7641 {
7642     CPUARMState *env = cs->env_ptr;
7643     bool rw;
7644     bool scr;
7645     bool hcr;
7646     int target_el;
7647     /* Is the highest EL AArch64? */
7648     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
7649     uint64_t hcr_el2;
7650
7651     if (arm_feature(env, ARM_FEATURE_EL3)) {
7652         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
7653     } else {
7654         /* Either EL2 is the highest EL (and so the EL2 register width
7655          * is given by is64); or there is no EL2 or EL3, in which case
7656          * the value of 'rw' does not affect the table lookup anyway.
7657          */
7658         rw = is64;
7659     }
7660
7661     hcr_el2 = arm_hcr_el2_eff(env);
7662     switch (excp_idx) {
7663     case EXCP_IRQ:
7664         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
7665         hcr = hcr_el2 & HCR_IMO;
7666         break;
7667     case EXCP_FIQ:
7668         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
7669         hcr = hcr_el2 & HCR_FMO;
7670         break;
7671     default:
7672         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
7673         hcr = hcr_el2 & HCR_AMO;
7674         break;
7675     };
7676
7677     /* Perform a table-lookup for the target EL given the current state */
7678     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
7679
7680     assert(target_el > 0);
7681
7682     return target_el;
7683 }
7684
7685 void arm_log_exception(int idx)
7686 {
7687     if (qemu_loglevel_mask(CPU_LOG_INT)) {
7688         const char *exc = NULL;
7689         static const char * const excnames[] = {
7690             [EXCP_UDEF] = "Undefined Instruction",
7691             [EXCP_SWI] = "SVC",
7692             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
7693             [EXCP_DATA_ABORT] = "Data Abort",
7694             [EXCP_IRQ] = "IRQ",
7695             [EXCP_FIQ] = "FIQ",
7696             [EXCP_BKPT] = "Breakpoint",
7697             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
7698             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
7699             [EXCP_HVC] = "Hypervisor Call",
7700             [EXCP_HYP_TRAP] = "Hypervisor Trap",
7701             [EXCP_SMC] = "Secure Monitor Call",
7702             [EXCP_VIRQ] = "Virtual IRQ",
7703             [EXCP_VFIQ] = "Virtual FIQ",
7704             [EXCP_SEMIHOST] = "Semihosting call",
7705             [EXCP_NOCP] = "v7M NOCP UsageFault",
7706             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
7707             [EXCP_STKOF] = "v8M STKOF UsageFault",
7708             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
7709             [EXCP_LSERR] = "v8M LSERR UsageFault",
7710             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
7711         };
7712
7713         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
7714             exc = excnames[idx];
7715         }
7716         if (!exc) {
7717             exc = "unknown";
7718         }
7719         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
7720     }
7721 }
7722
7723 /*
7724  * What kind of stack write are we doing? This affects how exceptions
7725  * generated during the stacking are treated.
7726  */
7727 typedef enum StackingMode {
7728     STACK_NORMAL,
7729     STACK_IGNFAULTS,
7730     STACK_LAZYFP,
7731 } StackingMode;
7732
7733 static bool v7m_stack_write(ARMCPU *cpu, uint32_t addr, uint32_t value,
7734                             ARMMMUIdx mmu_idx, StackingMode mode)
7735 {
7736     CPUState *cs = CPU(cpu);
7737     CPUARMState *env = &cpu->env;
7738     MemTxAttrs attrs = {};
7739     MemTxResult txres;
7740     target_ulong page_size;
7741     hwaddr physaddr;
7742     int prot;
7743     ARMMMUFaultInfo fi = {};
7744     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
7745     int exc;
7746     bool exc_secure;
7747
7748     if (get_phys_addr(env, addr, MMU_DATA_STORE, mmu_idx, &physaddr,
7749                       &attrs, &prot, &page_size, &fi, NULL)) {
7750         /* MPU/SAU lookup failed */
7751         if (fi.type == ARMFault_QEMU_SFault) {
7752             if (mode == STACK_LAZYFP) {
7753                 qemu_log_mask(CPU_LOG_INT,
7754                               "...SecureFault with SFSR.LSPERR "
7755                               "during lazy stacking\n");
7756                 env->v7m.sfsr |= R_V7M_SFSR_LSPERR_MASK;
7757             } else {
7758                 qemu_log_mask(CPU_LOG_INT,
7759                               "...SecureFault with SFSR.AUVIOL "
7760                               "during stacking\n");
7761                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
7762             }
7763             env->v7m.sfsr |= R_V7M_SFSR_SFARVALID_MASK;
7764             env->v7m.sfar = addr;
7765             exc = ARMV7M_EXCP_SECURE;
7766             exc_secure = false;
7767         } else {
7768             if (mode == STACK_LAZYFP) {
7769                 qemu_log_mask(CPU_LOG_INT,
7770                               "...MemManageFault with CFSR.MLSPERR\n");
7771                 env->v7m.cfsr[secure] |= R_V7M_CFSR_MLSPERR_MASK;
7772             } else {
7773                 qemu_log_mask(CPU_LOG_INT,
7774                               "...MemManageFault with CFSR.MSTKERR\n");
7775                 env->v7m.cfsr[secure] |= R_V7M_CFSR_MSTKERR_MASK;
7776             }
7777             exc = ARMV7M_EXCP_MEM;
7778             exc_secure = secure;
7779         }
7780         goto pend_fault;
7781     }
7782     address_space_stl_le(arm_addressspace(cs, attrs), physaddr, value,
7783                          attrs, &txres);
7784     if (txres != MEMTX_OK) {
7785         /* BusFault trying to write the data */
7786         if (mode == STACK_LAZYFP) {
7787             qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.LSPERR\n");
7788             env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_LSPERR_MASK;
7789         } else {
7790             qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.STKERR\n");
7791             env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_STKERR_MASK;
7792         }
7793         exc = ARMV7M_EXCP_BUS;
7794         exc_secure = false;
7795         goto pend_fault;
7796     }
7797     return true;
7798
7799 pend_fault:
7800     /*
7801      * By pending the exception at this point we are making
7802      * the IMPDEF choice "overridden exceptions pended" (see the
7803      * MergeExcInfo() pseudocode). The other choice would be to not
7804      * pend them now and then make a choice about which to throw away
7805      * later if we have two derived exceptions.
7806      * The only case when we must not pend the exception but instead
7807      * throw it away is if we are doing the push of the callee registers
7808      * and we've already generated a derived exception (this is indicated
7809      * by the caller passing STACK_IGNFAULTS). Even in this case we will
7810      * still update the fault status registers.
7811      */
7812     switch (mode) {
7813     case STACK_NORMAL:
7814         armv7m_nvic_set_pending_derived(env->nvic, exc, exc_secure);
7815         break;
7816     case STACK_LAZYFP:
7817         armv7m_nvic_set_pending_lazyfp(env->nvic, exc, exc_secure);
7818         break;
7819     case STACK_IGNFAULTS:
7820         break;
7821     }
7822     return false;
7823 }
7824
7825 static bool v7m_stack_read(ARMCPU *cpu, uint32_t *dest, uint32_t addr,
7826                            ARMMMUIdx mmu_idx)
7827 {
7828     CPUState *cs = CPU(cpu);
7829     CPUARMState *env = &cpu->env;
7830     MemTxAttrs attrs = {};
7831     MemTxResult txres;
7832     target_ulong page_size;
7833     hwaddr physaddr;
7834     int prot;
7835     ARMMMUFaultInfo fi = {};
7836     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
7837     int exc;
7838     bool exc_secure;
7839     uint32_t value;
7840
7841     if (get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &physaddr,
7842                       &attrs, &prot, &page_size, &fi, NULL)) {
7843         /* MPU/SAU lookup failed */
7844         if (fi.type == ARMFault_QEMU_SFault) {
7845             qemu_log_mask(CPU_LOG_INT,
7846                           "...SecureFault with SFSR.AUVIOL during unstack\n");
7847             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
7848             env->v7m.sfar = addr;
7849             exc = ARMV7M_EXCP_SECURE;
7850             exc_secure = false;
7851         } else {
7852             qemu_log_mask(CPU_LOG_INT,
7853                           "...MemManageFault with CFSR.MUNSTKERR\n");
7854             env->v7m.cfsr[secure] |= R_V7M_CFSR_MUNSTKERR_MASK;
7855             exc = ARMV7M_EXCP_MEM;
7856             exc_secure = secure;
7857         }
7858         goto pend_fault;
7859     }
7860
7861     value = address_space_ldl(arm_addressspace(cs, attrs), physaddr,
7862                               attrs, &txres);
7863     if (txres != MEMTX_OK) {
7864         /* BusFault trying to read the data */
7865         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.UNSTKERR\n");
7866         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_UNSTKERR_MASK;
7867         exc = ARMV7M_EXCP_BUS;
7868         exc_secure = false;
7869         goto pend_fault;
7870     }
7871
7872     *dest = value;
7873     return true;
7874
7875 pend_fault:
7876     /*
7877      * By pending the exception at this point we are making
7878      * the IMPDEF choice "overridden exceptions pended" (see the
7879      * MergeExcInfo() pseudocode). The other choice would be to not
7880      * pend them now and then make a choice about which to throw away
7881      * later if we have two derived exceptions.
7882      */
7883     armv7m_nvic_set_pending(env->nvic, exc, exc_secure);
7884     return false;
7885 }
7886
7887 void HELPER(v7m_preserve_fp_state)(CPUARMState *env)
7888 {
7889     /*
7890      * Preserve FP state (because LSPACT was set and we are about
7891      * to execute an FP instruction). This corresponds to the
7892      * PreserveFPState() pseudocode.
7893      * We may throw an exception if the stacking fails.
7894      */
7895     ARMCPU *cpu = env_archcpu(env);
7896     bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
7897     bool negpri = !(env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_HFRDY_MASK);
7898     bool is_priv = !(env->v7m.fpccr[is_secure] & R_V7M_FPCCR_USER_MASK);
7899     bool splimviol = env->v7m.fpccr[is_secure] & R_V7M_FPCCR_SPLIMVIOL_MASK;
7900     uint32_t fpcar = env->v7m.fpcar[is_secure];
7901     bool stacked_ok = true;
7902     bool ts = is_secure && (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK);
7903     bool take_exception;
7904
7905     /* Take the iothread lock as we are going to touch the NVIC */
7906     qemu_mutex_lock_iothread();
7907
7908     /* Check the background context had access to the FPU */
7909     if (!v7m_cpacr_pass(env, is_secure, is_priv)) {
7910         armv7m_nvic_set_pending_lazyfp(env->nvic, ARMV7M_EXCP_USAGE, is_secure);
7911         env->v7m.cfsr[is_secure] |= R_V7M_CFSR_NOCP_MASK;
7912         stacked_ok = false;
7913     } else if (!is_secure && !extract32(env->v7m.nsacr, 10, 1)) {
7914         armv7m_nvic_set_pending_lazyfp(env->nvic, ARMV7M_EXCP_USAGE, M_REG_S);
7915         env->v7m.cfsr[M_REG_S] |= R_V7M_CFSR_NOCP_MASK;
7916         stacked_ok = false;
7917     }
7918
7919     if (!splimviol && stacked_ok) {
7920         /* We only stack if the stack limit wasn't violated */
7921         int i;
7922         ARMMMUIdx mmu_idx;
7923
7924         mmu_idx = arm_v7m_mmu_idx_all(env, is_secure, is_priv, negpri);
7925         for (i = 0; i < (ts ? 32 : 16); i += 2) {
7926             uint64_t dn = *aa32_vfp_dreg(env, i / 2);
7927             uint32_t faddr = fpcar + 4 * i;
7928             uint32_t slo = extract64(dn, 0, 32);
7929             uint32_t shi = extract64(dn, 32, 32);
7930
7931             if (i >= 16) {
7932                 faddr += 8; /* skip the slot for the FPSCR */
7933             }
7934             stacked_ok = stacked_ok &&
7935                 v7m_stack_write(cpu, faddr, slo, mmu_idx, STACK_LAZYFP) &&
7936                 v7m_stack_write(cpu, faddr + 4, shi, mmu_idx, STACK_LAZYFP);
7937         }
7938
7939         stacked_ok = stacked_ok &&
7940             v7m_stack_write(cpu, fpcar + 0x40,
7941                             vfp_get_fpscr(env), mmu_idx, STACK_LAZYFP);
7942     }
7943
7944     /*
7945      * We definitely pended an exception, but it's possible that it
7946      * might not be able to be taken now. If its priority permits us
7947      * to take it now, then we must not update the LSPACT or FP regs,
7948      * but instead jump out to take the exception immediately.
7949      * If it's just pending and won't be taken until the current
7950      * handler exits, then we do update LSPACT and the FP regs.
7951      */
7952     take_exception = !stacked_ok &&
7953         armv7m_nvic_can_take_pending_exception(env->nvic);
7954
7955     qemu_mutex_unlock_iothread();
7956
7957     if (take_exception) {
7958         raise_exception_ra(env, EXCP_LAZYFP, 0, 1, GETPC());
7959     }
7960
7961     env->v7m.fpccr[is_secure] &= ~R_V7M_FPCCR_LSPACT_MASK;
7962
7963     if (ts) {
7964         /* Clear s0 to s31 and the FPSCR */
7965         int i;
7966
7967         for (i = 0; i < 32; i += 2) {
7968             *aa32_vfp_dreg(env, i / 2) = 0;
7969         }
7970         vfp_set_fpscr(env, 0);
7971     }
7972     /*
7973      * Otherwise s0 to s15 and FPSCR are UNKNOWN; we choose to leave them
7974      * unchanged.
7975      */
7976 }
7977
7978 /*
7979  * Write to v7M CONTROL.SPSEL bit for the specified security bank.
7980  * This may change the current stack pointer between Main and Process
7981  * stack pointers if it is done for the CONTROL register for the current
7982  * security state.
7983  */
7984 static void write_v7m_control_spsel_for_secstate(CPUARMState *env,
7985                                                  bool new_spsel,
7986                                                  bool secstate)
7987 {
7988     bool old_is_psp = v7m_using_psp(env);
7989
7990     env->v7m.control[secstate] =
7991         deposit32(env->v7m.control[secstate],
7992                   R_V7M_CONTROL_SPSEL_SHIFT,
7993                   R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);
7994
7995     if (secstate == env->v7m.secure) {
7996         bool new_is_psp = v7m_using_psp(env);
7997         uint32_t tmp;
7998
7999         if (old_is_psp != new_is_psp) {
8000             tmp = env->v7m.other_sp;
8001             env->v7m.other_sp = env->regs[13];
8002             env->regs[13] = tmp;
8003         }
8004     }
8005 }
8006
8007 /*
8008  * Write to v7M CONTROL.SPSEL bit. This may change the current
8009  * stack pointer between Main and Process stack pointers.
8010  */
8011 static void write_v7m_control_spsel(CPUARMState *env, bool new_spsel)
8012 {
8013     write_v7m_control_spsel_for_secstate(env, new_spsel, env->v7m.secure);
8014 }
8015
8016 void write_v7m_exception(CPUARMState *env, uint32_t new_exc)
8017 {
8018     /*
8019      * Write a new value to v7m.exception, thus transitioning into or out
8020      * of Handler mode; this may result in a change of active stack pointer.
8021      */
8022     bool new_is_psp, old_is_psp = v7m_using_psp(env);
8023     uint32_t tmp;
8024
8025     env->v7m.exception = new_exc;
8026
8027     new_is_psp = v7m_using_psp(env);
8028
8029     if (old_is_psp != new_is_psp) {
8030         tmp = env->v7m.other_sp;
8031         env->v7m.other_sp = env->regs[13];
8032         env->regs[13] = tmp;
8033     }
8034 }
8035
8036 /* Switch M profile security state between NS and S */
8037 static void switch_v7m_security_state(CPUARMState *env, bool new_secstate)
8038 {
8039     uint32_t new_ss_msp, new_ss_psp;
8040
8041     if (env->v7m.secure == new_secstate) {
8042         return;
8043     }
8044
8045     /*
8046      * All the banked state is accessed by looking at env->v7m.secure
8047      * except for the stack pointer; rearrange the SP appropriately.
8048      */
8049     new_ss_msp = env->v7m.other_ss_msp;
8050     new_ss_psp = env->v7m.other_ss_psp;
8051
8052     if (v7m_using_psp(env)) {
8053         env->v7m.other_ss_psp = env->regs[13];
8054         env->v7m.other_ss_msp = env->v7m.other_sp;
8055     } else {
8056         env->v7m.other_ss_msp = env->regs[13];
8057         env->v7m.other_ss_psp = env->v7m.other_sp;
8058     }
8059
8060     env->v7m.secure = new_secstate;
8061
8062     if (v7m_using_psp(env)) {
8063         env->regs[13] = new_ss_psp;
8064         env->v7m.other_sp = new_ss_msp;
8065     } else {
8066         env->regs[13] = new_ss_msp;
8067         env->v7m.other_sp = new_ss_psp;
8068     }
8069 }
8070
8071 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
8072 {
8073     /*
8074      * Handle v7M BXNS:
8075      *  - if the return value is a magic value, do exception return (like BX)
8076      *  - otherwise bit 0 of the return value is the target security state
8077      */
8078     uint32_t min_magic;
8079
8080     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8081         /* Covers FNC_RETURN and EXC_RETURN magic */
8082         min_magic = FNC_RETURN_MIN_MAGIC;
8083     } else {
8084         /* EXC_RETURN magic only */
8085         min_magic = EXC_RETURN_MIN_MAGIC;
8086     }
8087
8088     if (dest >= min_magic) {
8089         /*
8090          * This is an exception return magic value; put it where
8091          * do_v7m_exception_exit() expects and raise EXCEPTION_EXIT.
8092          * Note that if we ever add gen_ss_advance() singlestep support to
8093          * M profile this should count as an "instruction execution complete"
8094          * event (compare gen_bx_excret_final_code()).
8095          */
8096         env->regs[15] = dest & ~1;
8097         env->thumb = dest & 1;
8098         HELPER(exception_internal)(env, EXCP_EXCEPTION_EXIT);
8099         /* notreached */
8100     }
8101
8102     /* translate.c should have made BXNS UNDEF unless we're secure */
8103     assert(env->v7m.secure);
8104
8105     if (!(dest & 1)) {
8106         env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
8107     }
8108     switch_v7m_security_state(env, dest & 1);
8109     env->thumb = 1;
8110     env->regs[15] = dest & ~1;
8111 }
8112
8113 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
8114 {
8115     /*
8116      * Handle v7M BLXNS:
8117      *  - bit 0 of the destination address is the target security state
8118      */
8119
8120     /* At this point regs[15] is the address just after the BLXNS */
8121     uint32_t nextinst = env->regs[15] | 1;
8122     uint32_t sp = env->regs[13] - 8;
8123     uint32_t saved_psr;
8124
8125     /* translate.c will have made BLXNS UNDEF unless we're secure */
8126     assert(env->v7m.secure);
8127
8128     if (dest & 1) {
8129         /*
8130          * Target is Secure, so this is just a normal BLX,
8131          * except that the low bit doesn't indicate Thumb/not.
8132          */
8133         env->regs[14] = nextinst;
8134         env->thumb = 1;
8135         env->regs[15] = dest & ~1;
8136         return;
8137     }
8138
8139     /* Target is non-secure: first push a stack frame */
8140     if (!QEMU_IS_ALIGNED(sp, 8)) {
8141         qemu_log_mask(LOG_GUEST_ERROR,
8142                       "BLXNS with misaligned SP is UNPREDICTABLE\n");
8143     }
8144
8145     if (sp < v7m_sp_limit(env)) {
8146         raise_exception(env, EXCP_STKOF, 0, 1);
8147     }
8148
8149     saved_psr = env->v7m.exception;
8150     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK) {
8151         saved_psr |= XPSR_SFPA;
8152     }
8153
8154     /* Note that these stores can throw exceptions on MPU faults */
8155     cpu_stl_data(env, sp, nextinst);
8156     cpu_stl_data(env, sp + 4, saved_psr);
8157
8158     env->regs[13] = sp;
8159     env->regs[14] = 0xfeffffff;
8160     if (arm_v7m_is_handler_mode(env)) {
8161         /*
8162          * Write a dummy value to IPSR, to avoid leaking the current secure
8163          * exception number to non-secure code. This is guaranteed not
8164          * to cause write_v7m_exception() to actually change stacks.
8165          */
8166         write_v7m_exception(env, 1);
8167     }
8168     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
8169     switch_v7m_security_state(env, 0);
8170     env->thumb = 1;
8171     env->regs[15] = dest;
8172 }
8173
8174 static uint32_t *get_v7m_sp_ptr(CPUARMState *env, bool secure, bool threadmode,
8175                                 bool spsel)
8176 {
8177     /*
8178      * Return a pointer to the location where we currently store the
8179      * stack pointer for the requested security state and thread mode.
8180      * This pointer will become invalid if the CPU state is updated
8181      * such that the stack pointers are switched around (eg changing
8182      * the SPSEL control bit).
8183      * Compare the v8M ARM ARM pseudocode LookUpSP_with_security_mode().
8184      * Unlike that pseudocode, we require the caller to pass us in the
8185      * SPSEL control bit value; this is because we also use this
8186      * function in handling of pushing of the callee-saves registers
8187      * part of the v8M stack frame (pseudocode PushCalleeStack()),
8188      * and in the tailchain codepath the SPSEL bit comes from the exception
8189      * return magic LR value from the previous exception. The pseudocode
8190      * opencodes the stack-selection in PushCalleeStack(), but we prefer
8191      * to make this utility function generic enough to do the job.
8192      */
8193     bool want_psp = threadmode && spsel;
8194
8195     if (secure == env->v7m.secure) {
8196         if (want_psp == v7m_using_psp(env)) {
8197             return &env->regs[13];
8198         } else {
8199             return &env->v7m.other_sp;
8200         }
8201     } else {
8202         if (want_psp) {
8203             return &env->v7m.other_ss_psp;
8204         } else {
8205             return &env->v7m.other_ss_msp;
8206         }
8207     }
8208 }
8209
8210 static bool arm_v7m_load_vector(ARMCPU *cpu, int exc, bool targets_secure,
8211                                 uint32_t *pvec)
8212 {
8213     CPUState *cs = CPU(cpu);
8214     CPUARMState *env = &cpu->env;
8215     MemTxResult result;
8216     uint32_t addr = env->v7m.vecbase[targets_secure] + exc * 4;
8217     uint32_t vector_entry;
8218     MemTxAttrs attrs = {};
8219     ARMMMUIdx mmu_idx;
8220     bool exc_secure;
8221
8222     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targets_secure, true);
8223
8224     /*
8225      * We don't do a get_phys_addr() here because the rules for vector
8226      * loads are special: they always use the default memory map, and
8227      * the default memory map permits reads from all addresses.
8228      * Since there's no easy way to pass through to pmsav8_mpu_lookup()
8229      * that we want this special case which would always say "yes",
8230      * we just do the SAU lookup here followed by a direct physical load.
8231      */
8232     attrs.secure = targets_secure;
8233     attrs.user = false;
8234
8235     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8236         V8M_SAttributes sattrs = {};
8237
8238         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
8239         if (sattrs.ns) {
8240             attrs.secure = false;
8241         } else if (!targets_secure) {
8242             /* NS access to S memory */
8243             goto load_fail;
8244         }
8245     }
8246
8247     vector_entry = address_space_ldl(arm_addressspace(cs, attrs), addr,
8248                                      attrs, &result);
8249     if (result != MEMTX_OK) {
8250         goto load_fail;
8251     }
8252     *pvec = vector_entry;
8253     return true;
8254
8255 load_fail:
8256     /*
8257      * All vector table fetch fails are reported as HardFault, with
8258      * HFSR.VECTTBL and .FORCED set. (FORCED is set because
8259      * technically the underlying exception is a MemManage or BusFault
8260      * that is escalated to HardFault.) This is a terminal exception,
8261      * so we will either take the HardFault immediately or else enter
8262      * lockup (the latter case is handled in armv7m_nvic_set_pending_derived()).
8263      */
8264     exc_secure = targets_secure ||
8265         !(cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK);
8266     env->v7m.hfsr |= R_V7M_HFSR_VECTTBL_MASK | R_V7M_HFSR_FORCED_MASK;
8267     armv7m_nvic_set_pending_derived(env->nvic, ARMV7M_EXCP_HARD, exc_secure);
8268     return false;
8269 }
8270
8271 static uint32_t v7m_integrity_sig(CPUARMState *env, uint32_t lr)
8272 {
8273     /*
8274      * Return the integrity signature value for the callee-saves
8275      * stack frame section. @lr is the exception return payload/LR value
8276      * whose FType bit forms bit 0 of the signature if FP is present.
8277      */
8278     uint32_t sig = 0xfefa125a;
8279
8280     if (!arm_feature(env, ARM_FEATURE_VFP) || (lr & R_V7M_EXCRET_FTYPE_MASK)) {
8281         sig |= 1;
8282     }
8283     return sig;
8284 }
8285
8286 static bool v7m_push_callee_stack(ARMCPU *cpu, uint32_t lr, bool dotailchain,
8287                                   bool ignore_faults)
8288 {
8289     /*
8290      * For v8M, push the callee-saves register part of the stack frame.
8291      * Compare the v8M pseudocode PushCalleeStack().
8292      * In the tailchaining case this may not be the current stack.
8293      */
8294     CPUARMState *env = &cpu->env;
8295     uint32_t *frame_sp_p;
8296     uint32_t frameptr;
8297     ARMMMUIdx mmu_idx;
8298     bool stacked_ok;
8299     uint32_t limit;
8300     bool want_psp;
8301     uint32_t sig;
8302     StackingMode smode = ignore_faults ? STACK_IGNFAULTS : STACK_NORMAL;
8303
8304     if (dotailchain) {
8305         bool mode = lr & R_V7M_EXCRET_MODE_MASK;
8306         bool priv = !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_NPRIV_MASK) ||
8307             !mode;
8308
8309         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, M_REG_S, priv);
8310         frame_sp_p = get_v7m_sp_ptr(env, M_REG_S, mode,
8311                                     lr & R_V7M_EXCRET_SPSEL_MASK);
8312         want_psp = mode && (lr & R_V7M_EXCRET_SPSEL_MASK);
8313         if (want_psp) {
8314             limit = env->v7m.psplim[M_REG_S];
8315         } else {
8316             limit = env->v7m.msplim[M_REG_S];
8317         }
8318     } else {
8319         mmu_idx = arm_mmu_idx(env);
8320         frame_sp_p = &env->regs[13];
8321         limit = v7m_sp_limit(env);
8322     }
8323
8324     frameptr = *frame_sp_p - 0x28;
8325     if (frameptr < limit) {
8326         /*
8327          * Stack limit failure: set SP to the limit value, and generate
8328          * STKOF UsageFault. Stack pushes below the limit must not be
8329          * performed. It is IMPDEF whether pushes above the limit are
8330          * performed; we choose not to.
8331          */
8332         qemu_log_mask(CPU_LOG_INT,
8333                       "...STKOF during callee-saves register stacking\n");
8334         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
8335         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
8336                                 env->v7m.secure);
8337         *frame_sp_p = limit;
8338         return true;
8339     }
8340
8341     /*
8342      * Write as much of the stack frame as we can. A write failure may
8343      * cause us to pend a derived exception.
8344      */
8345     sig = v7m_integrity_sig(env, lr);
8346     stacked_ok =
8347         v7m_stack_write(cpu, frameptr, sig, mmu_idx, smode) &&
8348         v7m_stack_write(cpu, frameptr + 0x8, env->regs[4], mmu_idx, smode) &&
8349         v7m_stack_write(cpu, frameptr + 0xc, env->regs[5], mmu_idx, smode) &&
8350         v7m_stack_write(cpu, frameptr + 0x10, env->regs[6], mmu_idx, smode) &&
8351         v7m_stack_write(cpu, frameptr + 0x14, env->regs[7], mmu_idx, smode) &&
8352         v7m_stack_write(cpu, frameptr + 0x18, env->regs[8], mmu_idx, smode) &&
8353         v7m_stack_write(cpu, frameptr + 0x1c, env->regs[9], mmu_idx, smode) &&
8354         v7m_stack_write(cpu, frameptr + 0x20, env->regs[10], mmu_idx, smode) &&
8355         v7m_stack_write(cpu, frameptr + 0x24, env->regs[11], mmu_idx, smode);
8356
8357     /* Update SP regardless of whether any of the stack accesses failed. */
8358     *frame_sp_p = frameptr;
8359
8360     return !stacked_ok;
8361 }
8362
8363 static void v7m_exception_taken(ARMCPU *cpu, uint32_t lr, bool dotailchain,
8364                                 bool ignore_stackfaults)
8365 {
8366     /*
8367      * Do the "take the exception" parts of exception entry,
8368      * but not the pushing of state to the stack. This is
8369      * similar to the pseudocode ExceptionTaken() function.
8370      */
8371     CPUARMState *env = &cpu->env;
8372     uint32_t addr;
8373     bool targets_secure;
8374     int exc;
8375     bool push_failed = false;
8376
8377     armv7m_nvic_get_pending_irq_info(env->nvic, &exc, &targets_secure);
8378     qemu_log_mask(CPU_LOG_INT, "...taking pending %s exception %d\n",
8379                   targets_secure ? "secure" : "nonsecure", exc);
8380
8381     if (dotailchain) {
8382         /* Sanitize LR FType and PREFIX bits */
8383         if (!arm_feature(env, ARM_FEATURE_VFP)) {
8384             lr |= R_V7M_EXCRET_FTYPE_MASK;
8385         }
8386         lr = deposit32(lr, 24, 8, 0xff);
8387     }
8388
8389     if (arm_feature(env, ARM_FEATURE_V8)) {
8390         if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
8391             (lr & R_V7M_EXCRET_S_MASK)) {
8392             /*
8393              * The background code (the owner of the registers in the
8394              * exception frame) is Secure. This means it may either already
8395              * have or now needs to push callee-saves registers.
8396              */
8397             if (targets_secure) {
8398                 if (dotailchain && !(lr & R_V7M_EXCRET_ES_MASK)) {
8399                     /*
8400                      * We took an exception from Secure to NonSecure
8401                      * (which means the callee-saved registers got stacked)
8402                      * and are now tailchaining to a Secure exception.
8403                      * Clear DCRS so eventual return from this Secure
8404                      * exception unstacks the callee-saved registers.
8405                      */
8406                     lr &= ~R_V7M_EXCRET_DCRS_MASK;
8407                 }
8408             } else {
8409                 /*
8410                  * We're going to a non-secure exception; push the
8411                  * callee-saves registers to the stack now, if they're
8412                  * not already saved.
8413                  */
8414                 if (lr & R_V7M_EXCRET_DCRS_MASK &&
8415                     !(dotailchain && !(lr & R_V7M_EXCRET_ES_MASK))) {
8416                     push_failed = v7m_push_callee_stack(cpu, lr, dotailchain,
8417                                                         ignore_stackfaults);
8418                 }
8419                 lr |= R_V7M_EXCRET_DCRS_MASK;
8420             }
8421         }
8422
8423         lr &= ~R_V7M_EXCRET_ES_MASK;
8424         if (targets_secure || !arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8425             lr |= R_V7M_EXCRET_ES_MASK;
8426         }
8427         lr &= ~R_V7M_EXCRET_SPSEL_MASK;
8428         if (env->v7m.control[targets_secure] & R_V7M_CONTROL_SPSEL_MASK) {
8429             lr |= R_V7M_EXCRET_SPSEL_MASK;
8430         }
8431
8432         /*
8433          * Clear registers if necessary to prevent non-secure exception
8434          * code being able to see register values from secure code.
8435          * Where register values become architecturally UNKNOWN we leave
8436          * them with their previous values.
8437          */
8438         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8439             if (!targets_secure) {
8440                 /*
8441                  * Always clear the caller-saved registers (they have been
8442                  * pushed to the stack earlier in v7m_push_stack()).
8443                  * Clear callee-saved registers if the background code is
8444                  * Secure (in which case these regs were saved in
8445                  * v7m_push_callee_stack()).
8446                  */
8447                 int i;
8448
8449                 for (i = 0; i < 13; i++) {
8450                     /* r4..r11 are callee-saves, zero only if EXCRET.S == 1 */
8451                     if (i < 4 || i > 11 || (lr & R_V7M_EXCRET_S_MASK)) {
8452                         env->regs[i] = 0;
8453                     }
8454                 }
8455                 /* Clear EAPSR */
8456                 xpsr_write(env, 0, XPSR_NZCV | XPSR_Q | XPSR_GE | XPSR_IT);
8457             }
8458         }
8459     }
8460
8461     if (push_failed && !ignore_stackfaults) {
8462         /*
8463          * Derived exception on callee-saves register stacking:
8464          * we might now want to take a different exception which
8465          * targets a different security state, so try again from the top.
8466          */
8467         qemu_log_mask(CPU_LOG_INT,
8468                       "...derived exception on callee-saves register stacking");
8469         v7m_exception_taken(cpu, lr, true, true);
8470         return;
8471     }
8472
8473     if (!arm_v7m_load_vector(cpu, exc, targets_secure, &addr)) {
8474         /* Vector load failed: derived exception */
8475         qemu_log_mask(CPU_LOG_INT, "...derived exception on vector table load");
8476         v7m_exception_taken(cpu, lr, true, true);
8477         return;
8478     }
8479
8480     /*
8481      * Now we've done everything that might cause a derived exception
8482      * we can go ahead and activate whichever exception we're going to
8483      * take (which might now be the derived exception).
8484      */
8485     armv7m_nvic_acknowledge_irq(env->nvic);
8486
8487     /* Switch to target security state -- must do this before writing SPSEL */
8488     switch_v7m_security_state(env, targets_secure);
8489     write_v7m_control_spsel(env, 0);
8490     arm_clear_exclusive(env);
8491     /* Clear SFPA and FPCA (has no effect if no FPU) */
8492     env->v7m.control[M_REG_S] &=
8493         ~(R_V7M_CONTROL_FPCA_MASK | R_V7M_CONTROL_SFPA_MASK);
8494     /* Clear IT bits */
8495     env->condexec_bits = 0;
8496     env->regs[14] = lr;
8497     env->regs[15] = addr & 0xfffffffe;
8498     env->thumb = addr & 1;
8499 }
8500
8501 static void v7m_update_fpccr(CPUARMState *env, uint32_t frameptr,
8502                              bool apply_splim)
8503 {
8504     /*
8505      * Like the pseudocode UpdateFPCCR: save state in FPCAR and FPCCR
8506      * that we will need later in order to do lazy FP reg stacking.
8507      */
8508     bool is_secure = env->v7m.secure;
8509     void *nvic = env->nvic;
8510     /*
8511      * Some bits are unbanked and live always in fpccr[M_REG_S]; some bits
8512      * are banked and we want to update the bit in the bank for the
8513      * current security state; and in one case we want to specifically
8514      * update the NS banked version of a bit even if we are secure.
8515      */
8516     uint32_t *fpccr_s = &env->v7m.fpccr[M_REG_S];
8517     uint32_t *fpccr_ns = &env->v7m.fpccr[M_REG_NS];
8518     uint32_t *fpccr = &env->v7m.fpccr[is_secure];
8519     bool hfrdy, bfrdy, mmrdy, ns_ufrdy, s_ufrdy, sfrdy, monrdy;
8520
8521     env->v7m.fpcar[is_secure] = frameptr & ~0x7;
8522
8523     if (apply_splim && arm_feature(env, ARM_FEATURE_V8)) {
8524         bool splimviol;
8525         uint32_t splim = v7m_sp_limit(env);
8526         bool ign = armv7m_nvic_neg_prio_requested(nvic, is_secure) &&
8527             (env->v7m.ccr[is_secure] & R_V7M_CCR_STKOFHFNMIGN_MASK);
8528
8529         splimviol = !ign && frameptr < splim;
8530         *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, SPLIMVIOL, splimviol);
8531     }
8532
8533     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, LSPACT, 1);
8534
8535     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, S, is_secure);
8536
8537     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, USER, arm_current_el(env) == 0);
8538
8539     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, THREAD,
8540                         !arm_v7m_is_handler_mode(env));
8541
8542     hfrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_HARD, false);
8543     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, HFRDY, hfrdy);
8544
8545     bfrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_BUS, false);
8546     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, BFRDY, bfrdy);
8547
8548     mmrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_MEM, is_secure);
8549     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, MMRDY, mmrdy);
8550
8551     ns_ufrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_USAGE, false);
8552     *fpccr_ns = FIELD_DP32(*fpccr_ns, V7M_FPCCR, UFRDY, ns_ufrdy);
8553
8554     monrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_DEBUG, false);
8555     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, MONRDY, monrdy);
8556
8557     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8558         s_ufrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_USAGE, true);
8559         *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, UFRDY, s_ufrdy);
8560
8561         sfrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_SECURE, false);
8562         *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, SFRDY, sfrdy);
8563     }
8564 }
8565
8566 void HELPER(v7m_vlstm)(CPUARMState *env, uint32_t fptr)
8567 {
8568     /* fptr is the value of Rn, the frame pointer we store the FP regs to */
8569     bool s = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
8570     bool lspact = env->v7m.fpccr[s] & R_V7M_FPCCR_LSPACT_MASK;
8571
8572     assert(env->v7m.secure);
8573
8574     if (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)) {
8575         return;
8576     }
8577
8578     /* Check access to the coprocessor is permitted */
8579     if (!v7m_cpacr_pass(env, true, arm_current_el(env) != 0)) {
8580         raise_exception_ra(env, EXCP_NOCP, 0, 1, GETPC());
8581     }
8582
8583     if (lspact) {
8584         /* LSPACT should not be active when there is active FP state */
8585         raise_exception_ra(env, EXCP_LSERR, 0, 1, GETPC());
8586     }
8587
8588     if (fptr & 7) {
8589         raise_exception_ra(env, EXCP_UNALIGNED, 0, 1, GETPC());
8590     }
8591
8592     /*
8593      * Note that we do not use v7m_stack_write() here, because the
8594      * accesses should not set the FSR bits for stacking errors if they
8595      * fail. (In pseudocode terms, they are AccType_NORMAL, not AccType_STACK
8596      * or AccType_LAZYFP). Faults in cpu_stl_data() will throw exceptions
8597      * and longjmp out.
8598      */
8599     if (!(env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPEN_MASK)) {
8600         bool ts = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK;
8601         int i;
8602
8603         for (i = 0; i < (ts ? 32 : 16); i += 2) {
8604             uint64_t dn = *aa32_vfp_dreg(env, i / 2);
8605             uint32_t faddr = fptr + 4 * i;
8606             uint32_t slo = extract64(dn, 0, 32);
8607             uint32_t shi = extract64(dn, 32, 32);
8608
8609             if (i >= 16) {
8610                 faddr += 8; /* skip the slot for the FPSCR */
8611             }
8612             cpu_stl_data(env, faddr, slo);
8613             cpu_stl_data(env, faddr + 4, shi);
8614         }
8615         cpu_stl_data(env, fptr + 0x40, vfp_get_fpscr(env));
8616
8617         /*
8618          * If TS is 0 then s0 to s15 and FPSCR are UNKNOWN; we choose to
8619          * leave them unchanged, matching our choice in v7m_preserve_fp_state.
8620          */
8621         if (ts) {
8622             for (i = 0; i < 32; i += 2) {
8623                 *aa32_vfp_dreg(env, i / 2) = 0;
8624             }
8625             vfp_set_fpscr(env, 0);
8626         }
8627     } else {
8628         v7m_update_fpccr(env, fptr, false);
8629     }
8630
8631     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_FPCA_MASK;
8632 }
8633
8634 void HELPER(v7m_vlldm)(CPUARMState *env, uint32_t fptr)
8635 {
8636     /* fptr is the value of Rn, the frame pointer we load the FP regs from */
8637     assert(env->v7m.secure);
8638
8639     if (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)) {
8640         return;
8641     }
8642
8643     /* Check access to the coprocessor is permitted */
8644     if (!v7m_cpacr_pass(env, true, arm_current_el(env) != 0)) {
8645         raise_exception_ra(env, EXCP_NOCP, 0, 1, GETPC());
8646     }
8647
8648     if (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPACT_MASK) {
8649         /* State in FP is still valid */
8650         env->v7m.fpccr[M_REG_S] &= ~R_V7M_FPCCR_LSPACT_MASK;
8651     } else {
8652         bool ts = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK;
8653         int i;
8654         uint32_t fpscr;
8655
8656         if (fptr & 7) {
8657             raise_exception_ra(env, EXCP_UNALIGNED, 0, 1, GETPC());
8658         }
8659
8660         for (i = 0; i < (ts ? 32 : 16); i += 2) {
8661             uint32_t slo, shi;
8662             uint64_t dn;
8663             uint32_t faddr = fptr + 4 * i;
8664
8665             if (i >= 16) {
8666                 faddr += 8; /* skip the slot for the FPSCR */
8667             }
8668
8669             slo = cpu_ldl_data(env, faddr);
8670             shi = cpu_ldl_data(env, faddr + 4);
8671
8672             dn = (uint64_t) shi << 32 | slo;
8673             *aa32_vfp_dreg(env, i / 2) = dn;
8674         }
8675         fpscr = cpu_ldl_data(env, fptr + 0x40);
8676         vfp_set_fpscr(env, fpscr);
8677     }
8678
8679     env->v7m.control[M_REG_S] |= R_V7M_CONTROL_FPCA_MASK;
8680 }
8681
8682 static bool v7m_push_stack(ARMCPU *cpu)
8683 {
8684     /*
8685      * Do the "set up stack frame" part of exception entry,
8686      * similar to pseudocode PushStack().
8687      * Return true if we generate a derived exception (and so
8688      * should ignore further stack faults trying to process
8689      * that derived exception.)
8690      */
8691     bool stacked_ok = true, limitviol = false;
8692     CPUARMState *env = &cpu->env;
8693     uint32_t xpsr = xpsr_read(env);
8694     uint32_t frameptr = env->regs[13];
8695     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
8696     uint32_t framesize;
8697     bool nsacr_cp10 = extract32(env->v7m.nsacr, 10, 1);
8698
8699     if ((env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) &&
8700         (env->v7m.secure || nsacr_cp10)) {
8701         if (env->v7m.secure &&
8702             env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK) {
8703             framesize = 0xa8;
8704         } else {
8705             framesize = 0x68;
8706         }
8707     } else {
8708         framesize = 0x20;
8709     }
8710
8711     /* Align stack pointer if the guest wants that */
8712     if ((frameptr & 4) &&
8713         (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKALIGN_MASK)) {
8714         frameptr -= 4;
8715         xpsr |= XPSR_SPREALIGN;
8716     }
8717
8718     xpsr &= ~XPSR_SFPA;
8719     if (env->v7m.secure &&
8720         (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)) {
8721         xpsr |= XPSR_SFPA;
8722     }
8723
8724     frameptr -= framesize;
8725
8726     if (arm_feature(env, ARM_FEATURE_V8)) {
8727         uint32_t limit = v7m_sp_limit(env);
8728
8729         if (frameptr < limit) {
8730             /*
8731              * Stack limit failure: set SP to the limit value, and generate
8732              * STKOF UsageFault. Stack pushes below the limit must not be
8733              * performed. It is IMPDEF whether pushes above the limit are
8734              * performed; we choose not to.
8735              */
8736             qemu_log_mask(CPU_LOG_INT,
8737                           "...STKOF during stacking\n");
8738             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
8739             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
8740                                     env->v7m.secure);
8741             env->regs[13] = limit;
8742             /*
8743              * We won't try to perform any further memory accesses but
8744              * we must continue through the following code to check for
8745              * permission faults during FPU state preservation, and we
8746              * must update FPCCR if lazy stacking is enabled.
8747              */
8748             limitviol = true;
8749             stacked_ok = false;
8750         }
8751     }
8752
8753     /*
8754      * Write as much of the stack frame as we can. If we fail a stack
8755      * write this will result in a derived exception being pended
8756      * (which may be taken in preference to the one we started with
8757      * if it has higher priority).
8758      */
8759     stacked_ok = stacked_ok &&
8760         v7m_stack_write(cpu, frameptr, env->regs[0], mmu_idx, STACK_NORMAL) &&
8761         v7m_stack_write(cpu, frameptr + 4, env->regs[1],
8762                         mmu_idx, STACK_NORMAL) &&
8763         v7m_stack_write(cpu, frameptr + 8, env->regs[2],
8764                         mmu_idx, STACK_NORMAL) &&
8765         v7m_stack_write(cpu, frameptr + 12, env->regs[3],
8766                         mmu_idx, STACK_NORMAL) &&
8767         v7m_stack_write(cpu, frameptr + 16, env->regs[12],
8768                         mmu_idx, STACK_NORMAL) &&
8769         v7m_stack_write(cpu, frameptr + 20, env->regs[14],
8770                         mmu_idx, STACK_NORMAL) &&
8771         v7m_stack_write(cpu, frameptr + 24, env->regs[15],
8772                         mmu_idx, STACK_NORMAL) &&
8773         v7m_stack_write(cpu, frameptr + 28, xpsr, mmu_idx, STACK_NORMAL);
8774
8775     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) {
8776         /* FPU is active, try to save its registers */
8777         bool fpccr_s = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
8778         bool lspact = env->v7m.fpccr[fpccr_s] & R_V7M_FPCCR_LSPACT_MASK;
8779
8780         if (lspact && arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8781             qemu_log_mask(CPU_LOG_INT,
8782                           "...SecureFault because LSPACT and FPCA both set\n");
8783             env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
8784             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
8785         } else if (!env->v7m.secure && !nsacr_cp10) {
8786             qemu_log_mask(CPU_LOG_INT,
8787                           "...Secure UsageFault with CFSR.NOCP because "
8788                           "NSACR.CP10 prevents stacking FP regs\n");
8789             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, M_REG_S);
8790             env->v7m.cfsr[M_REG_S] |= R_V7M_CFSR_NOCP_MASK;
8791         } else {
8792             if (!(env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPEN_MASK)) {
8793                 /* Lazy stacking disabled, save registers now */
8794                 int i;
8795                 bool cpacr_pass = v7m_cpacr_pass(env, env->v7m.secure,
8796                                                  arm_current_el(env) != 0);
8797
8798                 if (stacked_ok && !cpacr_pass) {
8799                     /*
8800                      * Take UsageFault if CPACR forbids access. The pseudocode
8801                      * here does a full CheckCPEnabled() but we know the NSACR
8802                      * check can never fail as we have already handled that.
8803                      */
8804                     qemu_log_mask(CPU_LOG_INT,
8805                                   "...UsageFault with CFSR.NOCP because "
8806                                   "CPACR.CP10 prevents stacking FP regs\n");
8807                     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
8808                                             env->v7m.secure);
8809                     env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;
8810                     stacked_ok = false;
8811                 }
8812
8813                 for (i = 0; i < ((framesize == 0xa8) ? 32 : 16); i += 2) {
8814                     uint64_t dn = *aa32_vfp_dreg(env, i / 2);
8815                     uint32_t faddr = frameptr + 0x20 + 4 * i;
8816                     uint32_t slo = extract64(dn, 0, 32);
8817                     uint32_t shi = extract64(dn, 32, 32);
8818
8819                     if (i >= 16) {
8820                         faddr += 8; /* skip the slot for the FPSCR */
8821                     }
8822                     stacked_ok = stacked_ok &&
8823                         v7m_stack_write(cpu, faddr, slo,
8824                                         mmu_idx, STACK_NORMAL) &&
8825                         v7m_stack_write(cpu, faddr + 4, shi,
8826                                         mmu_idx, STACK_NORMAL);
8827                 }
8828                 stacked_ok = stacked_ok &&
8829                     v7m_stack_write(cpu, frameptr + 0x60,
8830                                     vfp_get_fpscr(env), mmu_idx, STACK_NORMAL);
8831                 if (cpacr_pass) {
8832                     for (i = 0; i < ((framesize == 0xa8) ? 32 : 16); i += 2) {
8833                         *aa32_vfp_dreg(env, i / 2) = 0;
8834                     }
8835                     vfp_set_fpscr(env, 0);
8836                 }
8837             } else {
8838                 /* Lazy stacking enabled, save necessary info to stack later */
8839                 v7m_update_fpccr(env, frameptr + 0x20, true);
8840             }
8841         }
8842     }
8843
8844     /*
8845      * If we broke a stack limit then SP was already updated earlier;
8846      * otherwise we update SP regardless of whether any of the stack
8847      * accesses failed or we took some other kind of fault.
8848      */
8849     if (!limitviol) {
8850         env->regs[13] = frameptr;
8851     }
8852
8853     return !stacked_ok;
8854 }
8855
8856 static void do_v7m_exception_exit(ARMCPU *cpu)
8857 {
8858     CPUARMState *env = &cpu->env;
8859     uint32_t excret;
8860     uint32_t xpsr, xpsr_mask;
8861     bool ufault = false;
8862     bool sfault = false;
8863     bool return_to_sp_process;
8864     bool return_to_handler;
8865     bool rettobase = false;
8866     bool exc_secure = false;
8867     bool return_to_secure;
8868     bool ftype;
8869     bool restore_s16_s31;
8870
8871     /*
8872      * If we're not in Handler mode then jumps to magic exception-exit
8873      * addresses don't have magic behaviour. However for the v8M
8874      * security extensions the magic secure-function-return has to
8875      * work in thread mode too, so to avoid doing an extra check in
8876      * the generated code we allow exception-exit magic to also cause the
8877      * internal exception and bring us here in thread mode. Correct code
8878      * will never try to do this (the following insn fetch will always
8879      * fault) so we the overhead of having taken an unnecessary exception
8880      * doesn't matter.
8881      */
8882     if (!arm_v7m_is_handler_mode(env)) {
8883         return;
8884     }
8885
8886     /*
8887      * In the spec pseudocode ExceptionReturn() is called directly
8888      * from BXWritePC() and gets the full target PC value including
8889      * bit zero. In QEMU's implementation we treat it as a normal
8890      * jump-to-register (which is then caught later on), and so split
8891      * the target value up between env->regs[15] and env->thumb in
8892      * gen_bx(). Reconstitute it.
8893      */
8894     excret = env->regs[15];
8895     if (env->thumb) {
8896         excret |= 1;
8897     }
8898
8899     qemu_log_mask(CPU_LOG_INT, "Exception return: magic PC %" PRIx32
8900                   " previous exception %d\n",
8901                   excret, env->v7m.exception);
8902
8903     if ((excret & R_V7M_EXCRET_RES1_MASK) != R_V7M_EXCRET_RES1_MASK) {
8904         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero high bits in exception "
8905                       "exit PC value 0x%" PRIx32 " are UNPREDICTABLE\n",
8906                       excret);
8907     }
8908
8909     ftype = excret & R_V7M_EXCRET_FTYPE_MASK;
8910
8911     if (!arm_feature(env, ARM_FEATURE_VFP) && !ftype) {
8912         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero FTYPE in exception "
8913                       "exit PC value 0x%" PRIx32 " is UNPREDICTABLE "
8914                       "if FPU not present\n",
8915                       excret);
8916         ftype = true;
8917     }
8918
8919     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8920         /*
8921          * EXC_RETURN.ES validation check (R_SMFL). We must do this before
8922          * we pick which FAULTMASK to clear.
8923          */
8924         if (!env->v7m.secure &&
8925             ((excret & R_V7M_EXCRET_ES_MASK) ||
8926              !(excret & R_V7M_EXCRET_DCRS_MASK))) {
8927             sfault = 1;
8928             /* For all other purposes, treat ES as 0 (R_HXSR) */
8929             excret &= ~R_V7M_EXCRET_ES_MASK;
8930         }
8931         exc_secure = excret & R_V7M_EXCRET_ES_MASK;
8932     }
8933
8934     if (env->v7m.exception != ARMV7M_EXCP_NMI) {
8935         /*
8936          * Auto-clear FAULTMASK on return from other than NMI.
8937          * If the security extension is implemented then this only
8938          * happens if the raw execution priority is >= 0; the
8939          * value of the ES bit in the exception return value indicates
8940          * which security state's faultmask to clear. (v8M ARM ARM R_KBNF.)
8941          */
8942         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8943             if (armv7m_nvic_raw_execution_priority(env->nvic) >= 0) {
8944                 env->v7m.faultmask[exc_secure] = 0;
8945             }
8946         } else {
8947             env->v7m.faultmask[M_REG_NS] = 0;
8948         }
8949     }
8950
8951     switch (armv7m_nvic_complete_irq(env->nvic, env->v7m.exception,
8952                                      exc_secure)) {
8953     case -1:
8954         /* attempt to exit an exception that isn't active */
8955         ufault = true;
8956         break;
8957     case 0:
8958         /* still an irq active now */
8959         break;
8960     case 1:
8961         /*
8962          * We returned to base exception level, no nesting.
8963          * (In the pseudocode this is written using "NestedActivation != 1"
8964          * where we have 'rettobase == false'.)
8965          */
8966         rettobase = true;
8967         break;
8968     default:
8969         g_assert_not_reached();
8970     }
8971
8972     return_to_handler = !(excret & R_V7M_EXCRET_MODE_MASK);
8973     return_to_sp_process = excret & R_V7M_EXCRET_SPSEL_MASK;
8974     return_to_secure = arm_feature(env, ARM_FEATURE_M_SECURITY) &&
8975         (excret & R_V7M_EXCRET_S_MASK);
8976
8977     if (arm_feature(env, ARM_FEATURE_V8)) {
8978         if (!arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8979             /*
8980              * UNPREDICTABLE if S == 1 or DCRS == 0 or ES == 1 (R_XLCP);
8981              * we choose to take the UsageFault.
8982              */
8983             if ((excret & R_V7M_EXCRET_S_MASK) ||
8984                 (excret & R_V7M_EXCRET_ES_MASK) ||
8985                 !(excret & R_V7M_EXCRET_DCRS_MASK)) {
8986                 ufault = true;
8987             }
8988         }
8989         if (excret & R_V7M_EXCRET_RES0_MASK) {
8990             ufault = true;
8991         }
8992     } else {
8993         /* For v7M we only recognize certain combinations of the low bits */
8994         switch (excret & 0xf) {
8995         case 1: /* Return to Handler */
8996             break;
8997         case 13: /* Return to Thread using Process stack */
8998         case 9: /* Return to Thread using Main stack */
8999             /*
9000              * We only need to check NONBASETHRDENA for v7M, because in
9001              * v8M this bit does not exist (it is RES1).
9002              */
9003             if (!rettobase &&
9004                 !(env->v7m.ccr[env->v7m.secure] &
9005                   R_V7M_CCR_NONBASETHRDENA_MASK)) {
9006                 ufault = true;
9007             }
9008             break;
9009         default:
9010             ufault = true;
9011         }
9012     }
9013
9014     /*
9015      * Set CONTROL.SPSEL from excret.SPSEL. Since we're still in
9016      * Handler mode (and will be until we write the new XPSR.Interrupt
9017      * field) this does not switch around the current stack pointer.
9018      * We must do this before we do any kind of tailchaining, including
9019      * for the derived exceptions on integrity check failures, or we will
9020      * give the guest an incorrect EXCRET.SPSEL value on exception entry.
9021      */
9022     write_v7m_control_spsel_for_secstate(env, return_to_sp_process, exc_secure);
9023
9024     /*
9025      * Clear scratch FP values left in caller saved registers; this
9026      * must happen before any kind of tail chaining.
9027      */
9028     if ((env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_CLRONRET_MASK) &&
9029         (env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK)) {
9030         if (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPACT_MASK) {
9031             env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
9032             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9033             qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
9034                           "stackframe: error during lazy state deactivation\n");
9035             v7m_exception_taken(cpu, excret, true, false);
9036             return;
9037         } else {
9038             /* Clear s0..s15 and FPSCR */
9039             int i;
9040
9041             for (i = 0; i < 16; i += 2) {
9042                 *aa32_vfp_dreg(env, i / 2) = 0;
9043             }
9044             vfp_set_fpscr(env, 0);
9045         }
9046     }
9047
9048     if (sfault) {
9049         env->v7m.sfsr |= R_V7M_SFSR_INVER_MASK;
9050         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9051         qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
9052                       "stackframe: failed EXC_RETURN.ES validity check\n");
9053         v7m_exception_taken(cpu, excret, true, false);
9054         return;
9055     }
9056
9057     if (ufault) {
9058         /*
9059          * Bad exception return: instead of popping the exception
9060          * stack, directly take a usage fault on the current stack.
9061          */
9062         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9063         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9064         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
9065                       "stackframe: failed exception return integrity check\n");
9066         v7m_exception_taken(cpu, excret, true, false);
9067         return;
9068     }
9069
9070     /*
9071      * Tailchaining: if there is currently a pending exception that
9072      * is high enough priority to preempt execution at the level we're
9073      * about to return to, then just directly take that exception now,
9074      * avoiding an unstack-and-then-stack. Note that now we have
9075      * deactivated the previous exception by calling armv7m_nvic_complete_irq()
9076      * our current execution priority is already the execution priority we are
9077      * returning to -- none of the state we would unstack or set based on
9078      * the EXCRET value affects it.
9079      */
9080     if (armv7m_nvic_can_take_pending_exception(env->nvic)) {
9081         qemu_log_mask(CPU_LOG_INT, "...tailchaining to pending exception\n");
9082         v7m_exception_taken(cpu, excret, true, false);
9083         return;
9084     }
9085
9086     switch_v7m_security_state(env, return_to_secure);
9087
9088     {
9089         /*
9090          * The stack pointer we should be reading the exception frame from
9091          * depends on bits in the magic exception return type value (and
9092          * for v8M isn't necessarily the stack pointer we will eventually
9093          * end up resuming execution with). Get a pointer to the location
9094          * in the CPU state struct where the SP we need is currently being
9095          * stored; we will use and modify it in place.
9096          * We use this limited C variable scope so we don't accidentally
9097          * use 'frame_sp_p' after we do something that makes it invalid.
9098          */
9099         uint32_t *frame_sp_p = get_v7m_sp_ptr(env,
9100                                               return_to_secure,
9101                                               !return_to_handler,
9102                                               return_to_sp_process);
9103         uint32_t frameptr = *frame_sp_p;
9104         bool pop_ok = true;
9105         ARMMMUIdx mmu_idx;
9106         bool return_to_priv = return_to_handler ||
9107             !(env->v7m.control[return_to_secure] & R_V7M_CONTROL_NPRIV_MASK);
9108
9109         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, return_to_secure,
9110                                                         return_to_priv);
9111
9112         if (!QEMU_IS_ALIGNED(frameptr, 8) &&
9113             arm_feature(env, ARM_FEATURE_V8)) {
9114             qemu_log_mask(LOG_GUEST_ERROR,
9115                           "M profile exception return with non-8-aligned SP "
9116                           "for destination state is UNPREDICTABLE\n");
9117         }
9118
9119         /* Do we need to pop callee-saved registers? */
9120         if (return_to_secure &&
9121             ((excret & R_V7M_EXCRET_ES_MASK) == 0 ||
9122              (excret & R_V7M_EXCRET_DCRS_MASK) == 0)) {
9123             uint32_t actual_sig;
9124
9125             pop_ok = v7m_stack_read(cpu, &actual_sig, frameptr, mmu_idx);
9126
9127             if (pop_ok && v7m_integrity_sig(env, excret) != actual_sig) {
9128                 /* Take a SecureFault on the current stack */
9129                 env->v7m.sfsr |= R_V7M_SFSR_INVIS_MASK;
9130                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9131                 qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
9132                               "stackframe: failed exception return integrity "
9133                               "signature check\n");
9134                 v7m_exception_taken(cpu, excret, true, false);
9135                 return;
9136             }
9137
9138             pop_ok = pop_ok &&
9139                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
9140                 v7m_stack_read(cpu, &env->regs[5], frameptr + 0xc, mmu_idx) &&
9141                 v7m_stack_read(cpu, &env->regs[6], frameptr + 0x10, mmu_idx) &&
9142                 v7m_stack_read(cpu, &env->regs[7], frameptr + 0x14, mmu_idx) &&
9143                 v7m_stack_read(cpu, &env->regs[8], frameptr + 0x18, mmu_idx) &&
9144                 v7m_stack_read(cpu, &env->regs[9], frameptr + 0x1c, mmu_idx) &&
9145                 v7m_stack_read(cpu, &env->regs[10], frameptr + 0x20, mmu_idx) &&
9146                 v7m_stack_read(cpu, &env->regs[11], frameptr + 0x24, mmu_idx);
9147
9148             frameptr += 0x28;
9149         }
9150
9151         /* Pop registers */
9152         pop_ok = pop_ok &&
9153             v7m_stack_read(cpu, &env->regs[0], frameptr, mmu_idx) &&
9154             v7m_stack_read(cpu, &env->regs[1], frameptr + 0x4, mmu_idx) &&
9155             v7m_stack_read(cpu, &env->regs[2], frameptr + 0x8, mmu_idx) &&
9156             v7m_stack_read(cpu, &env->regs[3], frameptr + 0xc, mmu_idx) &&
9157             v7m_stack_read(cpu, &env->regs[12], frameptr + 0x10, mmu_idx) &&
9158             v7m_stack_read(cpu, &env->regs[14], frameptr + 0x14, mmu_idx) &&
9159             v7m_stack_read(cpu, &env->regs[15], frameptr + 0x18, mmu_idx) &&
9160             v7m_stack_read(cpu, &xpsr, frameptr + 0x1c, mmu_idx);
9161
9162         if (!pop_ok) {
9163             /*
9164              * v7m_stack_read() pended a fault, so take it (as a tail
9165              * chained exception on the same stack frame)
9166              */
9167             qemu_log_mask(CPU_LOG_INT, "...derived exception on unstacking\n");
9168             v7m_exception_taken(cpu, excret, true, false);
9169             return;
9170         }
9171
9172         /*
9173          * Returning from an exception with a PC with bit 0 set is defined
9174          * behaviour on v8M (bit 0 is ignored), but for v7M it was specified
9175          * to be UNPREDICTABLE. In practice actual v7M hardware seems to ignore
9176          * the lsbit, and there are several RTOSes out there which incorrectly
9177          * assume the r15 in the stack frame should be a Thumb-style "lsbit
9178          * indicates ARM/Thumb" value, so ignore the bit on v7M as well, but
9179          * complain about the badly behaved guest.
9180          */
9181         if (env->regs[15] & 1) {
9182             env->regs[15] &= ~1U;
9183             if (!arm_feature(env, ARM_FEATURE_V8)) {
9184                 qemu_log_mask(LOG_GUEST_ERROR,
9185                               "M profile return from interrupt with misaligned "
9186                               "PC is UNPREDICTABLE on v7M\n");
9187             }
9188         }
9189
9190         if (arm_feature(env, ARM_FEATURE_V8)) {
9191             /*
9192              * For v8M we have to check whether the xPSR exception field
9193              * matches the EXCRET value for return to handler/thread
9194              * before we commit to changing the SP and xPSR.
9195              */
9196             bool will_be_handler = (xpsr & XPSR_EXCP) != 0;
9197             if (return_to_handler != will_be_handler) {
9198                 /*
9199                  * Take an INVPC UsageFault on the current stack.
9200                  * By this point we will have switched to the security state
9201                  * for the background state, so this UsageFault will target
9202                  * that state.
9203                  */
9204                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
9205                                         env->v7m.secure);
9206                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9207                 qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
9208                               "stackframe: failed exception return integrity "
9209                               "check\n");
9210                 v7m_exception_taken(cpu, excret, true, false);
9211                 return;
9212             }
9213         }
9214
9215         if (!ftype) {
9216             /* FP present and we need to handle it */
9217             if (!return_to_secure &&
9218                 (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPACT_MASK)) {
9219                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9220                 env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
9221                 qemu_log_mask(CPU_LOG_INT,
9222                               "...taking SecureFault on existing stackframe: "
9223                               "Secure LSPACT set but exception return is "
9224                               "not to secure state\n");
9225                 v7m_exception_taken(cpu, excret, true, false);
9226                 return;
9227             }
9228
9229             restore_s16_s31 = return_to_secure &&
9230                 (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK);
9231
9232             if (env->v7m.fpccr[return_to_secure] & R_V7M_FPCCR_LSPACT_MASK) {
9233                 /* State in FPU is still valid, just clear LSPACT */
9234                 env->v7m.fpccr[return_to_secure] &= ~R_V7M_FPCCR_LSPACT_MASK;
9235             } else {
9236                 int i;
9237                 uint32_t fpscr;
9238                 bool cpacr_pass, nsacr_pass;
9239
9240                 cpacr_pass = v7m_cpacr_pass(env, return_to_secure,
9241                                             return_to_priv);
9242                 nsacr_pass = return_to_secure ||
9243                     extract32(env->v7m.nsacr, 10, 1);
9244
9245                 if (!cpacr_pass) {
9246                     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
9247                                             return_to_secure);
9248                     env->v7m.cfsr[return_to_secure] |= R_V7M_CFSR_NOCP_MASK;
9249                     qemu_log_mask(CPU_LOG_INT,
9250                                   "...taking UsageFault on existing "
9251                                   "stackframe: CPACR.CP10 prevents unstacking "
9252                                   "FP regs\n");
9253                     v7m_exception_taken(cpu, excret, true, false);
9254                     return;
9255                 } else if (!nsacr_pass) {
9256                     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, true);
9257                     env->v7m.cfsr[M_REG_S] |= R_V7M_CFSR_INVPC_MASK;
9258                     qemu_log_mask(CPU_LOG_INT,
9259                                   "...taking Secure UsageFault on existing "
9260                                   "stackframe: NSACR.CP10 prevents unstacking "
9261                                   "FP regs\n");
9262                     v7m_exception_taken(cpu, excret, true, false);
9263                     return;
9264                 }
9265
9266                 for (i = 0; i < (restore_s16_s31 ? 32 : 16); i += 2) {
9267                     uint32_t slo, shi;
9268                     uint64_t dn;
9269                     uint32_t faddr = frameptr + 0x20 + 4 * i;
9270
9271                     if (i >= 16) {
9272                         faddr += 8; /* Skip the slot for the FPSCR */
9273                     }
9274
9275                     pop_ok = pop_ok &&
9276                         v7m_stack_read(cpu, &slo, faddr, mmu_idx) &&
9277                         v7m_stack_read(cpu, &shi, faddr + 4, mmu_idx);
9278
9279                     if (!pop_ok) {
9280                         break;
9281                     }
9282
9283                     dn = (uint64_t)shi << 32 | slo;
9284                     *aa32_vfp_dreg(env, i / 2) = dn;
9285                 }
9286                 pop_ok = pop_ok &&
9287                     v7m_stack_read(cpu, &fpscr, frameptr + 0x60, mmu_idx);
9288                 if (pop_ok) {
9289                     vfp_set_fpscr(env, fpscr);
9290                 }
9291                 if (!pop_ok) {
9292                     /*
9293                      * These regs are 0 if security extension present;
9294                      * otherwise merely UNKNOWN. We zero always.
9295                      */
9296                     for (i = 0; i < (restore_s16_s31 ? 32 : 16); i += 2) {
9297                         *aa32_vfp_dreg(env, i / 2) = 0;
9298                     }
9299                     vfp_set_fpscr(env, 0);
9300                 }
9301             }
9302         }
9303         env->v7m.control[M_REG_S] = FIELD_DP32(env->v7m.control[M_REG_S],
9304                                                V7M_CONTROL, FPCA, !ftype);
9305
9306         /* Commit to consuming the stack frame */
9307         frameptr += 0x20;
9308         if (!ftype) {
9309             frameptr += 0x48;
9310             if (restore_s16_s31) {
9311                 frameptr += 0x40;
9312             }
9313         }
9314         /*
9315          * Undo stack alignment (the SPREALIGN bit indicates that the original
9316          * pre-exception SP was not 8-aligned and we added a padding word to
9317          * align it, so we undo this by ORing in the bit that increases it
9318          * from the current 8-aligned value to the 8-unaligned value. (Adding 4
9319          * would work too but a logical OR is how the pseudocode specifies it.)
9320          */
9321         if (xpsr & XPSR_SPREALIGN) {
9322             frameptr |= 4;
9323         }
9324         *frame_sp_p = frameptr;
9325     }
9326
9327     xpsr_mask = ~(XPSR_SPREALIGN | XPSR_SFPA);
9328     if (!arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
9329         xpsr_mask &= ~XPSR_GE;
9330     }
9331     /* This xpsr_write() will invalidate frame_sp_p as it may switch stack */
9332     xpsr_write(env, xpsr, xpsr_mask);
9333
9334     if (env->v7m.secure) {
9335         bool sfpa = xpsr & XPSR_SFPA;
9336
9337         env->v7m.control[M_REG_S] = FIELD_DP32(env->v7m.control[M_REG_S],
9338                                                V7M_CONTROL, SFPA, sfpa);
9339     }
9340
9341     /*
9342      * The restored xPSR exception field will be zero if we're
9343      * resuming in Thread mode. If that doesn't match what the
9344      * exception return excret specified then this is a UsageFault.
9345      * v7M requires we make this check here; v8M did it earlier.
9346      */
9347     if (return_to_handler != arm_v7m_is_handler_mode(env)) {
9348         /*
9349          * Take an INVPC UsageFault by pushing the stack again;
9350          * we know we're v7M so this is never a Secure UsageFault.
9351          */
9352         bool ignore_stackfaults;
9353
9354         assert(!arm_feature(env, ARM_FEATURE_V8));
9355         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, false);
9356         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9357         ignore_stackfaults = v7m_push_stack(cpu);
9358         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on new stackframe: "
9359                       "failed exception return integrity check\n");
9360         v7m_exception_taken(cpu, excret, false, ignore_stackfaults);
9361         return;
9362     }
9363
9364     /* Otherwise, we have a successful exception exit. */
9365     arm_clear_exclusive(env);
9366     qemu_log_mask(CPU_LOG_INT, "...successful exception return\n");
9367 }
9368
9369 static bool do_v7m_function_return(ARMCPU *cpu)
9370 {
9371     /*
9372      * v8M security extensions magic function return.
9373      * We may either:
9374      *  (1) throw an exception (longjump)
9375      *  (2) return true if we successfully handled the function return
9376      *  (3) return false if we failed a consistency check and have
9377      *      pended a UsageFault that needs to be taken now
9378      *
9379      * At this point the magic return value is split between env->regs[15]
9380      * and env->thumb. We don't bother to reconstitute it because we don't
9381      * need it (all values are handled the same way).
9382      */
9383     CPUARMState *env = &cpu->env;
9384     uint32_t newpc, newpsr, newpsr_exc;
9385
9386     qemu_log_mask(CPU_LOG_INT, "...really v7M secure function return\n");
9387
9388     {
9389         bool threadmode, spsel;
9390         TCGMemOpIdx oi;
9391         ARMMMUIdx mmu_idx;
9392         uint32_t *frame_sp_p;
9393         uint32_t frameptr;
9394
9395         /* Pull the return address and IPSR from the Secure stack */
9396         threadmode = !arm_v7m_is_handler_mode(env);
9397         spsel = env->v7m.control[M_REG_S] & R_V7M_CONTROL_SPSEL_MASK;
9398
9399         frame_sp_p = get_v7m_sp_ptr(env, true, threadmode, spsel);
9400         frameptr = *frame_sp_p;
9401
9402         /*
9403          * These loads may throw an exception (for MPU faults). We want to
9404          * do them as secure, so work out what MMU index that is.
9405          */
9406         mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
9407         oi = make_memop_idx(MO_LE, arm_to_core_mmu_idx(mmu_idx));
9408         newpc = helper_le_ldul_mmu(env, frameptr, oi, 0);
9409         newpsr = helper_le_ldul_mmu(env, frameptr + 4, oi, 0);
9410
9411         /* Consistency checks on new IPSR */
9412         newpsr_exc = newpsr & XPSR_EXCP;
9413         if (!((env->v7m.exception == 0 && newpsr_exc == 0) ||
9414               (env->v7m.exception == 1 && newpsr_exc != 0))) {
9415             /* Pend the fault and tell our caller to take it */
9416             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9417             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
9418                                     env->v7m.secure);
9419             qemu_log_mask(CPU_LOG_INT,
9420                           "...taking INVPC UsageFault: "
9421                           "IPSR consistency check failed\n");
9422             return false;
9423         }
9424
9425         *frame_sp_p = frameptr + 8;
9426     }
9427
9428     /* This invalidates frame_sp_p */
9429     switch_v7m_security_state(env, true);
9430     env->v7m.exception = newpsr_exc;
9431     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
9432     if (newpsr & XPSR_SFPA) {
9433         env->v7m.control[M_REG_S] |= R_V7M_CONTROL_SFPA_MASK;
9434     }
9435     xpsr_write(env, 0, XPSR_IT);
9436     env->thumb = newpc & 1;
9437     env->regs[15] = newpc & ~1;
9438
9439     qemu_log_mask(CPU_LOG_INT, "...function return successful\n");
9440     return true;
9441 }
9442
9443 static bool v7m_read_half_insn(ARMCPU *cpu, ARMMMUIdx mmu_idx,
9444                                uint32_t addr, uint16_t *insn)
9445 {
9446     /*
9447      * Load a 16-bit portion of a v7M instruction, returning true on success,
9448      * or false on failure (in which case we will have pended the appropriate
9449      * exception).
9450      * We need to do the instruction fetch's MPU and SAU checks
9451      * like this because there is no MMU index that would allow
9452      * doing the load with a single function call. Instead we must
9453      * first check that the security attributes permit the load
9454      * and that they don't mismatch on the two halves of the instruction,
9455      * and then we do the load as a secure load (ie using the security
9456      * attributes of the address, not the CPU, as architecturally required).
9457      */
9458     CPUState *cs = CPU(cpu);
9459     CPUARMState *env = &cpu->env;
9460     V8M_SAttributes sattrs = {};
9461     MemTxAttrs attrs = {};
9462     ARMMMUFaultInfo fi = {};
9463     MemTxResult txres;
9464     target_ulong page_size;
9465     hwaddr physaddr;
9466     int prot;
9467
9468     v8m_security_lookup(env, addr, MMU_INST_FETCH, mmu_idx, &sattrs);
9469     if (!sattrs.nsc || sattrs.ns) {
9470         /*
9471          * This must be the second half of the insn, and it straddles a
9472          * region boundary with the second half not being S&NSC.
9473          */
9474         env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
9475         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9476         qemu_log_mask(CPU_LOG_INT,
9477                       "...really SecureFault with SFSR.INVEP\n");
9478         return false;
9479     }
9480     if (get_phys_addr(env, addr, MMU_INST_FETCH, mmu_idx,
9481                       &physaddr, &attrs, &prot, &page_size, &fi, NULL)) {
9482         /* the MPU lookup failed */
9483         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
9484         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM, env->v7m.secure);
9485         qemu_log_mask(CPU_LOG_INT, "...really MemManage with CFSR.IACCVIOL\n");
9486         return false;
9487     }
9488     *insn = address_space_lduw_le(arm_addressspace(cs, attrs), physaddr,
9489                                  attrs, &txres);
9490     if (txres != MEMTX_OK) {
9491         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
9492         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
9493         qemu_log_mask(CPU_LOG_INT, "...really BusFault with CFSR.IBUSERR\n");
9494         return false;
9495     }
9496     return true;
9497 }
9498
9499 static bool v7m_handle_execute_nsc(ARMCPU *cpu)
9500 {
9501     /*
9502      * Check whether this attempt to execute code in a Secure & NS-Callable
9503      * memory region is for an SG instruction; if so, then emulate the
9504      * effect of the SG instruction and return true. Otherwise pend
9505      * the correct kind of exception and return false.
9506      */
9507     CPUARMState *env = &cpu->env;
9508     ARMMMUIdx mmu_idx;
9509     uint16_t insn;
9510
9511     /*
9512      * We should never get here unless get_phys_addr_pmsav8() caused
9513      * an exception for NS executing in S&NSC memory.
9514      */
9515     assert(!env->v7m.secure);
9516     assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
9517
9518     /* We want to do the MPU lookup as secure; work out what mmu_idx that is */
9519     mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
9520
9521     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15], &insn)) {
9522         return false;
9523     }
9524
9525     if (!env->thumb) {
9526         goto gen_invep;
9527     }
9528
9529     if (insn != 0xe97f) {
9530         /*
9531          * Not an SG instruction first half (we choose the IMPDEF
9532          * early-SG-check option).
9533          */
9534         goto gen_invep;
9535     }
9536
9537     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15] + 2, &insn)) {
9538         return false;
9539     }
9540
9541     if (insn != 0xe97f) {
9542         /*
9543          * Not an SG instruction second half (yes, both halves of the SG
9544          * insn have the same hex value)
9545          */
9546         goto gen_invep;
9547     }
9548
9549     /*
9550      * OK, we have confirmed that we really have an SG instruction.
9551      * We know we're NS in S memory so don't need to repeat those checks.
9552      */
9553     qemu_log_mask(CPU_LOG_INT, "...really an SG instruction at 0x%08" PRIx32
9554                   ", executing it\n", env->regs[15]);
9555     env->regs[14] &= ~1;
9556     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
9557     switch_v7m_security_state(env, true);
9558     xpsr_write(env, 0, XPSR_IT);
9559     env->regs[15] += 4;
9560     return true;
9561
9562 gen_invep:
9563     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
9564     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9565     qemu_log_mask(CPU_LOG_INT,
9566                   "...really SecureFault with SFSR.INVEP\n");
9567     return false;
9568 }
9569
9570 void arm_v7m_cpu_do_interrupt(CPUState *cs)
9571 {
9572     ARMCPU *cpu = ARM_CPU(cs);
9573     CPUARMState *env = &cpu->env;
9574     uint32_t lr;
9575     bool ignore_stackfaults;
9576
9577     arm_log_exception(cs->exception_index);
9578
9579     /*
9580      * For exceptions we just mark as pending on the NVIC, and let that
9581      * handle it.
9582      */
9583     switch (cs->exception_index) {
9584     case EXCP_UDEF:
9585         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9586         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;
9587         break;
9588     case EXCP_NOCP:
9589     {
9590         /*
9591          * NOCP might be directed to something other than the current
9592          * security state if this fault is because of NSACR; we indicate
9593          * the target security state using exception.target_el.
9594          */
9595         int target_secstate;
9596
9597         if (env->exception.target_el == 3) {
9598             target_secstate = M_REG_S;
9599         } else {
9600             target_secstate = env->v7m.secure;
9601         }
9602         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, target_secstate);
9603         env->v7m.cfsr[target_secstate] |= R_V7M_CFSR_NOCP_MASK;
9604         break;
9605     }
9606     case EXCP_INVSTATE:
9607         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9608         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;
9609         break;
9610     case EXCP_STKOF:
9611         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9612         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
9613         break;
9614     case EXCP_LSERR:
9615         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9616         env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
9617         break;
9618     case EXCP_UNALIGNED:
9619         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9620         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNALIGNED_MASK;
9621         break;
9622     case EXCP_SWI:
9623         /* The PC already points to the next instruction.  */
9624         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC, env->v7m.secure);
9625         break;
9626     case EXCP_PREFETCH_ABORT:
9627     case EXCP_DATA_ABORT:
9628         /*
9629          * Note that for M profile we don't have a guest facing FSR, but
9630          * the env->exception.fsr will be populated by the code that
9631          * raises the fault, in the A profile short-descriptor format.
9632          */
9633         switch (env->exception.fsr & 0xf) {
9634         case M_FAKE_FSR_NSC_EXEC:
9635             /*
9636              * Exception generated when we try to execute code at an address
9637              * which is marked as Secure & Non-Secure Callable and the CPU
9638              * is in the Non-Secure state. The only instruction which can
9639              * be executed like this is SG (and that only if both halves of
9640              * the SG instruction have the same security attributes.)
9641              * Everything else must generate an INVEP SecureFault, so we
9642              * emulate the SG instruction here.
9643              */
9644             if (v7m_handle_execute_nsc(cpu)) {
9645                 return;
9646             }
9647             break;
9648         case M_FAKE_FSR_SFAULT:
9649             /*
9650              * Various flavours of SecureFault for attempts to execute or
9651              * access data in the wrong security state.
9652              */
9653             switch (cs->exception_index) {
9654             case EXCP_PREFETCH_ABORT:
9655                 if (env->v7m.secure) {
9656                     env->v7m.sfsr |= R_V7M_SFSR_INVTRAN_MASK;
9657                     qemu_log_mask(CPU_LOG_INT,
9658                                   "...really SecureFault with SFSR.INVTRAN\n");
9659                 } else {
9660                     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
9661                     qemu_log_mask(CPU_LOG_INT,
9662                                   "...really SecureFault with SFSR.INVEP\n");
9663                 }
9664                 break;
9665             case EXCP_DATA_ABORT:
9666                 /* This must be an NS access to S memory */
9667                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
9668                 qemu_log_mask(CPU_LOG_INT,
9669                               "...really SecureFault with SFSR.AUVIOL\n");
9670                 break;
9671             }
9672             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9673             break;
9674         case 0x8: /* External Abort */
9675             switch (cs->exception_index) {
9676             case EXCP_PREFETCH_ABORT:
9677                 env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
9678                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");
9679                 break;
9680             case EXCP_DATA_ABORT:
9681                 env->v7m.cfsr[M_REG_NS] |=
9682                     (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);
9683                 env->v7m.bfar = env->exception.vaddress;
9684                 qemu_log_mask(CPU_LOG_INT,
9685                               "...with CFSR.PRECISERR and BFAR 0x%x\n",
9686                               env->v7m.bfar);
9687                 break;
9688             }
9689             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
9690             break;
9691         default:
9692             /*
9693              * All other FSR values are either MPU faults or "can't happen
9694              * for M profile" cases.
9695              */
9696             switch (cs->exception_index) {
9697             case EXCP_PREFETCH_ABORT:
9698                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
9699                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");
9700                 break;
9701             case EXCP_DATA_ABORT:
9702                 env->v7m.cfsr[env->v7m.secure] |=
9703                     (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);
9704                 env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;
9705                 qemu_log_mask(CPU_LOG_INT,
9706                               "...with CFSR.DACCVIOL and MMFAR 0x%x\n",
9707                               env->v7m.mmfar[env->v7m.secure]);
9708                 break;
9709             }
9710             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM,
9711                                     env->v7m.secure);
9712             break;
9713         }
9714         break;
9715     case EXCP_BKPT:
9716         if (semihosting_enabled()) {
9717             int nr;
9718             nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;
9719             if (nr == 0xab) {
9720                 env->regs[15] += 2;
9721                 qemu_log_mask(CPU_LOG_INT,
9722                               "...handling as semihosting call 0x%x\n",
9723                               env->regs[0]);
9724                 env->regs[0] = do_arm_semihosting(env);
9725                 return;
9726             }
9727         }
9728         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG, false);
9729         break;
9730     case EXCP_IRQ:
9731         break;
9732     case EXCP_EXCEPTION_EXIT:
9733         if (env->regs[15] < EXC_RETURN_MIN_MAGIC) {
9734             /* Must be v8M security extension function return */
9735             assert(env->regs[15] >= FNC_RETURN_MIN_MAGIC);
9736             assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
9737             if (do_v7m_function_return(cpu)) {
9738                 return;
9739             }
9740         } else {
9741             do_v7m_exception_exit(cpu);
9742             return;
9743         }
9744         break;
9745     case EXCP_LAZYFP:
9746         /*
9747          * We already pended the specific exception in the NVIC in the
9748          * v7m_preserve_fp_state() helper function.
9749          */
9750         break;
9751     default:
9752         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9753         return; /* Never happens.  Keep compiler happy.  */
9754     }
9755
9756     if (arm_feature(env, ARM_FEATURE_V8)) {
9757         lr = R_V7M_EXCRET_RES1_MASK |
9758             R_V7M_EXCRET_DCRS_MASK;
9759         /*
9760          * The S bit indicates whether we should return to Secure
9761          * or NonSecure (ie our current state).
9762          * The ES bit indicates whether we're taking this exception
9763          * to Secure or NonSecure (ie our target state). We set it
9764          * later, in v7m_exception_taken().
9765          * The SPSEL bit is also set in v7m_exception_taken() for v8M.
9766          * This corresponds to the ARM ARM pseudocode for v8M setting
9767          * some LR bits in PushStack() and some in ExceptionTaken();
9768          * the distinction matters for the tailchain cases where we
9769          * can take an exception without pushing the stack.
9770          */
9771         if (env->v7m.secure) {
9772             lr |= R_V7M_EXCRET_S_MASK;
9773         }
9774         if (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK)) {
9775             lr |= R_V7M_EXCRET_FTYPE_MASK;
9776         }
9777     } else {
9778         lr = R_V7M_EXCRET_RES1_MASK |
9779             R_V7M_EXCRET_S_MASK |
9780             R_V7M_EXCRET_DCRS_MASK |
9781             R_V7M_EXCRET_FTYPE_MASK |
9782             R_V7M_EXCRET_ES_MASK;
9783         if (env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK) {
9784             lr |= R_V7M_EXCRET_SPSEL_MASK;
9785         }
9786     }
9787     if (!arm_v7m_is_handler_mode(env)) {
9788         lr |= R_V7M_EXCRET_MODE_MASK;
9789     }
9790
9791     ignore_stackfaults = v7m_push_stack(cpu);
9792     v7m_exception_taken(cpu, lr, false, ignore_stackfaults);
9793 }
9794
9795 /*
9796  * Function used to synchronize QEMU's AArch64 register set with AArch32
9797  * register set.  This is necessary when switching between AArch32 and AArch64
9798  * execution state.
9799  */
9800 void aarch64_sync_32_to_64(CPUARMState *env)
9801 {
9802     int i;
9803     uint32_t mode = env->uncached_cpsr & CPSR_M;
9804
9805     /* We can blanket copy R[0:7] to X[0:7] */
9806     for (i = 0; i < 8; i++) {
9807         env->xregs[i] = env->regs[i];
9808     }
9809
9810     /*
9811      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9812      * Otherwise, they come from the banked user regs.
9813      */
9814     if (mode == ARM_CPU_MODE_FIQ) {
9815         for (i = 8; i < 13; i++) {
9816             env->xregs[i] = env->usr_regs[i - 8];
9817         }
9818     } else {
9819         for (i = 8; i < 13; i++) {
9820             env->xregs[i] = env->regs[i];
9821         }
9822     }
9823
9824     /*
9825      * Registers x13-x23 are the various mode SP and FP registers. Registers
9826      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9827      * from the mode banked register.
9828      */
9829     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9830         env->xregs[13] = env->regs[13];
9831         env->xregs[14] = env->regs[14];
9832     } else {
9833         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9834         /* HYP is an exception in that it is copied from r14 */
9835         if (mode == ARM_CPU_MODE_HYP) {
9836             env->xregs[14] = env->regs[14];
9837         } else {
9838             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9839         }
9840     }
9841
9842     if (mode == ARM_CPU_MODE_HYP) {
9843         env->xregs[15] = env->regs[13];
9844     } else {
9845         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9846     }
9847
9848     if (mode == ARM_CPU_MODE_IRQ) {
9849         env->xregs[16] = env->regs[14];
9850         env->xregs[17] = env->regs[13];
9851     } else {
9852         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9853         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9854     }
9855
9856     if (mode == ARM_CPU_MODE_SVC) {
9857         env->xregs[18] = env->regs[14];
9858         env->xregs[19] = env->regs[13];
9859     } else {
9860         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9861         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9862     }
9863
9864     if (mode == ARM_CPU_MODE_ABT) {
9865         env->xregs[20] = env->regs[14];
9866         env->xregs[21] = env->regs[13];
9867     } else {
9868         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9869         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9870     }
9871
9872     if (mode == ARM_CPU_MODE_UND) {
9873         env->xregs[22] = env->regs[14];
9874         env->xregs[23] = env->regs[13];
9875     } else {
9876         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9877         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9878     }
9879
9880     /*
9881      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9882      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9883      * FIQ bank for r8-r14.
9884      */
9885     if (mode == ARM_CPU_MODE_FIQ) {
9886         for (i = 24; i < 31; i++) {
9887             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9888         }
9889     } else {
9890         for (i = 24; i < 29; i++) {
9891             env->xregs[i] = env->fiq_regs[i - 24];
9892         }
9893         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9894         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9895     }
9896
9897     env->pc = env->regs[15];
9898 }
9899
9900 /*
9901  * Function used to synchronize QEMU's AArch32 register set with AArch64
9902  * register set.  This is necessary when switching between AArch32 and AArch64
9903  * execution state.
9904  */
9905 void aarch64_sync_64_to_32(CPUARMState *env)
9906 {
9907     int i;
9908     uint32_t mode = env->uncached_cpsr & CPSR_M;
9909
9910     /* We can blanket copy X[0:7] to R[0:7] */
9911     for (i = 0; i < 8; i++) {
9912         env->regs[i] = env->xregs[i];
9913     }
9914
9915     /*
9916      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9917      * Otherwise, we copy x8-x12 into the banked user regs.
9918      */
9919     if (mode == ARM_CPU_MODE_FIQ) {
9920         for (i = 8; i < 13; i++) {
9921             env->usr_regs[i - 8] = env->xregs[i];
9922         }
9923     } else {
9924         for (i = 8; i < 13; i++) {
9925             env->regs[i] = env->xregs[i];
9926         }
9927     }
9928
9929     /*
9930      * Registers r13 & r14 depend on the current mode.
9931      * If we are in a given mode, we copy the corresponding x registers to r13
9932      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9933      * for the mode.
9934      */
9935     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9936         env->regs[13] = env->xregs[13];
9937         env->regs[14] = env->xregs[14];
9938     } else {
9939         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9940
9941         /*
9942          * HYP is an exception in that it does not have its own banked r14 but
9943          * shares the USR r14
9944          */
9945         if (mode == ARM_CPU_MODE_HYP) {
9946             env->regs[14] = env->xregs[14];
9947         } else {
9948             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9949         }
9950     }
9951
9952     if (mode == ARM_CPU_MODE_HYP) {
9953         env->regs[13] = env->xregs[15];
9954     } else {
9955         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9956     }
9957
9958     if (mode == ARM_CPU_MODE_IRQ) {
9959         env->regs[14] = env->xregs[16];
9960         env->regs[13] = env->xregs[17];
9961     } else {
9962         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9963         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9964     }
9965
9966     if (mode == ARM_CPU_MODE_SVC) {
9967         env->regs[14] = env->xregs[18];
9968         env->regs[13] = env->xregs[19];
9969     } else {
9970         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9971         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9972     }
9973
9974     if (mode == ARM_CPU_MODE_ABT) {
9975         env->regs[14] = env->xregs[20];
9976         env->regs[13] = env->xregs[21];
9977     } else {
9978         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9979         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9980     }
9981
9982     if (mode == ARM_CPU_MODE_UND) {
9983         env->regs[14] = env->xregs[22];
9984         env->regs[13] = env->xregs[23];
9985     } else {
9986         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9987         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9988     }
9989
9990     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9991      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9992      * FIQ bank for r8-r14.
9993      */
9994     if (mode == ARM_CPU_MODE_FIQ) {
9995         for (i = 24; i < 31; i++) {
9996             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9997         }
9998     } else {
9999         for (i = 24; i < 29; i++) {
10000             env->fiq_regs[i - 24] = env->xregs[i];
10001         }
10002         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
10003         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
10004     }
10005
10006     env->regs[15] = env->pc;
10007 }
10008
10009 static void take_aarch32_exception(CPUARMState *env, int new_mode,
10010                                    uint32_t mask, uint32_t offset,
10011                                    uint32_t newpc)
10012 {
10013     /* Change the CPU state so as to actually take the exception. */
10014     switch_mode(env, new_mode);
10015     /*
10016      * For exceptions taken to AArch32 we must clear the SS bit in both
10017      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
10018      */
10019     env->uncached_cpsr &= ~PSTATE_SS;
10020     env->spsr = cpsr_read(env);
10021     /* Clear IT bits.  */
10022     env->condexec_bits = 0;
10023     /* Switch to the new mode, and to the correct instruction set.  */
10024     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
10025     /* Set new mode endianness */
10026     env->uncached_cpsr &= ~CPSR_E;
10027     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
10028         env->uncached_cpsr |= CPSR_E;
10029     }
10030     /* J and IL must always be cleared for exception entry */
10031     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
10032     env->daif |= mask;
10033
10034     if (new_mode == ARM_CPU_MODE_HYP) {
10035         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
10036         env->elr_el[2] = env->regs[15];
10037     } else {
10038         /*
10039          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
10040          * and we should just guard the thumb mode on V4
10041          */
10042         if (arm_feature(env, ARM_FEATURE_V4T)) {
10043             env->thumb =
10044                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
10045         }
10046         env->regs[14] = env->regs[15] + offset;
10047     }
10048     env->regs[15] = newpc;
10049 }
10050
10051 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
10052 {
10053     /*
10054      * Handle exception entry to Hyp mode; this is sufficiently
10055      * different to entry to other AArch32 modes that we handle it
10056      * separately here.
10057      *
10058      * The vector table entry used is always the 0x14 Hyp mode entry point,
10059      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
10060      * The offset applied to the preferred return address is always zero
10061      * (see DDI0487C.a section G1.12.3).
10062      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
10063      */
10064     uint32_t addr, mask;
10065     ARMCPU *cpu = ARM_CPU(cs);
10066     CPUARMState *env = &cpu->env;
10067
10068     switch (cs->exception_index) {
10069     case EXCP_UDEF:
10070         addr = 0x04;
10071         break;
10072     case EXCP_SWI:
10073         addr = 0x14;
10074         break;
10075     case EXCP_BKPT:
10076         /* Fall through to prefetch abort.  */
10077     case EXCP_PREFETCH_ABORT:
10078         env->cp15.ifar_s = env->exception.vaddress;
10079         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
10080                       (uint32_t)env->exception.vaddress);
10081         addr = 0x0c;
10082         break;
10083     case EXCP_DATA_ABORT:
10084         env->cp15.dfar_s = env->exception.vaddress;
10085         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
10086                       (uint32_t)env->exception.vaddress);
10087         addr = 0x10;
10088         break;
10089     case EXCP_IRQ:
10090         addr = 0x18;
10091         break;
10092     case EXCP_FIQ:
10093         addr = 0x1c;
10094         break;
10095     case EXCP_HVC:
10096         addr = 0x08;
10097         break;
10098     case EXCP_HYP_TRAP:
10099         addr = 0x14;
10100     default:
10101         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10102     }
10103
10104     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
10105         if (!arm_feature(env, ARM_FEATURE_V8)) {
10106             /*
10107              * QEMU syndrome values are v8-style. v7 has the IL bit
10108              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
10109              * If this is a v7 CPU, squash the IL bit in those cases.
10110              */
10111             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
10112                 (cs->exception_index == EXCP_DATA_ABORT &&
10113                  !(env->exception.syndrome & ARM_EL_ISV)) ||
10114                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
10115                 env->exception.syndrome &= ~ARM_EL_IL;
10116             }
10117         }
10118         env->cp15.esr_el[2] = env->exception.syndrome;
10119     }
10120
10121     if (arm_current_el(env) != 2 && addr < 0x14) {
10122         addr = 0x14;
10123     }
10124
10125     mask = 0;
10126     if (!(env->cp15.scr_el3 & SCR_EA)) {
10127         mask |= CPSR_A;
10128     }
10129     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
10130         mask |= CPSR_I;
10131     }
10132     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
10133         mask |= CPSR_F;
10134     }
10135
10136     addr += env->cp15.hvbar;
10137
10138     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
10139 }
10140
10141 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
10142 {
10143     ARMCPU *cpu = ARM_CPU(cs);
10144     CPUARMState *env = &cpu->env;
10145     uint32_t addr;
10146     uint32_t mask;
10147     int new_mode;
10148     uint32_t offset;
10149     uint32_t moe;
10150
10151     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
10152     switch (syn_get_ec(env->exception.syndrome)) {
10153     case EC_BREAKPOINT:
10154     case EC_BREAKPOINT_SAME_EL:
10155         moe = 1;
10156         break;
10157     case EC_WATCHPOINT:
10158     case EC_WATCHPOINT_SAME_EL:
10159         moe = 10;
10160         break;
10161     case EC_AA32_BKPT:
10162         moe = 3;
10163         break;
10164     case EC_VECTORCATCH:
10165         moe = 5;
10166         break;
10167     default:
10168         moe = 0;
10169         break;
10170     }
10171
10172     if (moe) {
10173         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
10174     }
10175
10176     if (env->exception.target_el == 2) {
10177         arm_cpu_do_interrupt_aarch32_hyp(cs);
10178         return;
10179     }
10180
10181     switch (cs->exception_index) {
10182     case EXCP_UDEF:
10183         new_mode = ARM_CPU_MODE_UND;
10184         addr = 0x04;
10185         mask = CPSR_I;
10186         if (env->thumb)
10187             offset = 2;
10188         else
10189             offset = 4;
10190         break;
10191     case EXCP_SWI:
10192         new_mode = ARM_CPU_MODE_SVC;
10193         addr = 0x08;
10194         mask = CPSR_I;
10195         /* The PC already points to the next instruction.  */
10196         offset = 0;
10197         break;
10198     case EXCP_BKPT:
10199         /* Fall through to prefetch abort.  */
10200     case EXCP_PREFETCH_ABORT:
10201         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
10202         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
10203         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
10204                       env->exception.fsr, (uint32_t)env->exception.vaddress);
10205         new_mode = ARM_CPU_MODE_ABT;
10206         addr = 0x0c;
10207         mask = CPSR_A | CPSR_I;
10208         offset = 4;
10209         break;
10210     case EXCP_DATA_ABORT:
10211         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
10212         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
10213         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
10214                       env->exception.fsr,
10215                       (uint32_t)env->exception.vaddress);
10216         new_mode = ARM_CPU_MODE_ABT;
10217         addr = 0x10;
10218         mask = CPSR_A | CPSR_I;
10219         offset = 8;
10220         break;
10221     case EXCP_IRQ:
10222         new_mode = ARM_CPU_MODE_IRQ;
10223         addr = 0x18;
10224         /* Disable IRQ and imprecise data aborts.  */
10225         mask = CPSR_A | CPSR_I;
10226         offset = 4;
10227         if (env->cp15.scr_el3 & SCR_IRQ) {
10228             /* IRQ routed to monitor mode */
10229             new_mode = ARM_CPU_MODE_MON;
10230             mask |= CPSR_F;
10231         }
10232         break;
10233     case EXCP_FIQ:
10234         new_mode = ARM_CPU_MODE_FIQ;
10235         addr = 0x1c;
10236         /* Disable FIQ, IRQ and imprecise data aborts.  */
10237         mask = CPSR_A | CPSR_I | CPSR_F;
10238         if (env->cp15.scr_el3 & SCR_FIQ) {
10239             /* FIQ routed to monitor mode */
10240             new_mode = ARM_CPU_MODE_MON;
10241         }
10242         offset = 4;
10243         break;
10244     case EXCP_VIRQ:
10245         new_mode = ARM_CPU_MODE_IRQ;
10246         addr = 0x18;
10247         /* Disable IRQ and imprecise data aborts.  */
10248         mask = CPSR_A | CPSR_I;
10249         offset = 4;
10250         break;
10251     case EXCP_VFIQ:
10252         new_mode = ARM_CPU_MODE_FIQ;
10253         addr = 0x1c;
10254         /* Disable FIQ, IRQ and imprecise data aborts.  */
10255         mask = CPSR_A | CPSR_I | CPSR_F;
10256         offset = 4;
10257         break;
10258     case EXCP_SMC:
10259         new_mode = ARM_CPU_MODE_MON;
10260         addr = 0x08;
10261         mask = CPSR_A | CPSR_I | CPSR_F;
10262         offset = 0;
10263         break;
10264     default:
10265         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10266         return; /* Never happens.  Keep compiler happy.  */
10267     }
10268
10269     if (new_mode == ARM_CPU_MODE_MON) {
10270         addr += env->cp15.mvbar;
10271     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
10272         /* High vectors. When enabled, base address cannot be remapped. */
10273         addr += 0xffff0000;
10274     } else {
10275         /* ARM v7 architectures provide a vector base address register to remap
10276          * the interrupt vector table.
10277          * This register is only followed in non-monitor mode, and is banked.
10278          * Note: only bits 31:5 are valid.
10279          */
10280         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
10281     }
10282
10283     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
10284         env->cp15.scr_el3 &= ~SCR_NS;
10285     }
10286
10287     take_aarch32_exception(env, new_mode, mask, offset, addr);
10288 }
10289
10290 /* Handle exception entry to a target EL which is using AArch64 */
10291 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
10292 {
10293     ARMCPU *cpu = ARM_CPU(cs);
10294     CPUARMState *env = &cpu->env;
10295     unsigned int new_el = env->exception.target_el;
10296     target_ulong addr = env->cp15.vbar_el[new_el];
10297     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
10298     unsigned int cur_el = arm_current_el(env);
10299
10300     /*
10301      * Note that new_el can never be 0.  If cur_el is 0, then
10302      * el0_a64 is is_a64(), else el0_a64 is ignored.
10303      */
10304     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
10305
10306     if (cur_el < new_el) {
10307         /* Entry vector offset depends on whether the implemented EL
10308          * immediately lower than the target level is using AArch32 or AArch64
10309          */
10310         bool is_aa64;
10311
10312         switch (new_el) {
10313         case 3:
10314             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
10315             break;
10316         case 2:
10317             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
10318             break;
10319         case 1:
10320             is_aa64 = is_a64(env);
10321             break;
10322         default:
10323             g_assert_not_reached();
10324         }
10325
10326         if (is_aa64) {
10327             addr += 0x400;
10328         } else {
10329             addr += 0x600;
10330         }
10331     } else if (pstate_read(env) & PSTATE_SP) {
10332         addr += 0x200;
10333     }
10334
10335     switch (cs->exception_index) {
10336     case EXCP_PREFETCH_ABORT:
10337     case EXCP_DATA_ABORT:
10338         env->cp15.far_el[new_el] = env->exception.vaddress;
10339         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
10340                       env->cp15.far_el[new_el]);
10341         /* fall through */
10342     case EXCP_BKPT:
10343     case EXCP_UDEF:
10344     case EXCP_SWI:
10345     case EXCP_HVC:
10346     case EXCP_HYP_TRAP:
10347     case EXCP_SMC:
10348         if (syn_get_ec(env->exception.syndrome) == EC_ADVSIMDFPACCESSTRAP) {
10349             /*
10350              * QEMU internal FP/SIMD syndromes from AArch32 include the
10351              * TA and coproc fields which are only exposed if the exception
10352              * is taken to AArch32 Hyp mode. Mask them out to get a valid
10353              * AArch64 format syndrome.
10354              */
10355             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
10356         }
10357         env->cp15.esr_el[new_el] = env->exception.syndrome;
10358         break;
10359     case EXCP_IRQ:
10360     case EXCP_VIRQ:
10361         addr += 0x80;
10362         break;
10363     case EXCP_FIQ:
10364     case EXCP_VFIQ:
10365         addr += 0x100;
10366         break;
10367     case EXCP_SEMIHOST:
10368         qemu_log_mask(CPU_LOG_INT,
10369                       "...handling as semihosting call 0x%" PRIx64 "\n",
10370                       env->xregs[0]);
10371         env->xregs[0] = do_arm_semihosting(env);
10372         return;
10373     default:
10374         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10375     }
10376
10377     if (is_a64(env)) {
10378         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
10379         aarch64_save_sp(env, arm_current_el(env));
10380         env->elr_el[new_el] = env->pc;
10381     } else {
10382         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
10383         env->elr_el[new_el] = env->regs[15];
10384
10385         aarch64_sync_32_to_64(env);
10386
10387         env->condexec_bits = 0;
10388     }
10389     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
10390                   env->elr_el[new_el]);
10391
10392     pstate_write(env, PSTATE_DAIF | new_mode);
10393     env->aarch64 = 1;
10394     aarch64_restore_sp(env, new_el);
10395
10396     env->pc = addr;
10397
10398     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10399                   new_el, env->pc, pstate_read(env));
10400 }
10401
10402 static inline bool check_for_semihosting(CPUState *cs)
10403 {
10404 #ifdef CONFIG_TCG
10405     /* Check whether this exception is a semihosting call; if so
10406      * then handle it and return true; otherwise return false.
10407      */
10408     ARMCPU *cpu = ARM_CPU(cs);
10409     CPUARMState *env = &cpu->env;
10410
10411     if (is_a64(env)) {
10412         if (cs->exception_index == EXCP_SEMIHOST) {
10413             /* This is always the 64-bit semihosting exception.
10414              * The "is this usermode" and "is semihosting enabled"
10415              * checks have been done at translate time.
10416              */
10417             qemu_log_mask(CPU_LOG_INT,
10418                           "...handling as semihosting call 0x%" PRIx64 "\n",
10419                           env->xregs[0]);
10420             env->xregs[0] = do_arm_semihosting(env);
10421             return true;
10422         }
10423         return false;
10424     } else {
10425         uint32_t imm;
10426
10427         /* Only intercept calls from privileged modes, to provide some
10428          * semblance of security.
10429          */
10430         if (cs->exception_index != EXCP_SEMIHOST &&
10431             (!semihosting_enabled() ||
10432              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
10433             return false;
10434         }
10435
10436         switch (cs->exception_index) {
10437         case EXCP_SEMIHOST:
10438             /* This is always a semihosting call; the "is this usermode"
10439              * and "is semihosting enabled" checks have been done at
10440              * translate time.
10441              */
10442             break;
10443         case EXCP_SWI:
10444             /* Check for semihosting interrupt.  */
10445             if (env->thumb) {
10446                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
10447                     & 0xff;
10448                 if (imm == 0xab) {
10449                     break;
10450                 }
10451             } else {
10452                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
10453                     & 0xffffff;
10454                 if (imm == 0x123456) {
10455                     break;
10456                 }
10457             }
10458             return false;
10459         case EXCP_BKPT:
10460             /* See if this is a semihosting syscall.  */
10461             if (env->thumb) {
10462                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
10463                     & 0xff;
10464                 if (imm == 0xab) {
10465                     env->regs[15] += 2;
10466                     break;
10467                 }
10468             }
10469             return false;
10470         default:
10471             return false;
10472         }
10473
10474         qemu_log_mask(CPU_LOG_INT,
10475                       "...handling as semihosting call 0x%x\n",
10476                       env->regs[0]);
10477         env->regs[0] = do_arm_semihosting(env);
10478         return true;
10479     }
10480 #else
10481     return false;
10482 #endif
10483 }
10484
10485 /* Handle a CPU exception for A and R profile CPUs.
10486  * Do any appropriate logging, handle PSCI calls, and then hand off
10487  * to the AArch64-entry or AArch32-entry function depending on the
10488  * target exception level's register width.
10489  */
10490 void arm_cpu_do_interrupt(CPUState *cs)
10491 {
10492     ARMCPU *cpu = ARM_CPU(cs);
10493     CPUARMState *env = &cpu->env;
10494     unsigned int new_el = env->exception.target_el;
10495
10496     assert(!arm_feature(env, ARM_FEATURE_M));
10497
10498     arm_log_exception(cs->exception_index);
10499     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10500                   new_el);
10501     if (qemu_loglevel_mask(CPU_LOG_INT)
10502         && !excp_is_internal(cs->exception_index)) {
10503         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10504                       syn_get_ec(env->exception.syndrome),
10505                       env->exception.syndrome);
10506     }
10507
10508     if (arm_is_psci_call(cpu, cs->exception_index)) {
10509         arm_handle_psci_call(cpu);
10510         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10511         return;
10512     }
10513
10514     /* Semihosting semantics depend on the register width of the
10515      * code that caused the exception, not the target exception level,
10516      * so must be handled here.
10517      */
10518     if (check_for_semihosting(cs)) {
10519         return;
10520     }
10521
10522     /* Hooks may change global state so BQL should be held, also the
10523      * BQL needs to be held for any modification of
10524      * cs->interrupt_request.
10525      */
10526     g_assert(qemu_mutex_iothread_locked());
10527
10528     arm_call_pre_el_change_hook(cpu);
10529
10530     assert(!excp_is_internal(cs->exception_index));
10531     if (arm_el_is_aa64(env, new_el)) {
10532         arm_cpu_do_interrupt_aarch64(cs);
10533     } else {
10534         arm_cpu_do_interrupt_aarch32(cs);
10535     }
10536
10537     arm_call_el_change_hook(cpu);
10538
10539     if (!kvm_enabled()) {
10540         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10541     }
10542 }
10543 #endif /* !CONFIG_USER_ONLY */
10544
10545 /* Return the exception level which controls this address translation regime */
10546 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
10547 {
10548     switch (mmu_idx) {
10549     case ARMMMUIdx_S2NS:
10550     case ARMMMUIdx_S1E2:
10551         return 2;
10552     case ARMMMUIdx_S1E3:
10553         return 3;
10554     case ARMMMUIdx_S1SE0:
10555         return arm_el_is_aa64(env, 3) ? 1 : 3;
10556     case ARMMMUIdx_S1SE1:
10557     case ARMMMUIdx_S1NSE0:
10558     case ARMMMUIdx_S1NSE1:
10559     case ARMMMUIdx_MPrivNegPri:
10560     case ARMMMUIdx_MUserNegPri:
10561     case ARMMMUIdx_MPriv:
10562     case ARMMMUIdx_MUser:
10563     case ARMMMUIdx_MSPrivNegPri:
10564     case ARMMMUIdx_MSUserNegPri:
10565     case ARMMMUIdx_MSPriv:
10566     case ARMMMUIdx_MSUser:
10567         return 1;
10568     default:
10569         g_assert_not_reached();
10570     }
10571 }
10572
10573 #ifndef CONFIG_USER_ONLY
10574
10575 /* Return the SCTLR value which controls this address translation regime */
10576 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10577 {
10578     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10579 }
10580
10581 /* Return true if the specified stage of address translation is disabled */
10582 static inline bool regime_translation_disabled(CPUARMState *env,
10583                                                ARMMMUIdx mmu_idx)
10584 {
10585     if (arm_feature(env, ARM_FEATURE_M)) {
10586         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10587                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10588         case R_V7M_MPU_CTRL_ENABLE_MASK:
10589             /* Enabled, but not for HardFault and NMI */
10590             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10591         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10592             /* Enabled for all cases */
10593             return false;
10594         case 0:
10595         default:
10596             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10597              * we warned about that in armv7m_nvic.c when the guest set it.
10598              */
10599             return true;
10600         }
10601     }
10602
10603     if (mmu_idx == ARMMMUIdx_S2NS) {
10604         /* HCR.DC means HCR.VM behaves as 1 */
10605         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10606     }
10607
10608     if (env->cp15.hcr_el2 & HCR_TGE) {
10609         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10610         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10611             return true;
10612         }
10613     }
10614
10615     if ((env->cp15.hcr_el2 & HCR_DC) &&
10616         (mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1)) {
10617         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10618         return true;
10619     }
10620
10621     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10622 }
10623
10624 static inline bool regime_translation_big_endian(CPUARMState *env,
10625                                                  ARMMMUIdx mmu_idx)
10626 {
10627     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10628 }
10629
10630 /* Return the TTBR associated with this translation regime */
10631 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10632                                    int ttbrn)
10633 {
10634     if (mmu_idx == ARMMMUIdx_S2NS) {
10635         return env->cp15.vttbr_el2;
10636     }
10637     if (ttbrn == 0) {
10638         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10639     } else {
10640         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10641     }
10642 }
10643
10644 #endif /* !CONFIG_USER_ONLY */
10645
10646 /* Return the TCR controlling this translation regime */
10647 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
10648 {
10649     if (mmu_idx == ARMMMUIdx_S2NS) {
10650         return &env->cp15.vtcr_el2;
10651     }
10652     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
10653 }
10654
10655 /* Convert a possible stage1+2 MMU index into the appropriate
10656  * stage 1 MMU index
10657  */
10658 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10659 {
10660     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10661         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
10662     }
10663     return mmu_idx;
10664 }
10665
10666 /* Return true if the translation regime is using LPAE format page tables */
10667 static inline bool regime_using_lpae_format(CPUARMState *env,
10668                                             ARMMMUIdx mmu_idx)
10669 {
10670     int el = regime_el(env, mmu_idx);
10671     if (el == 2 || arm_el_is_aa64(env, el)) {
10672         return true;
10673     }
10674     if (arm_feature(env, ARM_FEATURE_LPAE)
10675         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10676         return true;
10677     }
10678     return false;
10679 }
10680
10681 /* Returns true if the stage 1 translation regime is using LPAE format page
10682  * tables. Used when raising alignment exceptions, whose FSR changes depending
10683  * on whether the long or short descriptor format is in use. */
10684 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10685 {
10686     mmu_idx = stage_1_mmu_idx(mmu_idx);
10687
10688     return regime_using_lpae_format(env, mmu_idx);
10689 }
10690
10691 #ifndef CONFIG_USER_ONLY
10692 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10693 {
10694     switch (mmu_idx) {
10695     case ARMMMUIdx_S1SE0:
10696     case ARMMMUIdx_S1NSE0:
10697     case ARMMMUIdx_MUser:
10698     case ARMMMUIdx_MSUser:
10699     case ARMMMUIdx_MUserNegPri:
10700     case ARMMMUIdx_MSUserNegPri:
10701         return true;
10702     default:
10703         return false;
10704     case ARMMMUIdx_S12NSE0:
10705     case ARMMMUIdx_S12NSE1:
10706         g_assert_not_reached();
10707     }
10708 }
10709
10710 /* Translate section/page access permissions to page
10711  * R/W protection flags
10712  *
10713  * @env:         CPUARMState
10714  * @mmu_idx:     MMU index indicating required translation regime
10715  * @ap:          The 3-bit access permissions (AP[2:0])
10716  * @domain_prot: The 2-bit domain access permissions
10717  */
10718 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10719                                 int ap, int domain_prot)
10720 {
10721     bool is_user = regime_is_user(env, mmu_idx);
10722
10723     if (domain_prot == 3) {
10724         return PAGE_READ | PAGE_WRITE;
10725     }
10726
10727     switch (ap) {
10728     case 0:
10729         if (arm_feature(env, ARM_FEATURE_V7)) {
10730             return 0;
10731         }
10732         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10733         case SCTLR_S:
10734             return is_user ? 0 : PAGE_READ;
10735         case SCTLR_R:
10736             return PAGE_READ;
10737         default:
10738             return 0;
10739         }
10740     case 1:
10741         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10742     case 2:
10743         if (is_user) {
10744             return PAGE_READ;
10745         } else {
10746             return PAGE_READ | PAGE_WRITE;
10747         }
10748     case 3:
10749         return PAGE_READ | PAGE_WRITE;
10750     case 4: /* Reserved.  */
10751         return 0;
10752     case 5:
10753         return is_user ? 0 : PAGE_READ;
10754     case 6:
10755         return PAGE_READ;
10756     case 7:
10757         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10758             return 0;
10759         }
10760         return PAGE_READ;
10761     default:
10762         g_assert_not_reached();
10763     }
10764 }
10765
10766 /* Translate section/page access permissions to page
10767  * R/W protection flags.
10768  *
10769  * @ap:      The 2-bit simple AP (AP[2:1])
10770  * @is_user: TRUE if accessing from PL0
10771  */
10772 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10773 {
10774     switch (ap) {
10775     case 0:
10776         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10777     case 1:
10778         return PAGE_READ | PAGE_WRITE;
10779     case 2:
10780         return is_user ? 0 : PAGE_READ;
10781     case 3:
10782         return PAGE_READ;
10783     default:
10784         g_assert_not_reached();
10785     }
10786 }
10787
10788 static inline int
10789 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10790 {
10791     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10792 }
10793
10794 /* Translate S2 section/page access permissions to protection flags
10795  *
10796  * @env:     CPUARMState
10797  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10798  * @xn:      XN (execute-never) bit
10799  */
10800 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
10801 {
10802     int prot = 0;
10803
10804     if (s2ap & 1) {
10805         prot |= PAGE_READ;
10806     }
10807     if (s2ap & 2) {
10808         prot |= PAGE_WRITE;
10809     }
10810     if (!xn) {
10811         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10812             prot |= PAGE_EXEC;
10813         }
10814     }
10815     return prot;
10816 }
10817
10818 /* Translate section/page access permissions to protection flags
10819  *
10820  * @env:     CPUARMState
10821  * @mmu_idx: MMU index indicating required translation regime
10822  * @is_aa64: TRUE if AArch64
10823  * @ap:      The 2-bit simple AP (AP[2:1])
10824  * @ns:      NS (non-secure) bit
10825  * @xn:      XN (execute-never) bit
10826  * @pxn:     PXN (privileged execute-never) bit
10827  */
10828 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10829                       int ap, int ns, int xn, int pxn)
10830 {
10831     bool is_user = regime_is_user(env, mmu_idx);
10832     int prot_rw, user_rw;
10833     bool have_wxn;
10834     int wxn = 0;
10835
10836     assert(mmu_idx != ARMMMUIdx_S2NS);
10837
10838     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10839     if (is_user) {
10840         prot_rw = user_rw;
10841     } else {
10842         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10843     }
10844
10845     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10846         return prot_rw;
10847     }
10848
10849     /* TODO have_wxn should be replaced with
10850      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10851      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10852      * compatible processors have EL2, which is required for [U]WXN.
10853      */
10854     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10855
10856     if (have_wxn) {
10857         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10858     }
10859
10860     if (is_aa64) {
10861         switch (regime_el(env, mmu_idx)) {
10862         case 1:
10863             if (!is_user) {
10864                 xn = pxn || (user_rw & PAGE_WRITE);
10865             }
10866             break;
10867         case 2:
10868         case 3:
10869             break;
10870         }
10871     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10872         switch (regime_el(env, mmu_idx)) {
10873         case 1:
10874         case 3:
10875             if (is_user) {
10876                 xn = xn || !(user_rw & PAGE_READ);
10877             } else {
10878                 int uwxn = 0;
10879                 if (have_wxn) {
10880                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10881                 }
10882                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10883                      (uwxn && (user_rw & PAGE_WRITE));
10884             }
10885             break;
10886         case 2:
10887             break;
10888         }
10889     } else {
10890         xn = wxn = 0;
10891     }
10892
10893     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10894         return prot_rw;
10895     }
10896     return prot_rw | PAGE_EXEC;
10897 }
10898
10899 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10900                                      uint32_t *table, uint32_t address)
10901 {
10902     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10903     TCR *tcr = regime_tcr(env, mmu_idx);
10904
10905     if (address & tcr->mask) {
10906         if (tcr->raw_tcr & TTBCR_PD1) {
10907             /* Translation table walk disabled for TTBR1 */
10908             return false;
10909         }
10910         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10911     } else {
10912         if (tcr->raw_tcr & TTBCR_PD0) {
10913             /* Translation table walk disabled for TTBR0 */
10914             return false;
10915         }
10916         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10917     }
10918     *table |= (address >> 18) & 0x3ffc;
10919     return true;
10920 }
10921
10922 /* Translate a S1 pagetable walk through S2 if needed.  */
10923 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10924                                hwaddr addr, MemTxAttrs txattrs,
10925                                ARMMMUFaultInfo *fi)
10926 {
10927     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
10928         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10929         target_ulong s2size;
10930         hwaddr s2pa;
10931         int s2prot;
10932         int ret;
10933         ARMCacheAttrs cacheattrs = {};
10934         ARMCacheAttrs *pcacheattrs = NULL;
10935
10936         if (env->cp15.hcr_el2 & HCR_PTW) {
10937             /*
10938              * PTW means we must fault if this S1 walk touches S2 Device
10939              * memory; otherwise we don't care about the attributes and can
10940              * save the S2 translation the effort of computing them.
10941              */
10942             pcacheattrs = &cacheattrs;
10943         }
10944
10945         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
10946                                  &txattrs, &s2prot, &s2size, fi, pcacheattrs);
10947         if (ret) {
10948             assert(fi->type != ARMFault_None);
10949             fi->s2addr = addr;
10950             fi->stage2 = true;
10951             fi->s1ptw = true;
10952             return ~0;
10953         }
10954         if (pcacheattrs && (pcacheattrs->attrs & 0xf0) == 0) {
10955             /* Access was to Device memory: generate Permission fault */
10956             fi->type = ARMFault_Permission;
10957             fi->s2addr = addr;
10958             fi->stage2 = true;
10959             fi->s1ptw = true;
10960             return ~0;
10961         }
10962         addr = s2pa;
10963     }
10964     return addr;
10965 }
10966
10967 /* All loads done in the course of a page table walk go through here. */
10968 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10969                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10970 {
10971     ARMCPU *cpu = ARM_CPU(cs);
10972     CPUARMState *env = &cpu->env;
10973     MemTxAttrs attrs = {};
10974     MemTxResult result = MEMTX_OK;
10975     AddressSpace *as;
10976     uint32_t data;
10977
10978     attrs.secure = is_secure;
10979     as = arm_addressspace(cs, attrs);
10980     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10981     if (fi->s1ptw) {
10982         return 0;
10983     }
10984     if (regime_translation_big_endian(env, mmu_idx)) {
10985         data = address_space_ldl_be(as, addr, attrs, &result);
10986     } else {
10987         data = address_space_ldl_le(as, addr, attrs, &result);
10988     }
10989     if (result == MEMTX_OK) {
10990         return data;
10991     }
10992     fi->type = ARMFault_SyncExternalOnWalk;
10993     fi->ea = arm_extabort_type(result);
10994     return 0;
10995 }
10996
10997 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10998                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10999 {
11000     ARMCPU *cpu = ARM_CPU(cs);
11001     CPUARMState *env = &cpu->env;
11002     MemTxAttrs attrs = {};
11003     MemTxResult result = MEMTX_OK;
11004     AddressSpace *as;
11005     uint64_t data;
11006
11007     attrs.secure = is_secure;
11008     as = arm_addressspace(cs, attrs);
11009     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
11010     if (fi->s1ptw) {
11011         return 0;
11012     }
11013     if (regime_translation_big_endian(env, mmu_idx)) {
11014         data = address_space_ldq_be(as, addr, attrs, &result);
11015     } else {
11016         data = address_space_ldq_le(as, addr, attrs, &result);
11017     }
11018     if (result == MEMTX_OK) {
11019         return data;
11020     }
11021     fi->type = ARMFault_SyncExternalOnWalk;
11022     fi->ea = arm_extabort_type(result);
11023     return 0;
11024 }
11025
11026 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
11027                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
11028                              hwaddr *phys_ptr, int *prot,
11029                              target_ulong *page_size,
11030                              ARMMMUFaultInfo *fi)
11031 {
11032     CPUState *cs = env_cpu(env);
11033     int level = 1;
11034     uint32_t table;
11035     uint32_t desc;
11036     int type;
11037     int ap;
11038     int domain = 0;
11039     int domain_prot;
11040     hwaddr phys_addr;
11041     uint32_t dacr;
11042
11043     /* Pagetable walk.  */
11044     /* Lookup l1 descriptor.  */
11045     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
11046         /* Section translation fault if page walk is disabled by PD0 or PD1 */
11047         fi->type = ARMFault_Translation;
11048         goto do_fault;
11049     }
11050     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11051                        mmu_idx, fi);
11052     if (fi->type != ARMFault_None) {
11053         goto do_fault;
11054     }
11055     type = (desc & 3);
11056     domain = (desc >> 5) & 0x0f;
11057     if (regime_el(env, mmu_idx) == 1) {
11058         dacr = env->cp15.dacr_ns;
11059     } else {
11060         dacr = env->cp15.dacr_s;
11061     }
11062     domain_prot = (dacr >> (domain * 2)) & 3;
11063     if (type == 0) {
11064         /* Section translation fault.  */
11065         fi->type = ARMFault_Translation;
11066         goto do_fault;
11067     }
11068     if (type != 2) {
11069         level = 2;
11070     }
11071     if (domain_prot == 0 || domain_prot == 2) {
11072         fi->type = ARMFault_Domain;
11073         goto do_fault;
11074     }
11075     if (type == 2) {
11076         /* 1Mb section.  */
11077         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
11078         ap = (desc >> 10) & 3;
11079         *page_size = 1024 * 1024;
11080     } else {
11081         /* Lookup l2 entry.  */
11082         if (type == 1) {
11083             /* Coarse pagetable.  */
11084             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11085         } else {
11086             /* Fine pagetable.  */
11087             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
11088         }
11089         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11090                            mmu_idx, fi);
11091         if (fi->type != ARMFault_None) {
11092             goto do_fault;
11093         }
11094         switch (desc & 3) {
11095         case 0: /* Page translation fault.  */
11096             fi->type = ARMFault_Translation;
11097             goto do_fault;
11098         case 1: /* 64k page.  */
11099             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11100             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
11101             *page_size = 0x10000;
11102             break;
11103         case 2: /* 4k page.  */
11104             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11105             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
11106             *page_size = 0x1000;
11107             break;
11108         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
11109             if (type == 1) {
11110                 /* ARMv6/XScale extended small page format */
11111                 if (arm_feature(env, ARM_FEATURE_XSCALE)
11112                     || arm_feature(env, ARM_FEATURE_V6)) {
11113                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11114                     *page_size = 0x1000;
11115                 } else {
11116                     /* UNPREDICTABLE in ARMv5; we choose to take a
11117                      * page translation fault.
11118                      */
11119                     fi->type = ARMFault_Translation;
11120                     goto do_fault;
11121                 }
11122             } else {
11123                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
11124                 *page_size = 0x400;
11125             }
11126             ap = (desc >> 4) & 3;
11127             break;
11128         default:
11129             /* Never happens, but compiler isn't smart enough to tell.  */
11130             abort();
11131         }
11132     }
11133     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11134     *prot |= *prot ? PAGE_EXEC : 0;
11135     if (!(*prot & (1 << access_type))) {
11136         /* Access permission fault.  */
11137         fi->type = ARMFault_Permission;
11138         goto do_fault;
11139     }
11140     *phys_ptr = phys_addr;
11141     return false;
11142 do_fault:
11143     fi->domain = domain;
11144     fi->level = level;
11145     return true;
11146 }
11147
11148 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
11149                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
11150                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
11151                              target_ulong *page_size, ARMMMUFaultInfo *fi)
11152 {
11153     CPUState *cs = env_cpu(env);
11154     int level = 1;
11155     uint32_t table;
11156     uint32_t desc;
11157     uint32_t xn;
11158     uint32_t pxn = 0;
11159     int type;
11160     int ap;
11161     int domain = 0;
11162     int domain_prot;
11163     hwaddr phys_addr;
11164     uint32_t dacr;
11165     bool ns;
11166
11167     /* Pagetable walk.  */
11168     /* Lookup l1 descriptor.  */
11169     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
11170         /* Section translation fault if page walk is disabled by PD0 or PD1 */
11171         fi->type = ARMFault_Translation;
11172         goto do_fault;
11173     }
11174     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11175                        mmu_idx, fi);
11176     if (fi->type != ARMFault_None) {
11177         goto do_fault;
11178     }
11179     type = (desc & 3);
11180     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
11181         /* Section translation fault, or attempt to use the encoding
11182          * which is Reserved on implementations without PXN.
11183          */
11184         fi->type = ARMFault_Translation;
11185         goto do_fault;
11186     }
11187     if ((type == 1) || !(desc & (1 << 18))) {
11188         /* Page or Section.  */
11189         domain = (desc >> 5) & 0x0f;
11190     }
11191     if (regime_el(env, mmu_idx) == 1) {
11192         dacr = env->cp15.dacr_ns;
11193     } else {
11194         dacr = env->cp15.dacr_s;
11195     }
11196     if (type == 1) {
11197         level = 2;
11198     }
11199     domain_prot = (dacr >> (domain * 2)) & 3;
11200     if (domain_prot == 0 || domain_prot == 2) {
11201         /* Section or Page domain fault */
11202         fi->type = ARMFault_Domain;
11203         goto do_fault;
11204     }
11205     if (type != 1) {
11206         if (desc & (1 << 18)) {
11207             /* Supersection.  */
11208             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
11209             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
11210             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
11211             *page_size = 0x1000000;
11212         } else {
11213             /* Section.  */
11214             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
11215             *page_size = 0x100000;
11216         }
11217         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
11218         xn = desc & (1 << 4);
11219         pxn = desc & 1;
11220         ns = extract32(desc, 19, 1);
11221     } else {
11222         if (arm_feature(env, ARM_FEATURE_PXN)) {
11223             pxn = (desc >> 2) & 1;
11224         }
11225         ns = extract32(desc, 3, 1);
11226         /* Lookup l2 entry.  */
11227         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11228         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11229                            mmu_idx, fi);
11230         if (fi->type != ARMFault_None) {
11231             goto do_fault;
11232         }
11233         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
11234         switch (desc & 3) {
11235         case 0: /* Page translation fault.  */
11236             fi->type = ARMFault_Translation;
11237             goto do_fault;
11238         case 1: /* 64k page.  */
11239             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11240             xn = desc & (1 << 15);
11241             *page_size = 0x10000;
11242             break;
11243         case 2: case 3: /* 4k page.  */
11244             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11245             xn = desc & 1;
11246             *page_size = 0x1000;
11247             break;
11248         default:
11249             /* Never happens, but compiler isn't smart enough to tell.  */
11250             abort();
11251         }
11252     }
11253     if (domain_prot == 3) {
11254         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11255     } else {
11256         if (pxn && !regime_is_user(env, mmu_idx)) {
11257             xn = 1;
11258         }
11259         if (xn && access_type == MMU_INST_FETCH) {
11260             fi->type = ARMFault_Permission;
11261             goto do_fault;
11262         }
11263
11264         if (arm_feature(env, ARM_FEATURE_V6K) &&
11265                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
11266             /* The simplified model uses AP[0] as an access control bit.  */
11267             if ((ap & 1) == 0) {
11268                 /* Access flag fault.  */
11269                 fi->type = ARMFault_AccessFlag;
11270                 goto do_fault;
11271             }
11272             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
11273         } else {
11274             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11275         }
11276         if (*prot && !xn) {
11277             *prot |= PAGE_EXEC;
11278         }
11279         if (!(*prot & (1 << access_type))) {
11280             /* Access permission fault.  */
11281             fi->type = ARMFault_Permission;
11282             goto do_fault;
11283         }
11284     }
11285     if (ns) {
11286         /* The NS bit will (as required by the architecture) have no effect if
11287          * the CPU doesn't support TZ or this is a non-secure translation
11288          * regime, because the attribute will already be non-secure.
11289          */
11290         attrs->secure = false;
11291     }
11292     *phys_ptr = phys_addr;
11293     return false;
11294 do_fault:
11295     fi->domain = domain;
11296     fi->level = level;
11297     return true;
11298 }
11299
11300 /*
11301  * check_s2_mmu_setup
11302  * @cpu:        ARMCPU
11303  * @is_aa64:    True if the translation regime is in AArch64 state
11304  * @startlevel: Suggested starting level
11305  * @inputsize:  Bitsize of IPAs
11306  * @stride:     Page-table stride (See the ARM ARM)
11307  *
11308  * Returns true if the suggested S2 translation parameters are OK and
11309  * false otherwise.
11310  */
11311 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
11312                                int inputsize, int stride)
11313 {
11314     const int grainsize = stride + 3;
11315     int startsizecheck;
11316
11317     /* Negative levels are never allowed.  */
11318     if (level < 0) {
11319         return false;
11320     }
11321
11322     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
11323     if (startsizecheck < 1 || startsizecheck > stride + 4) {
11324         return false;
11325     }
11326
11327     if (is_aa64) {
11328         CPUARMState *env = &cpu->env;
11329         unsigned int pamax = arm_pamax(cpu);
11330
11331         switch (stride) {
11332         case 13: /* 64KB Pages.  */
11333             if (level == 0 || (level == 1 && pamax <= 42)) {
11334                 return false;
11335             }
11336             break;
11337         case 11: /* 16KB Pages.  */
11338             if (level == 0 || (level == 1 && pamax <= 40)) {
11339                 return false;
11340             }
11341             break;
11342         case 9: /* 4KB Pages.  */
11343             if (level == 0 && pamax <= 42) {
11344                 return false;
11345             }
11346             break;
11347         default:
11348             g_assert_not_reached();
11349         }
11350
11351         /* Inputsize checks.  */
11352         if (inputsize > pamax &&
11353             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
11354             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
11355             return false;
11356         }
11357     } else {
11358         /* AArch32 only supports 4KB pages. Assert on that.  */
11359         assert(stride == 9);
11360
11361         if (level == 0) {
11362             return false;
11363         }
11364     }
11365     return true;
11366 }
11367
11368 /* Translate from the 4-bit stage 2 representation of
11369  * memory attributes (without cache-allocation hints) to
11370  * the 8-bit representation of the stage 1 MAIR registers
11371  * (which includes allocation hints).
11372  *
11373  * ref: shared/translation/attrs/S2AttrDecode()
11374  *      .../S2ConvertAttrsHints()
11375  */
11376 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11377 {
11378     uint8_t hiattr = extract32(s2attrs, 2, 2);
11379     uint8_t loattr = extract32(s2attrs, 0, 2);
11380     uint8_t hihint = 0, lohint = 0;
11381
11382     if (hiattr != 0) { /* normal memory */
11383         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
11384             hiattr = loattr = 1; /* non-cacheable */
11385         } else {
11386             if (hiattr != 1) { /* Write-through or write-back */
11387                 hihint = 3; /* RW allocate */
11388             }
11389             if (loattr != 1) { /* Write-through or write-back */
11390                 lohint = 3; /* RW allocate */
11391             }
11392         }
11393     }
11394
11395     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11396 }
11397 #endif /* !CONFIG_USER_ONLY */
11398
11399 ARMVAParameters aa64_va_parameters_both(CPUARMState *env, uint64_t va,
11400                                         ARMMMUIdx mmu_idx)
11401 {
11402     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11403     uint32_t el = regime_el(env, mmu_idx);
11404     bool tbi, tbid, epd, hpd, using16k, using64k;
11405     int select, tsz;
11406
11407     /*
11408      * Bit 55 is always between the two regions, and is canonical for
11409      * determining if address tagging is enabled.
11410      */
11411     select = extract64(va, 55, 1);
11412
11413     if (el > 1) {
11414         tsz = extract32(tcr, 0, 6);
11415         using64k = extract32(tcr, 14, 1);
11416         using16k = extract32(tcr, 15, 1);
11417         if (mmu_idx == ARMMMUIdx_S2NS) {
11418             /* VTCR_EL2 */
11419             tbi = tbid = hpd = false;
11420         } else {
11421             tbi = extract32(tcr, 20, 1);
11422             hpd = extract32(tcr, 24, 1);
11423             tbid = extract32(tcr, 29, 1);
11424         }
11425         epd = false;
11426     } else if (!select) {
11427         tsz = extract32(tcr, 0, 6);
11428         epd = extract32(tcr, 7, 1);
11429         using64k = extract32(tcr, 14, 1);
11430         using16k = extract32(tcr, 15, 1);
11431         tbi = extract64(tcr, 37, 1);
11432         hpd = extract64(tcr, 41, 1);
11433         tbid = extract64(tcr, 51, 1);
11434     } else {
11435         int tg = extract32(tcr, 30, 2);
11436         using16k = tg == 1;
11437         using64k = tg == 3;
11438         tsz = extract32(tcr, 16, 6);
11439         epd = extract32(tcr, 23, 1);
11440         tbi = extract64(tcr, 38, 1);
11441         hpd = extract64(tcr, 42, 1);
11442         tbid = extract64(tcr, 52, 1);
11443     }
11444     tsz = MIN(tsz, 39);  /* TODO: ARMv8.4-TTST */
11445     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
11446
11447     return (ARMVAParameters) {
11448         .tsz = tsz,
11449         .select = select,
11450         .tbi = tbi,
11451         .tbid = tbid,
11452         .epd = epd,
11453         .hpd = hpd,
11454         .using16k = using16k,
11455         .using64k = using64k,
11456     };
11457 }
11458
11459 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11460                                    ARMMMUIdx mmu_idx, bool data)
11461 {
11462     ARMVAParameters ret = aa64_va_parameters_both(env, va, mmu_idx);
11463
11464     /* Present TBI as a composite with TBID.  */
11465     ret.tbi &= (data || !ret.tbid);
11466     return ret;
11467 }
11468
11469 #ifndef CONFIG_USER_ONLY
11470 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11471                                           ARMMMUIdx mmu_idx)
11472 {
11473     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11474     uint32_t el = regime_el(env, mmu_idx);
11475     int select, tsz;
11476     bool epd, hpd;
11477
11478     if (mmu_idx == ARMMMUIdx_S2NS) {
11479         /* VTCR */
11480         bool sext = extract32(tcr, 4, 1);
11481         bool sign = extract32(tcr, 3, 1);
11482
11483         /*
11484          * If the sign-extend bit is not the same as t0sz[3], the result
11485          * is unpredictable. Flag this as a guest error.
11486          */
11487         if (sign != sext) {
11488             qemu_log_mask(LOG_GUEST_ERROR,
11489                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11490         }
11491         tsz = sextract32(tcr, 0, 4) + 8;
11492         select = 0;
11493         hpd = false;
11494         epd = false;
11495     } else if (el == 2) {
11496         /* HTCR */
11497         tsz = extract32(tcr, 0, 3);
11498         select = 0;
11499         hpd = extract64(tcr, 24, 1);
11500         epd = false;
11501     } else {
11502         int t0sz = extract32(tcr, 0, 3);
11503         int t1sz = extract32(tcr, 16, 3);
11504
11505         if (t1sz == 0) {
11506             select = va > (0xffffffffu >> t0sz);
11507         } else {
11508             /* Note that we will detect errors later.  */
11509             select = va >= ~(0xffffffffu >> t1sz);
11510         }
11511         if (!select) {
11512             tsz = t0sz;
11513             epd = extract32(tcr, 7, 1);
11514             hpd = extract64(tcr, 41, 1);
11515         } else {
11516             tsz = t1sz;
11517             epd = extract32(tcr, 23, 1);
11518             hpd = extract64(tcr, 42, 1);
11519         }
11520         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11521         hpd &= extract32(tcr, 6, 1);
11522     }
11523
11524     return (ARMVAParameters) {
11525         .tsz = tsz,
11526         .select = select,
11527         .epd = epd,
11528         .hpd = hpd,
11529     };
11530 }
11531
11532 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
11533                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11534                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11535                                target_ulong *page_size_ptr,
11536                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11537 {
11538     ARMCPU *cpu = env_archcpu(env);
11539     CPUState *cs = CPU(cpu);
11540     /* Read an LPAE long-descriptor translation table. */
11541     ARMFaultType fault_type = ARMFault_Translation;
11542     uint32_t level;
11543     ARMVAParameters param;
11544     uint64_t ttbr;
11545     hwaddr descaddr, indexmask, indexmask_grainsize;
11546     uint32_t tableattrs;
11547     target_ulong page_size;
11548     uint32_t attrs;
11549     int32_t stride;
11550     int addrsize, inputsize;
11551     TCR *tcr = regime_tcr(env, mmu_idx);
11552     int ap, ns, xn, pxn;
11553     uint32_t el = regime_el(env, mmu_idx);
11554     bool ttbr1_valid;
11555     uint64_t descaddrmask;
11556     bool aarch64 = arm_el_is_aa64(env, el);
11557     bool guarded = false;
11558
11559     /* TODO:
11560      * This code does not handle the different format TCR for VTCR_EL2.
11561      * This code also does not support shareability levels.
11562      * Attribute and permission bit handling should also be checked when adding
11563      * support for those page table walks.
11564      */
11565     if (aarch64) {
11566         param = aa64_va_parameters(env, address, mmu_idx,
11567                                    access_type != MMU_INST_FETCH);
11568         level = 0;
11569         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
11570          * invalid.
11571          */
11572         ttbr1_valid = (el < 2);
11573         addrsize = 64 - 8 * param.tbi;
11574         inputsize = 64 - param.tsz;
11575     } else {
11576         param = aa32_va_parameters(env, address, mmu_idx);
11577         level = 1;
11578         /* There is no TTBR1 for EL2 */
11579         ttbr1_valid = (el != 2);
11580         addrsize = (mmu_idx == ARMMMUIdx_S2NS ? 40 : 32);
11581         inputsize = addrsize - param.tsz;
11582     }
11583
11584     /*
11585      * We determined the region when collecting the parameters, but we
11586      * have not yet validated that the address is valid for the region.
11587      * Extract the top bits and verify that they all match select.
11588      *
11589      * For aa32, if inputsize == addrsize, then we have selected the
11590      * region by exclusion in aa32_va_parameters and there is no more
11591      * validation to do here.
11592      */
11593     if (inputsize < addrsize) {
11594         target_ulong top_bits = sextract64(address, inputsize,
11595                                            addrsize - inputsize);
11596         if (-top_bits != param.select || (param.select && !ttbr1_valid)) {
11597             /* The gap between the two regions is a Translation fault */
11598             fault_type = ARMFault_Translation;
11599             goto do_fault;
11600         }
11601     }
11602
11603     if (param.using64k) {
11604         stride = 13;
11605     } else if (param.using16k) {
11606         stride = 11;
11607     } else {
11608         stride = 9;
11609     }
11610
11611     /* Note that QEMU ignores shareability and cacheability attributes,
11612      * so we don't need to do anything with the SH, ORGN, IRGN fields
11613      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11614      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11615      * implement any ASID-like capability so we can ignore it (instead
11616      * we will always flush the TLB any time the ASID is changed).
11617      */
11618     ttbr = regime_ttbr(env, mmu_idx, param.select);
11619
11620     /* Here we should have set up all the parameters for the translation:
11621      * inputsize, ttbr, epd, stride, tbi
11622      */
11623
11624     if (param.epd) {
11625         /* Translation table walk disabled => Translation fault on TLB miss
11626          * Note: This is always 0 on 64-bit EL2 and EL3.
11627          */
11628         goto do_fault;
11629     }
11630
11631     if (mmu_idx != ARMMMUIdx_S2NS) {
11632         /* The starting level depends on the virtual address size (which can
11633          * be up to 48 bits) and the translation granule size. It indicates
11634          * the number of strides (stride bits at a time) needed to
11635          * consume the bits of the input address. In the pseudocode this is:
11636          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11637          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11638          * our 'stride + 3' and 'stride' is our 'stride'.
11639          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11640          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11641          * = 4 - (inputsize - 4) / stride;
11642          */
11643         level = 4 - (inputsize - 4) / stride;
11644     } else {
11645         /* For stage 2 translations the starting level is specified by the
11646          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11647          */
11648         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11649         uint32_t startlevel;
11650         bool ok;
11651
11652         if (!aarch64 || stride == 9) {
11653             /* AArch32 or 4KB pages */
11654             startlevel = 2 - sl0;
11655         } else {
11656             /* 16KB or 64KB pages */
11657             startlevel = 3 - sl0;
11658         }
11659
11660         /* Check that the starting level is valid. */
11661         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11662                                 inputsize, stride);
11663         if (!ok) {
11664             fault_type = ARMFault_Translation;
11665             goto do_fault;
11666         }
11667         level = startlevel;
11668     }
11669
11670     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
11671     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
11672
11673     /* Now we can extract the actual base address from the TTBR */
11674     descaddr = extract64(ttbr, 0, 48);
11675     descaddr &= ~indexmask;
11676
11677     /* The address field in the descriptor goes up to bit 39 for ARMv7
11678      * but up to bit 47 for ARMv8, but we use the descaddrmask
11679      * up to bit 39 for AArch32, because we don't need other bits in that case
11680      * to construct next descriptor address (anyway they should be all zeroes).
11681      */
11682     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
11683                    ~indexmask_grainsize;
11684
11685     /* Secure accesses start with the page table in secure memory and
11686      * can be downgraded to non-secure at any step. Non-secure accesses
11687      * remain non-secure. We implement this by just ORing in the NSTable/NS
11688      * bits at each step.
11689      */
11690     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11691     for (;;) {
11692         uint64_t descriptor;
11693         bool nstable;
11694
11695         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11696         descaddr &= ~7ULL;
11697         nstable = extract32(tableattrs, 4, 1);
11698         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11699         if (fi->type != ARMFault_None) {
11700             goto do_fault;
11701         }
11702
11703         if (!(descriptor & 1) ||
11704             (!(descriptor & 2) && (level == 3))) {
11705             /* Invalid, or the Reserved level 3 encoding */
11706             goto do_fault;
11707         }
11708         descaddr = descriptor & descaddrmask;
11709
11710         if ((descriptor & 2) && (level < 3)) {
11711             /* Table entry. The top five bits are attributes which may
11712              * propagate down through lower levels of the table (and
11713              * which are all arranged so that 0 means "no effect", so
11714              * we can gather them up by ORing in the bits at each level).
11715              */
11716             tableattrs |= extract64(descriptor, 59, 5);
11717             level++;
11718             indexmask = indexmask_grainsize;
11719             continue;
11720         }
11721         /* Block entry at level 1 or 2, or page entry at level 3.
11722          * These are basically the same thing, although the number
11723          * of bits we pull in from the vaddr varies.
11724          */
11725         page_size = (1ULL << ((stride * (4 - level)) + 3));
11726         descaddr |= (address & (page_size - 1));
11727         /* Extract attributes from the descriptor */
11728         attrs = extract64(descriptor, 2, 10)
11729             | (extract64(descriptor, 52, 12) << 10);
11730
11731         if (mmu_idx == ARMMMUIdx_S2NS) {
11732             /* Stage 2 table descriptors do not include any attribute fields */
11733             break;
11734         }
11735         /* Merge in attributes from table descriptors */
11736         attrs |= nstable << 3; /* NS */
11737         guarded = extract64(descriptor, 50, 1);  /* GP */
11738         if (param.hpd) {
11739             /* HPD disables all the table attributes except NSTable.  */
11740             break;
11741         }
11742         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11743         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11744          * means "force PL1 access only", which means forcing AP[1] to 0.
11745          */
11746         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11747         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11748         break;
11749     }
11750     /* Here descaddr is the final physical address, and attributes
11751      * are all in attrs.
11752      */
11753     fault_type = ARMFault_AccessFlag;
11754     if ((attrs & (1 << 8)) == 0) {
11755         /* Access flag */
11756         goto do_fault;
11757     }
11758
11759     ap = extract32(attrs, 4, 2);
11760     xn = extract32(attrs, 12, 1);
11761
11762     if (mmu_idx == ARMMMUIdx_S2NS) {
11763         ns = true;
11764         *prot = get_S2prot(env, ap, xn);
11765     } else {
11766         ns = extract32(attrs, 3, 1);
11767         pxn = extract32(attrs, 11, 1);
11768         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11769     }
11770
11771     fault_type = ARMFault_Permission;
11772     if (!(*prot & (1 << access_type))) {
11773         goto do_fault;
11774     }
11775
11776     if (ns) {
11777         /* The NS bit will (as required by the architecture) have no effect if
11778          * the CPU doesn't support TZ or this is a non-secure translation
11779          * regime, because the attribute will already be non-secure.
11780          */
11781         txattrs->secure = false;
11782     }
11783     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11784     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11785         txattrs->target_tlb_bit0 = true;
11786     }
11787
11788     if (cacheattrs != NULL) {
11789         if (mmu_idx == ARMMMUIdx_S2NS) {
11790             cacheattrs->attrs = convert_stage2_attrs(env,
11791                                                      extract32(attrs, 0, 4));
11792         } else {
11793             /* Index into MAIR registers for cache attributes */
11794             uint8_t attrindx = extract32(attrs, 0, 3);
11795             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11796             assert(attrindx <= 7);
11797             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11798         }
11799         cacheattrs->shareability = extract32(attrs, 6, 2);
11800     }
11801
11802     *phys_ptr = descaddr;
11803     *page_size_ptr = page_size;
11804     return false;
11805
11806 do_fault:
11807     fi->type = fault_type;
11808     fi->level = level;
11809     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11810     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
11811     return true;
11812 }
11813
11814 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11815                                                 ARMMMUIdx mmu_idx,
11816                                                 int32_t address, int *prot)
11817 {
11818     if (!arm_feature(env, ARM_FEATURE_M)) {
11819         *prot = PAGE_READ | PAGE_WRITE;
11820         switch (address) {
11821         case 0xF0000000 ... 0xFFFFFFFF:
11822             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11823                 /* hivecs execing is ok */
11824                 *prot |= PAGE_EXEC;
11825             }
11826             break;
11827         case 0x00000000 ... 0x7FFFFFFF:
11828             *prot |= PAGE_EXEC;
11829             break;
11830         }
11831     } else {
11832         /* Default system address map for M profile cores.
11833          * The architecture specifies which regions are execute-never;
11834          * at the MPU level no other checks are defined.
11835          */
11836         switch (address) {
11837         case 0x00000000 ... 0x1fffffff: /* ROM */
11838         case 0x20000000 ... 0x3fffffff: /* SRAM */
11839         case 0x60000000 ... 0x7fffffff: /* RAM */
11840         case 0x80000000 ... 0x9fffffff: /* RAM */
11841             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11842             break;
11843         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11844         case 0xa0000000 ... 0xbfffffff: /* Device */
11845         case 0xc0000000 ... 0xdfffffff: /* Device */
11846         case 0xe0000000 ... 0xffffffff: /* System */
11847             *prot = PAGE_READ | PAGE_WRITE;
11848             break;
11849         default:
11850             g_assert_not_reached();
11851         }
11852     }
11853 }
11854
11855 static bool pmsav7_use_background_region(ARMCPU *cpu,
11856                                          ARMMMUIdx mmu_idx, bool is_user)
11857 {
11858     /* Return true if we should use the default memory map as a
11859      * "background" region if there are no hits against any MPU regions.
11860      */
11861     CPUARMState *env = &cpu->env;
11862
11863     if (is_user) {
11864         return false;
11865     }
11866
11867     if (arm_feature(env, ARM_FEATURE_M)) {
11868         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11869             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11870     } else {
11871         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11872     }
11873 }
11874
11875 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11876 {
11877     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11878     return arm_feature(env, ARM_FEATURE_M) &&
11879         extract32(address, 20, 12) == 0xe00;
11880 }
11881
11882 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11883 {
11884     /* True if address is in the M profile system region
11885      * 0xe0000000 - 0xffffffff
11886      */
11887     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11888 }
11889
11890 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11891                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11892                                  hwaddr *phys_ptr, int *prot,
11893                                  target_ulong *page_size,
11894                                  ARMMMUFaultInfo *fi)
11895 {
11896     ARMCPU *cpu = env_archcpu(env);
11897     int n;
11898     bool is_user = regime_is_user(env, mmu_idx);
11899
11900     *phys_ptr = address;
11901     *page_size = TARGET_PAGE_SIZE;
11902     *prot = 0;
11903
11904     if (regime_translation_disabled(env, mmu_idx) ||
11905         m_is_ppb_region(env, address)) {
11906         /* MPU disabled or M profile PPB access: use default memory map.
11907          * The other case which uses the default memory map in the
11908          * v7M ARM ARM pseudocode is exception vector reads from the vector
11909          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11910          * which always does a direct read using address_space_ldl(), rather
11911          * than going via this function, so we don't need to check that here.
11912          */
11913         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11914     } else { /* MPU enabled */
11915         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11916             /* region search */
11917             uint32_t base = env->pmsav7.drbar[n];
11918             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11919             uint32_t rmask;
11920             bool srdis = false;
11921
11922             if (!(env->pmsav7.drsr[n] & 0x1)) {
11923                 continue;
11924             }
11925
11926             if (!rsize) {
11927                 qemu_log_mask(LOG_GUEST_ERROR,
11928                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11929                 continue;
11930             }
11931             rsize++;
11932             rmask = (1ull << rsize) - 1;
11933
11934             if (base & rmask) {
11935                 qemu_log_mask(LOG_GUEST_ERROR,
11936                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11937                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11938                               n, base, rmask);
11939                 continue;
11940             }
11941
11942             if (address < base || address > base + rmask) {
11943                 /*
11944                  * Address not in this region. We must check whether the
11945                  * region covers addresses in the same page as our address.
11946                  * In that case we must not report a size that covers the
11947                  * whole page for a subsequent hit against a different MPU
11948                  * region or the background region, because it would result in
11949                  * incorrect TLB hits for subsequent accesses to addresses that
11950                  * are in this MPU region.
11951                  */
11952                 if (ranges_overlap(base, rmask,
11953                                    address & TARGET_PAGE_MASK,
11954                                    TARGET_PAGE_SIZE)) {
11955                     *page_size = 1;
11956                 }
11957                 continue;
11958             }
11959
11960             /* Region matched */
11961
11962             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11963                 int i, snd;
11964                 uint32_t srdis_mask;
11965
11966                 rsize -= 3; /* sub region size (power of 2) */
11967                 snd = ((address - base) >> rsize) & 0x7;
11968                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11969
11970                 srdis_mask = srdis ? 0x3 : 0x0;
11971                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11972                     /* This will check in groups of 2, 4 and then 8, whether
11973                      * the subregion bits are consistent. rsize is incremented
11974                      * back up to give the region size, considering consistent
11975                      * adjacent subregions as one region. Stop testing if rsize
11976                      * is already big enough for an entire QEMU page.
11977                      */
11978                     int snd_rounded = snd & ~(i - 1);
11979                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11980                                                      snd_rounded + 8, i);
11981                     if (srdis_mask ^ srdis_multi) {
11982                         break;
11983                     }
11984                     srdis_mask = (srdis_mask << i) | srdis_mask;
11985                     rsize++;
11986                 }
11987             }
11988             if (srdis) {
11989                 continue;
11990             }
11991             if (rsize < TARGET_PAGE_BITS) {
11992                 *page_size = 1 << rsize;
11993             }
11994             break;
11995         }
11996
11997         if (n == -1) { /* no hits */
11998             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11999                 /* background fault */
12000                 fi->type = ARMFault_Background;
12001                 return true;
12002             }
12003             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12004         } else { /* a MPU hit! */
12005             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
12006             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
12007
12008             if (m_is_system_region(env, address)) {
12009                 /* System space is always execute never */
12010                 xn = 1;
12011             }
12012
12013             if (is_user) { /* User mode AP bit decoding */
12014                 switch (ap) {
12015                 case 0:
12016                 case 1:
12017                 case 5:
12018                     break; /* no access */
12019                 case 3:
12020                     *prot |= PAGE_WRITE;
12021                     /* fall through */
12022                 case 2:
12023                 case 6:
12024                     *prot |= PAGE_READ | PAGE_EXEC;
12025                     break;
12026                 case 7:
12027                     /* for v7M, same as 6; for R profile a reserved value */
12028                     if (arm_feature(env, ARM_FEATURE_M)) {
12029                         *prot |= PAGE_READ | PAGE_EXEC;
12030                         break;
12031                     }
12032                     /* fall through */
12033                 default:
12034                     qemu_log_mask(LOG_GUEST_ERROR,
12035                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12036                                   PRIx32 "\n", n, ap);
12037                 }
12038             } else { /* Priv. mode AP bits decoding */
12039                 switch (ap) {
12040                 case 0:
12041                     break; /* no access */
12042                 case 1:
12043                 case 2:
12044                 case 3:
12045                     *prot |= PAGE_WRITE;
12046                     /* fall through */
12047                 case 5:
12048                 case 6:
12049                     *prot |= PAGE_READ | PAGE_EXEC;
12050                     break;
12051                 case 7:
12052                     /* for v7M, same as 6; for R profile a reserved value */
12053                     if (arm_feature(env, ARM_FEATURE_M)) {
12054                         *prot |= PAGE_READ | PAGE_EXEC;
12055                         break;
12056                     }
12057                     /* fall through */
12058                 default:
12059                     qemu_log_mask(LOG_GUEST_ERROR,
12060                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12061                                   PRIx32 "\n", n, ap);
12062                 }
12063             }
12064
12065             /* execute never */
12066             if (xn) {
12067                 *prot &= ~PAGE_EXEC;
12068             }
12069         }
12070     }
12071
12072     fi->type = ARMFault_Permission;
12073     fi->level = 1;
12074     return !(*prot & (1 << access_type));
12075 }
12076
12077 static bool v8m_is_sau_exempt(CPUARMState *env,
12078                               uint32_t address, MMUAccessType access_type)
12079 {
12080     /* The architecture specifies that certain address ranges are
12081      * exempt from v8M SAU/IDAU checks.
12082      */
12083     return
12084         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
12085         (address >= 0xe0000000 && address <= 0xe0002fff) ||
12086         (address >= 0xe000e000 && address <= 0xe000efff) ||
12087         (address >= 0xe002e000 && address <= 0xe002efff) ||
12088         (address >= 0xe0040000 && address <= 0xe0041fff) ||
12089         (address >= 0xe00ff000 && address <= 0xe00fffff);
12090 }
12091
12092 void v8m_security_lookup(CPUARMState *env, uint32_t address,
12093                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
12094                                 V8M_SAttributes *sattrs)
12095 {
12096     /* Look up the security attributes for this address. Compare the
12097      * pseudocode SecurityCheck() function.
12098      * We assume the caller has zero-initialized *sattrs.
12099      */
12100     ARMCPU *cpu = env_archcpu(env);
12101     int r;
12102     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
12103     int idau_region = IREGION_NOTVALID;
12104     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12105     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12106
12107     if (cpu->idau) {
12108         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
12109         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
12110
12111         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
12112                    &idau_nsc);
12113     }
12114
12115     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
12116         /* 0xf0000000..0xffffffff is always S for insn fetches */
12117         return;
12118     }
12119
12120     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
12121         sattrs->ns = !regime_is_secure(env, mmu_idx);
12122         return;
12123     }
12124
12125     if (idau_region != IREGION_NOTVALID) {
12126         sattrs->irvalid = true;
12127         sattrs->iregion = idau_region;
12128     }
12129
12130     switch (env->sau.ctrl & 3) {
12131     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
12132         break;
12133     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
12134         sattrs->ns = true;
12135         break;
12136     default: /* SAU.ENABLE == 1 */
12137         for (r = 0; r < cpu->sau_sregion; r++) {
12138             if (env->sau.rlar[r] & 1) {
12139                 uint32_t base = env->sau.rbar[r] & ~0x1f;
12140                 uint32_t limit = env->sau.rlar[r] | 0x1f;
12141
12142                 if (base <= address && limit >= address) {
12143                     if (base > addr_page_base || limit < addr_page_limit) {
12144                         sattrs->subpage = true;
12145                     }
12146                     if (sattrs->srvalid) {
12147                         /* If we hit in more than one region then we must report
12148                          * as Secure, not NS-Callable, with no valid region
12149                          * number info.
12150                          */
12151                         sattrs->ns = false;
12152                         sattrs->nsc = false;
12153                         sattrs->sregion = 0;
12154                         sattrs->srvalid = false;
12155                         break;
12156                     } else {
12157                         if (env->sau.rlar[r] & 2) {
12158                             sattrs->nsc = true;
12159                         } else {
12160                             sattrs->ns = true;
12161                         }
12162                         sattrs->srvalid = true;
12163                         sattrs->sregion = r;
12164                     }
12165                 } else {
12166                     /*
12167                      * Address not in this region. We must check whether the
12168                      * region covers addresses in the same page as our address.
12169                      * In that case we must not report a size that covers the
12170                      * whole page for a subsequent hit against a different MPU
12171                      * region or the background region, because it would result
12172                      * in incorrect TLB hits for subsequent accesses to
12173                      * addresses that are in this MPU region.
12174                      */
12175                     if (limit >= base &&
12176                         ranges_overlap(base, limit - base + 1,
12177                                        addr_page_base,
12178                                        TARGET_PAGE_SIZE)) {
12179                         sattrs->subpage = true;
12180                     }
12181                 }
12182             }
12183         }
12184         break;
12185     }
12186
12187     /*
12188      * The IDAU will override the SAU lookup results if it specifies
12189      * higher security than the SAU does.
12190      */
12191     if (!idau_ns) {
12192         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12193             sattrs->ns = false;
12194             sattrs->nsc = idau_nsc;
12195         }
12196     }
12197 }
12198
12199 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12200                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12201                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12202                               int *prot, bool *is_subpage,
12203                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12204 {
12205     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12206      * that a full phys-to-virt translation does).
12207      * mregion is (if not NULL) set to the region number which matched,
12208      * or -1 if no region number is returned (MPU off, address did not
12209      * hit a region, address hit in multiple regions).
12210      * We set is_subpage to true if the region hit doesn't cover the
12211      * entire TARGET_PAGE the address is within.
12212      */
12213     ARMCPU *cpu = env_archcpu(env);
12214     bool is_user = regime_is_user(env, mmu_idx);
12215     uint32_t secure = regime_is_secure(env, mmu_idx);
12216     int n;
12217     int matchregion = -1;
12218     bool hit = false;
12219     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12220     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12221
12222     *is_subpage = false;
12223     *phys_ptr = address;
12224     *prot = 0;
12225     if (mregion) {
12226         *mregion = -1;
12227     }
12228
12229     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12230      * was an exception vector read from the vector table (which is always
12231      * done using the default system address map), because those accesses
12232      * are done in arm_v7m_load_vector(), which always does a direct
12233      * read using address_space_ldl(), rather than going via this function.
12234      */
12235     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12236         hit = true;
12237     } else if (m_is_ppb_region(env, address)) {
12238         hit = true;
12239     } else {
12240         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12241             hit = true;
12242         }
12243
12244         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12245             /* region search */
12246             /* Note that the base address is bits [31:5] from the register
12247              * with bits [4:0] all zeroes, but the limit address is bits
12248              * [31:5] from the register with bits [4:0] all ones.
12249              */
12250             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12251             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12252
12253             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12254                 /* Region disabled */
12255                 continue;
12256             }
12257
12258             if (address < base || address > limit) {
12259                 /*
12260                  * Address not in this region. We must check whether the
12261                  * region covers addresses in the same page as our address.
12262                  * In that case we must not report a size that covers the
12263                  * whole page for a subsequent hit against a different MPU
12264                  * region or the background region, because it would result in
12265                  * incorrect TLB hits for subsequent accesses to addresses that
12266                  * are in this MPU region.
12267                  */
12268                 if (limit >= base &&
12269                     ranges_overlap(base, limit - base + 1,
12270                                    addr_page_base,
12271                                    TARGET_PAGE_SIZE)) {
12272                     *is_subpage = true;
12273                 }
12274                 continue;
12275             }
12276
12277             if (base > addr_page_base || limit < addr_page_limit) {
12278                 *is_subpage = true;
12279             }
12280
12281             if (matchregion != -1) {
12282                 /* Multiple regions match -- always a failure (unlike
12283                  * PMSAv7 where highest-numbered-region wins)
12284                  */
12285                 fi->type = ARMFault_Permission;
12286                 fi->level = 1;
12287                 return true;
12288             }
12289
12290             matchregion = n;
12291             hit = true;
12292         }
12293     }
12294
12295     if (!hit) {
12296         /* background fault */
12297         fi->type = ARMFault_Background;
12298         return true;
12299     }
12300
12301     if (matchregion == -1) {
12302         /* hit using the background region */
12303         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12304     } else {
12305         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12306         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12307
12308         if (m_is_system_region(env, address)) {
12309             /* System space is always execute never */
12310             xn = 1;
12311         }
12312
12313         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12314         if (*prot && !xn) {
12315             *prot |= PAGE_EXEC;
12316         }
12317         /* We don't need to look the attribute up in the MAIR0/MAIR1
12318          * registers because that only tells us about cacheability.
12319          */
12320         if (mregion) {
12321             *mregion = matchregion;
12322         }
12323     }
12324
12325     fi->type = ARMFault_Permission;
12326     fi->level = 1;
12327     return !(*prot & (1 << access_type));
12328 }
12329
12330
12331 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12332                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12333                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12334                                  int *prot, target_ulong *page_size,
12335                                  ARMMMUFaultInfo *fi)
12336 {
12337     uint32_t secure = regime_is_secure(env, mmu_idx);
12338     V8M_SAttributes sattrs = {};
12339     bool ret;
12340     bool mpu_is_subpage;
12341
12342     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12343         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12344         if (access_type == MMU_INST_FETCH) {
12345             /* Instruction fetches always use the MMU bank and the
12346              * transaction attribute determined by the fetch address,
12347              * regardless of CPU state. This is painful for QEMU
12348              * to handle, because it would mean we need to encode
12349              * into the mmu_idx not just the (user, negpri) information
12350              * for the current security state but also that for the
12351              * other security state, which would balloon the number
12352              * of mmu_idx values needed alarmingly.
12353              * Fortunately we can avoid this because it's not actually
12354              * possible to arbitrarily execute code from memory with
12355              * the wrong security attribute: it will always generate
12356              * an exception of some kind or another, apart from the
12357              * special case of an NS CPU executing an SG instruction
12358              * in S&NSC memory. So we always just fail the translation
12359              * here and sort things out in the exception handler
12360              * (including possibly emulating an SG instruction).
12361              */
12362             if (sattrs.ns != !secure) {
12363                 if (sattrs.nsc) {
12364                     fi->type = ARMFault_QEMU_NSCExec;
12365                 } else {
12366                     fi->type = ARMFault_QEMU_SFault;
12367                 }
12368                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12369                 *phys_ptr = address;
12370                 *prot = 0;
12371                 return true;
12372             }
12373         } else {
12374             /* For data accesses we always use the MMU bank indicated
12375              * by the current CPU state, but the security attributes
12376              * might downgrade a secure access to nonsecure.
12377              */
12378             if (sattrs.ns) {
12379                 txattrs->secure = false;
12380             } else if (!secure) {
12381                 /* NS access to S memory must fault.
12382                  * Architecturally we should first check whether the
12383                  * MPU information for this address indicates that we
12384                  * are doing an unaligned access to Device memory, which
12385                  * should generate a UsageFault instead. QEMU does not
12386                  * currently check for that kind of unaligned access though.
12387                  * If we added it we would need to do so as a special case
12388                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12389                  */
12390                 fi->type = ARMFault_QEMU_SFault;
12391                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12392                 *phys_ptr = address;
12393                 *prot = 0;
12394                 return true;
12395             }
12396         }
12397     }
12398
12399     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12400                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12401     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12402     return ret;
12403 }
12404
12405 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12406                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12407                                  hwaddr *phys_ptr, int *prot,
12408                                  ARMMMUFaultInfo *fi)
12409 {
12410     int n;
12411     uint32_t mask;
12412     uint32_t base;
12413     bool is_user = regime_is_user(env, mmu_idx);
12414
12415     if (regime_translation_disabled(env, mmu_idx)) {
12416         /* MPU disabled.  */
12417         *phys_ptr = address;
12418         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12419         return false;
12420     }
12421
12422     *phys_ptr = address;
12423     for (n = 7; n >= 0; n--) {
12424         base = env->cp15.c6_region[n];
12425         if ((base & 1) == 0) {
12426             continue;
12427         }
12428         mask = 1 << ((base >> 1) & 0x1f);
12429         /* Keep this shift separate from the above to avoid an
12430            (undefined) << 32.  */
12431         mask = (mask << 1) - 1;
12432         if (((base ^ address) & ~mask) == 0) {
12433             break;
12434         }
12435     }
12436     if (n < 0) {
12437         fi->type = ARMFault_Background;
12438         return true;
12439     }
12440
12441     if (access_type == MMU_INST_FETCH) {
12442         mask = env->cp15.pmsav5_insn_ap;
12443     } else {
12444         mask = env->cp15.pmsav5_data_ap;
12445     }
12446     mask = (mask >> (n * 4)) & 0xf;
12447     switch (mask) {
12448     case 0:
12449         fi->type = ARMFault_Permission;
12450         fi->level = 1;
12451         return true;
12452     case 1:
12453         if (is_user) {
12454             fi->type = ARMFault_Permission;
12455             fi->level = 1;
12456             return true;
12457         }
12458         *prot = PAGE_READ | PAGE_WRITE;
12459         break;
12460     case 2:
12461         *prot = PAGE_READ;
12462         if (!is_user) {
12463             *prot |= PAGE_WRITE;
12464         }
12465         break;
12466     case 3:
12467         *prot = PAGE_READ | PAGE_WRITE;
12468         break;
12469     case 5:
12470         if (is_user) {
12471             fi->type = ARMFault_Permission;
12472             fi->level = 1;
12473             return true;
12474         }
12475         *prot = PAGE_READ;
12476         break;
12477     case 6:
12478         *prot = PAGE_READ;
12479         break;
12480     default:
12481         /* Bad permission.  */
12482         fi->type = ARMFault_Permission;
12483         fi->level = 1;
12484         return true;
12485     }
12486     *prot |= PAGE_EXEC;
12487     return false;
12488 }
12489
12490 /* Combine either inner or outer cacheability attributes for normal
12491  * memory, according to table D4-42 and pseudocode procedure
12492  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12493  *
12494  * NB: only stage 1 includes allocation hints (RW bits), leading to
12495  * some asymmetry.
12496  */
12497 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12498 {
12499     if (s1 == 4 || s2 == 4) {
12500         /* non-cacheable has precedence */
12501         return 4;
12502     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12503         /* stage 1 write-through takes precedence */
12504         return s1;
12505     } else if (extract32(s2, 2, 2) == 2) {
12506         /* stage 2 write-through takes precedence, but the allocation hint
12507          * is still taken from stage 1
12508          */
12509         return (2 << 2) | extract32(s1, 0, 2);
12510     } else { /* write-back */
12511         return s1;
12512     }
12513 }
12514
12515 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12516  * and CombineS1S2Desc()
12517  *
12518  * @s1:      Attributes from stage 1 walk
12519  * @s2:      Attributes from stage 2 walk
12520  */
12521 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12522 {
12523     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
12524     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
12525     ARMCacheAttrs ret;
12526
12527     /* Combine shareability attributes (table D4-43) */
12528     if (s1.shareability == 2 || s2.shareability == 2) {
12529         /* if either are outer-shareable, the result is outer-shareable */
12530         ret.shareability = 2;
12531     } else if (s1.shareability == 3 || s2.shareability == 3) {
12532         /* if either are inner-shareable, the result is inner-shareable */
12533         ret.shareability = 3;
12534     } else {
12535         /* both non-shareable */
12536         ret.shareability = 0;
12537     }
12538
12539     /* Combine memory type and cacheability attributes */
12540     if (s1hi == 0 || s2hi == 0) {
12541         /* Device has precedence over normal */
12542         if (s1lo == 0 || s2lo == 0) {
12543             /* nGnRnE has precedence over anything */
12544             ret.attrs = 0;
12545         } else if (s1lo == 4 || s2lo == 4) {
12546             /* non-Reordering has precedence over Reordering */
12547             ret.attrs = 4;  /* nGnRE */
12548         } else if (s1lo == 8 || s2lo == 8) {
12549             /* non-Gathering has precedence over Gathering */
12550             ret.attrs = 8;  /* nGRE */
12551         } else {
12552             ret.attrs = 0xc; /* GRE */
12553         }
12554
12555         /* Any location for which the resultant memory type is any
12556          * type of Device memory is always treated as Outer Shareable.
12557          */
12558         ret.shareability = 2;
12559     } else { /* Normal memory */
12560         /* Outer/inner cacheability combine independently */
12561         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12562                   | combine_cacheattr_nibble(s1lo, s2lo);
12563
12564         if (ret.attrs == 0x44) {
12565             /* Any location for which the resultant memory type is Normal
12566              * Inner Non-cacheable, Outer Non-cacheable is always treated
12567              * as Outer Shareable.
12568              */
12569             ret.shareability = 2;
12570         }
12571     }
12572
12573     return ret;
12574 }
12575
12576
12577 /* get_phys_addr - get the physical address for this virtual address
12578  *
12579  * Find the physical address corresponding to the given virtual address,
12580  * by doing a translation table walk on MMU based systems or using the
12581  * MPU state on MPU based systems.
12582  *
12583  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12584  * prot and page_size may not be filled in, and the populated fsr value provides
12585  * information on why the translation aborted, in the format of a
12586  * DFSR/IFSR fault register, with the following caveats:
12587  *  * we honour the short vs long DFSR format differences.
12588  *  * the WnR bit is never set (the caller must do this).
12589  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12590  *    value.
12591  *
12592  * @env: CPUARMState
12593  * @address: virtual address to get physical address for
12594  * @access_type: 0 for read, 1 for write, 2 for execute
12595  * @mmu_idx: MMU index indicating required translation regime
12596  * @phys_ptr: set to the physical address corresponding to the virtual address
12597  * @attrs: set to the memory transaction attributes to use
12598  * @prot: set to the permissions for the page containing phys_ptr
12599  * @page_size: set to the size of the page containing phys_ptr
12600  * @fi: set to fault info if the translation fails
12601  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12602  */
12603 bool get_phys_addr(CPUARMState *env, target_ulong address,
12604                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12605                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12606                    target_ulong *page_size,
12607                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12608 {
12609     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
12610         /* Call ourselves recursively to do the stage 1 and then stage 2
12611          * translations.
12612          */
12613         if (arm_feature(env, ARM_FEATURE_EL2)) {
12614             hwaddr ipa;
12615             int s2_prot;
12616             int ret;
12617             ARMCacheAttrs cacheattrs2 = {};
12618
12619             ret = get_phys_addr(env, address, access_type,
12620                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
12621                                 prot, page_size, fi, cacheattrs);
12622
12623             /* If S1 fails or S2 is disabled, return early.  */
12624             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
12625                 *phys_ptr = ipa;
12626                 return ret;
12627             }
12628
12629             /* S1 is done. Now do S2 translation.  */
12630             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
12631                                      phys_ptr, attrs, &s2_prot,
12632                                      page_size, fi,
12633                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
12634             fi->s2addr = ipa;
12635             /* Combine the S1 and S2 perms.  */
12636             *prot &= s2_prot;
12637
12638             /* Combine the S1 and S2 cache attributes, if needed */
12639             if (!ret && cacheattrs != NULL) {
12640                 if (env->cp15.hcr_el2 & HCR_DC) {
12641                     /*
12642                      * HCR.DC forces the first stage attributes to
12643                      *  Normal Non-Shareable,
12644                      *  Inner Write-Back Read-Allocate Write-Allocate,
12645                      *  Outer Write-Back Read-Allocate Write-Allocate.
12646                      */
12647                     cacheattrs->attrs = 0xff;
12648                     cacheattrs->shareability = 0;
12649                 }
12650                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12651             }
12652
12653             return ret;
12654         } else {
12655             /*
12656              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12657              */
12658             mmu_idx = stage_1_mmu_idx(mmu_idx);
12659         }
12660     }
12661
12662     /* The page table entries may downgrade secure to non-secure, but
12663      * cannot upgrade an non-secure translation regime's attributes
12664      * to secure.
12665      */
12666     attrs->secure = regime_is_secure(env, mmu_idx);
12667     attrs->user = regime_is_user(env, mmu_idx);
12668
12669     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12670      * In v7 and earlier it affects all stage 1 translations.
12671      */
12672     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
12673         && !arm_feature(env, ARM_FEATURE_V8)) {
12674         if (regime_el(env, mmu_idx) == 3) {
12675             address += env->cp15.fcseidr_s;
12676         } else {
12677             address += env->cp15.fcseidr_ns;
12678         }
12679     }
12680
12681     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12682         bool ret;
12683         *page_size = TARGET_PAGE_SIZE;
12684
12685         if (arm_feature(env, ARM_FEATURE_V8)) {
12686             /* PMSAv8 */
12687             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12688                                        phys_ptr, attrs, prot, page_size, fi);
12689         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12690             /* PMSAv7 */
12691             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12692                                        phys_ptr, prot, page_size, fi);
12693         } else {
12694             /* Pre-v7 MPU */
12695             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12696                                        phys_ptr, prot, fi);
12697         }
12698         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12699                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12700                       access_type == MMU_DATA_LOAD ? "reading" :
12701                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12702                       (uint32_t)address, mmu_idx,
12703                       ret ? "Miss" : "Hit",
12704                       *prot & PAGE_READ ? 'r' : '-',
12705                       *prot & PAGE_WRITE ? 'w' : '-',
12706                       *prot & PAGE_EXEC ? 'x' : '-');
12707
12708         return ret;
12709     }
12710
12711     /* Definitely a real MMU, not an MPU */
12712
12713     if (regime_translation_disabled(env, mmu_idx)) {
12714         /* MMU disabled. */
12715         *phys_ptr = address;
12716         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12717         *page_size = TARGET_PAGE_SIZE;
12718         return 0;
12719     }
12720
12721     if (regime_using_lpae_format(env, mmu_idx)) {
12722         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
12723                                   phys_ptr, attrs, prot, page_size,
12724                                   fi, cacheattrs);
12725     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12726         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12727                                 phys_ptr, attrs, prot, page_size, fi);
12728     } else {
12729         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12730                                     phys_ptr, prot, page_size, fi);
12731     }
12732 }
12733
12734 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12735                                          MemTxAttrs *attrs)
12736 {
12737     ARMCPU *cpu = ARM_CPU(cs);
12738     CPUARMState *env = &cpu->env;
12739     hwaddr phys_addr;
12740     target_ulong page_size;
12741     int prot;
12742     bool ret;
12743     ARMMMUFaultInfo fi = {};
12744     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12745
12746     *attrs = (MemTxAttrs) {};
12747
12748     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
12749                         attrs, &prot, &page_size, &fi, NULL);
12750
12751     if (ret) {
12752         return -1;
12753     }
12754     return phys_addr;
12755 }
12756
12757 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
12758 {
12759     uint32_t mask;
12760     unsigned el = arm_current_el(env);
12761
12762     /* First handle registers which unprivileged can read */
12763
12764     switch (reg) {
12765     case 0 ... 7: /* xPSR sub-fields */
12766         mask = 0;
12767         if ((reg & 1) && el) {
12768             mask |= XPSR_EXCP; /* IPSR (unpriv. reads as zero) */
12769         }
12770         if (!(reg & 4)) {
12771             mask |= XPSR_NZCV | XPSR_Q; /* APSR */
12772             if (arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
12773                 mask |= XPSR_GE;
12774             }
12775         }
12776         /* EPSR reads as zero */
12777         return xpsr_read(env) & mask;
12778         break;
12779     case 20: /* CONTROL */
12780     {
12781         uint32_t value = env->v7m.control[env->v7m.secure];
12782         if (!env->v7m.secure) {
12783             /* SFPA is RAZ/WI from NS; FPCA is stored in the M_REG_S bank */
12784             value |= env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK;
12785         }
12786         return value;
12787     }
12788     case 0x94: /* CONTROL_NS */
12789         /*
12790          * We have to handle this here because unprivileged Secure code
12791          * can read the NS CONTROL register.
12792          */
12793         if (!env->v7m.secure) {
12794             return 0;
12795         }
12796         return env->v7m.control[M_REG_NS] |
12797             (env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK);
12798     }
12799
12800     if (el == 0) {
12801         return 0; /* unprivileged reads others as zero */
12802     }
12803
12804     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12805         switch (reg) {
12806         case 0x88: /* MSP_NS */
12807             if (!env->v7m.secure) {
12808                 return 0;
12809             }
12810             return env->v7m.other_ss_msp;
12811         case 0x89: /* PSP_NS */
12812             if (!env->v7m.secure) {
12813                 return 0;
12814             }
12815             return env->v7m.other_ss_psp;
12816         case 0x8a: /* MSPLIM_NS */
12817             if (!env->v7m.secure) {
12818                 return 0;
12819             }
12820             return env->v7m.msplim[M_REG_NS];
12821         case 0x8b: /* PSPLIM_NS */
12822             if (!env->v7m.secure) {
12823                 return 0;
12824             }
12825             return env->v7m.psplim[M_REG_NS];
12826         case 0x90: /* PRIMASK_NS */
12827             if (!env->v7m.secure) {
12828                 return 0;
12829             }
12830             return env->v7m.primask[M_REG_NS];
12831         case 0x91: /* BASEPRI_NS */
12832             if (!env->v7m.secure) {
12833                 return 0;
12834             }
12835             return env->v7m.basepri[M_REG_NS];
12836         case 0x93: /* FAULTMASK_NS */
12837             if (!env->v7m.secure) {
12838                 return 0;
12839             }
12840             return env->v7m.faultmask[M_REG_NS];
12841         case 0x98: /* SP_NS */
12842         {
12843             /*
12844              * This gives the non-secure SP selected based on whether we're
12845              * currently in handler mode or not, using the NS CONTROL.SPSEL.
12846              */
12847             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
12848
12849             if (!env->v7m.secure) {
12850                 return 0;
12851             }
12852             if (!arm_v7m_is_handler_mode(env) && spsel) {
12853                 return env->v7m.other_ss_psp;
12854             } else {
12855                 return env->v7m.other_ss_msp;
12856             }
12857         }
12858         default:
12859             break;
12860         }
12861     }
12862
12863     switch (reg) {
12864     case 8: /* MSP */
12865         return v7m_using_psp(env) ? env->v7m.other_sp : env->regs[13];
12866     case 9: /* PSP */
12867         return v7m_using_psp(env) ? env->regs[13] : env->v7m.other_sp;
12868     case 10: /* MSPLIM */
12869         if (!arm_feature(env, ARM_FEATURE_V8)) {
12870             goto bad_reg;
12871         }
12872         return env->v7m.msplim[env->v7m.secure];
12873     case 11: /* PSPLIM */
12874         if (!arm_feature(env, ARM_FEATURE_V8)) {
12875             goto bad_reg;
12876         }
12877         return env->v7m.psplim[env->v7m.secure];
12878     case 16: /* PRIMASK */
12879         return env->v7m.primask[env->v7m.secure];
12880     case 17: /* BASEPRI */
12881     case 18: /* BASEPRI_MAX */
12882         return env->v7m.basepri[env->v7m.secure];
12883     case 19: /* FAULTMASK */
12884         return env->v7m.faultmask[env->v7m.secure];
12885     default:
12886     bad_reg:
12887         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"
12888                                        " register %d\n", reg);
12889         return 0;
12890     }
12891 }
12892
12893 void HELPER(v7m_msr)(CPUARMState *env, uint32_t maskreg, uint32_t val)
12894 {
12895     /*
12896      * We're passed bits [11..0] of the instruction; extract
12897      * SYSm and the mask bits.
12898      * Invalid combinations of SYSm and mask are UNPREDICTABLE;
12899      * we choose to treat them as if the mask bits were valid.
12900      * NB that the pseudocode 'mask' variable is bits [11..10],
12901      * whereas ours is [11..8].
12902      */
12903     uint32_t mask = extract32(maskreg, 8, 4);
12904     uint32_t reg = extract32(maskreg, 0, 8);
12905     int cur_el = arm_current_el(env);
12906
12907     if (cur_el == 0 && reg > 7 && reg != 20) {
12908         /*
12909          * only xPSR sub-fields and CONTROL.SFPA may be written by
12910          * unprivileged code
12911          */
12912         return;
12913     }
12914
12915     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12916         switch (reg) {
12917         case 0x88: /* MSP_NS */
12918             if (!env->v7m.secure) {
12919                 return;
12920             }
12921             env->v7m.other_ss_msp = val;
12922             return;
12923         case 0x89: /* PSP_NS */
12924             if (!env->v7m.secure) {
12925                 return;
12926             }
12927             env->v7m.other_ss_psp = val;
12928             return;
12929         case 0x8a: /* MSPLIM_NS */
12930             if (!env->v7m.secure) {
12931                 return;
12932             }
12933             env->v7m.msplim[M_REG_NS] = val & ~7;
12934             return;
12935         case 0x8b: /* PSPLIM_NS */
12936             if (!env->v7m.secure) {
12937                 return;
12938             }
12939             env->v7m.psplim[M_REG_NS] = val & ~7;
12940             return;
12941         case 0x90: /* PRIMASK_NS */
12942             if (!env->v7m.secure) {
12943                 return;
12944             }
12945             env->v7m.primask[M_REG_NS] = val & 1;
12946             return;
12947         case 0x91: /* BASEPRI_NS */
12948             if (!env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_MAIN)) {
12949                 return;
12950             }
12951             env->v7m.basepri[M_REG_NS] = val & 0xff;
12952             return;
12953         case 0x93: /* FAULTMASK_NS */
12954             if (!env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_MAIN)) {
12955                 return;
12956             }
12957             env->v7m.faultmask[M_REG_NS] = val & 1;
12958             return;
12959         case 0x94: /* CONTROL_NS */
12960             if (!env->v7m.secure) {
12961                 return;
12962             }
12963             write_v7m_control_spsel_for_secstate(env,
12964                                                  val & R_V7M_CONTROL_SPSEL_MASK,
12965                                                  M_REG_NS);
12966             if (arm_feature(env, ARM_FEATURE_M_MAIN)) {
12967                 env->v7m.control[M_REG_NS] &= ~R_V7M_CONTROL_NPRIV_MASK;
12968                 env->v7m.control[M_REG_NS] |= val & R_V7M_CONTROL_NPRIV_MASK;
12969             }
12970             /*
12971              * SFPA is RAZ/WI from NS. FPCA is RO if NSACR.CP10 == 0,
12972              * RES0 if the FPU is not present, and is stored in the S bank
12973              */
12974             if (arm_feature(env, ARM_FEATURE_VFP) &&
12975                 extract32(env->v7m.nsacr, 10, 1)) {
12976                 env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_FPCA_MASK;
12977                 env->v7m.control[M_REG_S] |= val & R_V7M_CONTROL_FPCA_MASK;
12978             }
12979             return;
12980         case 0x98: /* SP_NS */
12981         {
12982             /*
12983              * This gives the non-secure SP selected based on whether we're
12984              * currently in handler mode or not, using the NS CONTROL.SPSEL.
12985              */
12986             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
12987             bool is_psp = !arm_v7m_is_handler_mode(env) && spsel;
12988             uint32_t limit;
12989
12990             if (!env->v7m.secure) {
12991                 return;
12992             }
12993
12994             limit = is_psp ? env->v7m.psplim[false] : env->v7m.msplim[false];
12995
12996             if (val < limit) {
12997                 CPUState *cs = env_cpu(env);
12998
12999                 cpu_restore_state(cs, GETPC(), true);
13000                 raise_exception(env, EXCP_STKOF, 0, 1);
13001             }
13002
13003             if (is_psp) {
13004                 env->v7m.other_ss_psp = val;
13005             } else {
13006                 env->v7m.other_ss_msp = val;
13007             }
13008             return;
13009         }
13010         default:
13011             break;
13012         }
13013     }
13014
13015     switch (reg) {
13016     case 0 ... 7: /* xPSR sub-fields */
13017         /* only APSR is actually writable */
13018         if (!(reg & 4)) {
13019             uint32_t apsrmask = 0;
13020
13021             if (mask & 8) {
13022                 apsrmask |= XPSR_NZCV | XPSR_Q;
13023             }
13024             if ((mask & 4) && arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
13025                 apsrmask |= XPSR_GE;
13026             }
13027             xpsr_write(env, val, apsrmask);
13028         }
13029         break;
13030     case 8: /* MSP */
13031         if (v7m_using_psp(env)) {
13032             env->v7m.other_sp = val;
13033         } else {
13034             env->regs[13] = val;
13035         }
13036         break;
13037     case 9: /* PSP */
13038         if (v7m_using_psp(env)) {
13039             env->regs[13] = val;
13040         } else {
13041             env->v7m.other_sp = val;
13042         }
13043         break;
13044     case 10: /* MSPLIM */
13045         if (!arm_feature(env, ARM_FEATURE_V8)) {
13046             goto bad_reg;
13047         }
13048         env->v7m.msplim[env->v7m.secure] = val & ~7;
13049         break;
13050     case 11: /* PSPLIM */
13051         if (!arm_feature(env, ARM_FEATURE_V8)) {
13052             goto bad_reg;
13053         }
13054         env->v7m.psplim[env->v7m.secure] = val & ~7;
13055         break;
13056     case 16: /* PRIMASK */
13057         env->v7m.primask[env->v7m.secure] = val & 1;
13058         break;
13059     case 17: /* BASEPRI */
13060         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
13061             goto bad_reg;
13062         }
13063         env->v7m.basepri[env->v7m.secure] = val & 0xff;
13064         break;
13065     case 18: /* BASEPRI_MAX */
13066         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
13067             goto bad_reg;
13068         }
13069         val &= 0xff;
13070         if (val != 0 && (val < env->v7m.basepri[env->v7m.secure]
13071                          || env->v7m.basepri[env->v7m.secure] == 0)) {
13072             env->v7m.basepri[env->v7m.secure] = val;
13073         }
13074         break;
13075     case 19: /* FAULTMASK */
13076         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
13077             goto bad_reg;
13078         }
13079         env->v7m.faultmask[env->v7m.secure] = val & 1;
13080         break;
13081     case 20: /* CONTROL */
13082         /*
13083          * Writing to the SPSEL bit only has an effect if we are in
13084          * thread mode; other bits can be updated by any privileged code.
13085          * write_v7m_control_spsel() deals with updating the SPSEL bit in
13086          * env->v7m.control, so we only need update the others.
13087          * For v7M, we must just ignore explicit writes to SPSEL in handler
13088          * mode; for v8M the write is permitted but will have no effect.
13089          * All these bits are writes-ignored from non-privileged code,
13090          * except for SFPA.
13091          */
13092         if (cur_el > 0 && (arm_feature(env, ARM_FEATURE_V8) ||
13093                            !arm_v7m_is_handler_mode(env))) {
13094             write_v7m_control_spsel(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);
13095         }
13096         if (cur_el > 0 && arm_feature(env, ARM_FEATURE_M_MAIN)) {
13097             env->v7m.control[env->v7m.secure] &= ~R_V7M_CONTROL_NPRIV_MASK;
13098             env->v7m.control[env->v7m.secure] |= val & R_V7M_CONTROL_NPRIV_MASK;
13099         }
13100         if (arm_feature(env, ARM_FEATURE_VFP)) {
13101             /*
13102              * SFPA is RAZ/WI from NS or if no FPU.
13103              * FPCA is RO if NSACR.CP10 == 0, RES0 if the FPU is not present.
13104              * Both are stored in the S bank.
13105              */
13106             if (env->v7m.secure) {
13107                 env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
13108                 env->v7m.control[M_REG_S] |= val & R_V7M_CONTROL_SFPA_MASK;
13109             }
13110             if (cur_el > 0 &&
13111                 (env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_SECURITY) ||
13112                  extract32(env->v7m.nsacr, 10, 1))) {
13113                 env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_FPCA_MASK;
13114                 env->v7m.control[M_REG_S] |= val & R_V7M_CONTROL_FPCA_MASK;
13115             }
13116         }
13117         break;
13118     default:
13119     bad_reg:
13120         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"
13121                                        " register %d\n", reg);
13122         return;
13123     }
13124 }
13125
13126 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
13127 {
13128     /* Implement the TT instruction. op is bits [7:6] of the insn. */
13129     bool forceunpriv = op & 1;
13130     bool alt = op & 2;
13131     V8M_SAttributes sattrs = {};
13132     uint32_t tt_resp;
13133     bool r, rw, nsr, nsrw, mrvalid;
13134     int prot;
13135     ARMMMUFaultInfo fi = {};
13136     MemTxAttrs attrs = {};
13137     hwaddr phys_addr;
13138     ARMMMUIdx mmu_idx;
13139     uint32_t mregion;
13140     bool targetpriv;
13141     bool targetsec = env->v7m.secure;
13142     bool is_subpage;
13143
13144     /*
13145      * Work out what the security state and privilege level we're
13146      * interested in is...
13147      */
13148     if (alt) {
13149         targetsec = !targetsec;
13150     }
13151
13152     if (forceunpriv) {
13153         targetpriv = false;
13154     } else {
13155         targetpriv = arm_v7m_is_handler_mode(env) ||
13156             !(env->v7m.control[targetsec] & R_V7M_CONTROL_NPRIV_MASK);
13157     }
13158
13159     /* ...and then figure out which MMU index this is */
13160     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targetsec, targetpriv);
13161
13162     /*
13163      * We know that the MPU and SAU don't care about the access type
13164      * for our purposes beyond that we don't want to claim to be
13165      * an insn fetch, so we arbitrarily call this a read.
13166      */
13167
13168     /*
13169      * MPU region info only available for privileged or if
13170      * inspecting the other MPU state.
13171      */
13172     if (arm_current_el(env) != 0 || alt) {
13173         /* We can ignore the return value as prot is always set */
13174         pmsav8_mpu_lookup(env, addr, MMU_DATA_LOAD, mmu_idx,
13175                           &phys_addr, &attrs, &prot, &is_subpage,
13176                           &fi, &mregion);
13177         if (mregion == -1) {
13178             mrvalid = false;
13179             mregion = 0;
13180         } else {
13181             mrvalid = true;
13182         }
13183         r = prot & PAGE_READ;
13184         rw = prot & PAGE_WRITE;
13185     } else {
13186         r = false;
13187         rw = false;
13188         mrvalid = false;
13189         mregion = 0;
13190     }
13191
13192     if (env->v7m.secure) {
13193         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
13194         nsr = sattrs.ns && r;
13195         nsrw = sattrs.ns && rw;
13196     } else {
13197         sattrs.ns = true;
13198         nsr = false;
13199         nsrw = false;
13200     }
13201
13202     tt_resp = (sattrs.iregion << 24) |
13203         (sattrs.irvalid << 23) |
13204         ((!sattrs.ns) << 22) |
13205         (nsrw << 21) |
13206         (nsr << 20) |
13207         (rw << 19) |
13208         (r << 18) |
13209         (sattrs.srvalid << 17) |
13210         (mrvalid << 16) |
13211         (sattrs.sregion << 8) |
13212         mregion;
13213
13214     return tt_resp;
13215 }
13216
13217 #endif
13218
13219 /* Note that signed overflow is undefined in C.  The following routines are
13220    careful to use unsigned types where modulo arithmetic is required.
13221    Failure to do so _will_ break on newer gcc.  */
13222
13223 /* Signed saturating arithmetic.  */
13224
13225 /* Perform 16-bit signed saturating addition.  */
13226 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
13227 {
13228     uint16_t res;
13229
13230     res = a + b;
13231     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
13232         if (a & 0x8000)
13233             res = 0x8000;
13234         else
13235             res = 0x7fff;
13236     }
13237     return res;
13238 }
13239
13240 /* Perform 8-bit signed saturating addition.  */
13241 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
13242 {
13243     uint8_t res;
13244
13245     res = a + b;
13246     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
13247         if (a & 0x80)
13248             res = 0x80;
13249         else
13250             res = 0x7f;
13251     }
13252     return res;
13253 }
13254
13255 /* Perform 16-bit signed saturating subtraction.  */
13256 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
13257 {
13258     uint16_t res;
13259
13260     res = a - b;
13261     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
13262         if (a & 0x8000)
13263             res = 0x8000;
13264         else
13265             res = 0x7fff;
13266     }
13267     return res;
13268 }
13269
13270 /* Perform 8-bit signed saturating subtraction.  */
13271 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
13272 {
13273     uint8_t res;
13274
13275     res = a - b;
13276     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
13277         if (a & 0x80)
13278             res = 0x80;
13279         else
13280             res = 0x7f;
13281     }
13282     return res;
13283 }
13284
13285 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
13286 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
13287 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
13288 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
13289 #define PFX q
13290
13291 #include "op_addsub.h"
13292
13293 /* Unsigned saturating arithmetic.  */
13294 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
13295 {
13296     uint16_t res;
13297     res = a + b;
13298     if (res < a)
13299         res = 0xffff;
13300     return res;
13301 }
13302
13303 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
13304 {
13305     if (a > b)
13306         return a - b;
13307     else
13308         return 0;
13309 }
13310
13311 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
13312 {
13313     uint8_t res;
13314     res = a + b;
13315     if (res < a)
13316         res = 0xff;
13317     return res;
13318 }
13319
13320 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
13321 {
13322     if (a > b)
13323         return a - b;
13324     else
13325         return 0;
13326 }
13327
13328 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
13329 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
13330 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
13331 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
13332 #define PFX uq
13333
13334 #include "op_addsub.h"
13335
13336 /* Signed modulo arithmetic.  */
13337 #define SARITH16(a, b, n, op) do { \
13338     int32_t sum; \
13339     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
13340     RESULT(sum, n, 16); \
13341     if (sum >= 0) \
13342         ge |= 3 << (n * 2); \
13343     } while(0)
13344
13345 #define SARITH8(a, b, n, op) do { \
13346     int32_t sum; \
13347     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
13348     RESULT(sum, n, 8); \
13349     if (sum >= 0) \
13350         ge |= 1 << n; \
13351     } while(0)
13352
13353
13354 #define ADD16(a, b, n) SARITH16(a, b, n, +)
13355 #define SUB16(a, b, n) SARITH16(a, b, n, -)
13356 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
13357 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
13358 #define PFX s
13359 #define ARITH_GE
13360
13361 #include "op_addsub.h"
13362
13363 /* Unsigned modulo arithmetic.  */
13364 #define ADD16(a, b, n) do { \
13365     uint32_t sum; \
13366     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
13367     RESULT(sum, n, 16); \
13368     if ((sum >> 16) == 1) \
13369         ge |= 3 << (n * 2); \
13370     } while(0)
13371
13372 #define ADD8(a, b, n) do { \
13373     uint32_t sum; \
13374     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
13375     RESULT(sum, n, 8); \
13376     if ((sum >> 8) == 1) \
13377         ge |= 1 << n; \
13378     } while(0)
13379
13380 #define SUB16(a, b, n) do { \
13381     uint32_t sum; \
13382     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
13383     RESULT(sum, n, 16); \
13384     if ((sum >> 16) == 0) \
13385         ge |= 3 << (n * 2); \
13386     } while(0)
13387
13388 #define SUB8(a, b, n) do { \
13389     uint32_t sum; \
13390     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
13391     RESULT(sum, n, 8); \
13392     if ((sum >> 8) == 0) \
13393         ge |= 1 << n; \
13394     } while(0)
13395
13396 #define PFX u
13397 #define ARITH_GE
13398
13399 #include "op_addsub.h"
13400
13401 /* Halved signed arithmetic.  */
13402 #define ADD16(a, b, n) \
13403   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
13404 #define SUB16(a, b, n) \
13405   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
13406 #define ADD8(a, b, n) \
13407   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
13408 #define SUB8(a, b, n) \
13409   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
13410 #define PFX sh
13411
13412 #include "op_addsub.h"
13413
13414 /* Halved unsigned arithmetic.  */
13415 #define ADD16(a, b, n) \
13416   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13417 #define SUB16(a, b, n) \
13418   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13419 #define ADD8(a, b, n) \
13420   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13421 #define SUB8(a, b, n) \
13422   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13423 #define PFX uh
13424
13425 #include "op_addsub.h"
13426
13427 static inline uint8_t do_usad(uint8_t a, uint8_t b)
13428 {
13429     if (a > b)
13430         return a - b;
13431     else
13432         return b - a;
13433 }
13434
13435 /* Unsigned sum of absolute byte differences.  */
13436 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
13437 {
13438     uint32_t sum;
13439     sum = do_usad(a, b);
13440     sum += do_usad(a >> 8, b >> 8);
13441     sum += do_usad(a >> 16, b >>16);
13442     sum += do_usad(a >> 24, b >> 24);
13443     return sum;
13444 }
13445
13446 /* For ARMv6 SEL instruction.  */
13447 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
13448 {
13449     uint32_t mask;
13450
13451     mask = 0;
13452     if (flags & 1)
13453         mask |= 0xff;
13454     if (flags & 2)
13455         mask |= 0xff00;
13456     if (flags & 4)
13457         mask |= 0xff0000;
13458     if (flags & 8)
13459         mask |= 0xff000000;
13460     return (a & mask) | (b & ~mask);
13461 }
13462
13463 /* CRC helpers.
13464  * The upper bytes of val (above the number specified by 'bytes') must have
13465  * been zeroed out by the caller.
13466  */
13467 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
13468 {
13469     uint8_t buf[4];
13470
13471     stl_le_p(buf, val);
13472
13473     /* zlib crc32 converts the accumulator and output to one's complement.  */
13474     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
13475 }
13476
13477 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
13478 {
13479     uint8_t buf[4];
13480
13481     stl_le_p(buf, val);
13482
13483     /* Linux crc32c converts the output to one's complement.  */
13484     return crc32c(acc, buf, bytes) ^ 0xffffffff;
13485 }
13486
13487 /* Return the exception level to which FP-disabled exceptions should
13488  * be taken, or 0 if FP is enabled.
13489  */
13490 int fp_exception_el(CPUARMState *env, int cur_el)
13491 {
13492 #ifndef CONFIG_USER_ONLY
13493     int fpen;
13494
13495     /* CPACR and the CPTR registers don't exist before v6, so FP is
13496      * always accessible
13497      */
13498     if (!arm_feature(env, ARM_FEATURE_V6)) {
13499         return 0;
13500     }
13501
13502     if (arm_feature(env, ARM_FEATURE_M)) {
13503         /* CPACR can cause a NOCP UsageFault taken to current security state */
13504         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13505             return 1;
13506         }
13507
13508         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13509             if (!extract32(env->v7m.nsacr, 10, 1)) {
13510                 /* FP insns cause a NOCP UsageFault taken to Secure */
13511                 return 3;
13512             }
13513         }
13514
13515         return 0;
13516     }
13517
13518     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13519      * 0, 2 : trap EL0 and EL1/PL1 accesses
13520      * 1    : trap only EL0 accesses
13521      * 3    : trap no accesses
13522      */
13523     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
13524     switch (fpen) {
13525     case 0:
13526     case 2:
13527         if (cur_el == 0 || cur_el == 1) {
13528             /* Trap to PL1, which might be EL1 or EL3 */
13529             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13530                 return 3;
13531             }
13532             return 1;
13533         }
13534         if (cur_el == 3 && !is_a64(env)) {
13535             /* Secure PL1 running at EL3 */
13536             return 3;
13537         }
13538         break;
13539     case 1:
13540         if (cur_el == 0) {
13541             return 1;
13542         }
13543         break;
13544     case 3:
13545         break;
13546     }
13547
13548     /*
13549      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
13550      * to control non-secure access to the FPU. It doesn't have any
13551      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
13552      */
13553     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
13554          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
13555         if (!extract32(env->cp15.nsacr, 10, 1)) {
13556             /* FP insns act as UNDEF */
13557             return cur_el == 2 ? 2 : 1;
13558         }
13559     }
13560
13561     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
13562      * check because zero bits in the registers mean "don't trap".
13563      */
13564
13565     /* CPTR_EL2 : present in v7VE or v8 */
13566     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
13567         && !arm_is_secure_below_el3(env)) {
13568         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
13569         return 2;
13570     }
13571
13572     /* CPTR_EL3 : present in v8 */
13573     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
13574         /* Trap all FP ops to EL3 */
13575         return 3;
13576     }
13577 #endif
13578     return 0;
13579 }
13580
13581 ARMMMUIdx arm_v7m_mmu_idx_all(CPUARMState *env,
13582                               bool secstate, bool priv, bool negpri)
13583 {
13584     ARMMMUIdx mmu_idx = ARM_MMU_IDX_M;
13585
13586     if (priv) {
13587         mmu_idx |= ARM_MMU_IDX_M_PRIV;
13588     }
13589
13590     if (negpri) {
13591         mmu_idx |= ARM_MMU_IDX_M_NEGPRI;
13592     }
13593
13594     if (secstate) {
13595         mmu_idx |= ARM_MMU_IDX_M_S;
13596     }
13597
13598     return mmu_idx;
13599 }
13600
13601 ARMMMUIdx arm_v7m_mmu_idx_for_secstate_and_priv(CPUARMState *env,
13602                                                 bool secstate, bool priv)
13603 {
13604     bool negpri = armv7m_nvic_neg_prio_requested(env->nvic, secstate);
13605
13606     return arm_v7m_mmu_idx_all(env, secstate, priv, negpri);
13607 }
13608
13609 /* Return the MMU index for a v7M CPU in the specified security state */
13610 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13611 {
13612     bool priv = arm_current_el(env) != 0;
13613
13614     return arm_v7m_mmu_idx_for_secstate_and_priv(env, secstate, priv);
13615 }
13616
13617 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13618 {
13619     int el;
13620
13621     if (arm_feature(env, ARM_FEATURE_M)) {
13622         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13623     }
13624
13625     el = arm_current_el(env);
13626     if (el < 2 && arm_is_secure_below_el3(env)) {
13627         return ARMMMUIdx_S1SE0 + el;
13628     } else {
13629         return ARMMMUIdx_S12NSE0 + el;
13630     }
13631 }
13632
13633 int cpu_mmu_index(CPUARMState *env, bool ifetch)
13634 {
13635     return arm_to_core_mmu_idx(arm_mmu_idx(env));
13636 }
13637
13638 #ifndef CONFIG_USER_ONLY
13639 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13640 {
13641     return stage_1_mmu_idx(arm_mmu_idx(env));
13642 }
13643 #endif
13644
13645 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13646                           target_ulong *cs_base, uint32_t *pflags)
13647 {
13648     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
13649     int current_el = arm_current_el(env);
13650     int fp_el = fp_exception_el(env, current_el);
13651     uint32_t flags = 0;
13652
13653     if (is_a64(env)) {
13654         ARMCPU *cpu = env_archcpu(env);
13655         uint64_t sctlr;
13656
13657         *pc = env->pc;
13658         flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
13659
13660         /* Get control bits for tagged addresses.  */
13661         {
13662             ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13663             ARMVAParameters p0 = aa64_va_parameters_both(env, 0, stage1);
13664             int tbii, tbid;
13665
13666             /* FIXME: ARMv8.1-VHE S2 translation regime.  */
13667             if (regime_el(env, stage1) < 2) {
13668                 ARMVAParameters p1 = aa64_va_parameters_both(env, -1, stage1);
13669                 tbid = (p1.tbi << 1) | p0.tbi;
13670                 tbii = tbid & ~((p1.tbid << 1) | p0.tbid);
13671             } else {
13672                 tbid = p0.tbi;
13673                 tbii = tbid & !p0.tbid;
13674             }
13675
13676             flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
13677             flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
13678         }
13679
13680         if (cpu_isar_feature(aa64_sve, cpu)) {
13681             int sve_el = sve_exception_el(env, current_el);
13682             uint32_t zcr_len;
13683
13684             /* If SVE is disabled, but FP is enabled,
13685              * then the effective len is 0.
13686              */
13687             if (sve_el != 0 && fp_el == 0) {
13688                 zcr_len = 0;
13689             } else {
13690                 zcr_len = sve_zcr_len_for_el(env, current_el);
13691             }
13692             flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
13693             flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
13694         }
13695
13696         sctlr = arm_sctlr(env, current_el);
13697
13698         if (cpu_isar_feature(aa64_pauth, cpu)) {
13699             /*
13700              * In order to save space in flags, we record only whether
13701              * pauth is "inactive", meaning all insns are implemented as
13702              * a nop, or "active" when some action must be performed.
13703              * The decision of which action to take is left to a helper.
13704              */
13705             if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13706                 flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
13707             }
13708         }
13709
13710         if (cpu_isar_feature(aa64_bti, cpu)) {
13711             /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13712             if (sctlr & (current_el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13713                 flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
13714             }
13715             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
13716         }
13717     } else {
13718         *pc = env->regs[15];
13719         flags = FIELD_DP32(flags, TBFLAG_A32, THUMB, env->thumb);
13720         flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN, env->vfp.vec_len);
13721         flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE, env->vfp.vec_stride);
13722         flags = FIELD_DP32(flags, TBFLAG_A32, CONDEXEC, env->condexec_bits);
13723         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, arm_sctlr_b(env));
13724         flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
13725         if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)
13726             || arm_el_is_aa64(env, 1) || arm_feature(env, ARM_FEATURE_M)) {
13727             flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
13728         }
13729         /* Note that XSCALE_CPAR shares bits with VECSTRIDE */
13730         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13731             flags = FIELD_DP32(flags, TBFLAG_A32,
13732                                XSCALE_CPAR, env->cp15.c15_cpar);
13733         }
13734     }
13735
13736     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13737
13738     /* The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13739      * states defined in the ARM ARM for software singlestep:
13740      *  SS_ACTIVE   PSTATE.SS   State
13741      *     0            x       Inactive (the TB flag for SS is always 0)
13742      *     1            0       Active-pending
13743      *     1            1       Active-not-pending
13744      */
13745     if (arm_singlestep_active(env)) {
13746         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
13747         if (is_a64(env)) {
13748             if (env->pstate & PSTATE_SS) {
13749                 flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
13750             }
13751         } else {
13752             if (env->uncached_cpsr & PSTATE_SS) {
13753                 flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
13754             }
13755         }
13756     }
13757     if (arm_cpu_data_is_big_endian(env)) {
13758         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
13759     }
13760     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
13761
13762     if (arm_v7m_is_handler_mode(env)) {
13763         flags = FIELD_DP32(flags, TBFLAG_A32, HANDLER, 1);
13764     }
13765
13766     /* v8M always applies stack limit checks unless CCR.STKOFHFNMIGN is
13767      * suppressing them because the requested execution priority is less than 0.
13768      */
13769     if (arm_feature(env, ARM_FEATURE_V8) &&
13770         arm_feature(env, ARM_FEATURE_M) &&
13771         !((mmu_idx  & ARM_MMU_IDX_M_NEGPRI) &&
13772           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13773         flags = FIELD_DP32(flags, TBFLAG_A32, STACKCHECK, 1);
13774     }
13775
13776     if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13777         FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S) != env->v7m.secure) {
13778         flags = FIELD_DP32(flags, TBFLAG_A32, FPCCR_S_WRONG, 1);
13779     }
13780
13781     if (arm_feature(env, ARM_FEATURE_M) &&
13782         (env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13783         (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13784          (env->v7m.secure &&
13785           !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13786         /*
13787          * ASPEN is set, but FPCA/SFPA indicate that there is no active
13788          * FP context; we must create a new FP context before executing
13789          * any FP insn.
13790          */
13791         flags = FIELD_DP32(flags, TBFLAG_A32, NEW_FP_CTXT_NEEDED, 1);
13792     }
13793
13794     if (arm_feature(env, ARM_FEATURE_M)) {
13795         bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13796
13797         if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13798             flags = FIELD_DP32(flags, TBFLAG_A32, LSPACT, 1);
13799         }
13800     }
13801
13802     *pflags = flags;
13803     *cs_base = 0;
13804 }
13805
13806 #ifdef TARGET_AARCH64
13807 /*
13808  * The manual says that when SVE is enabled and VQ is widened the
13809  * implementation is allowed to zero the previously inaccessible
13810  * portion of the registers.  The corollary to that is that when
13811  * SVE is enabled and VQ is narrowed we are also allowed to zero
13812  * the now inaccessible portion of the registers.
13813  *
13814  * The intent of this is that no predicate bit beyond VQ is ever set.
13815  * Which means that some operations on predicate registers themselves
13816  * may operate on full uint64_t or even unrolled across the maximum
13817  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13818  * may well be cheaper than conditionals to restrict the operation
13819  * to the relevant portion of a uint16_t[16].
13820  */
13821 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13822 {
13823     int i, j;
13824     uint64_t pmask;
13825
13826     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13827     assert(vq <= env_archcpu(env)->sve_max_vq);
13828
13829     /* Zap the high bits of the zregs.  */
13830     for (i = 0; i < 32; i++) {
13831         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13832     }
13833
13834     /* Zap the high bits of the pregs and ffr.  */
13835     pmask = 0;
13836     if (vq & 3) {
13837         pmask = ~(-1ULL << (16 * (vq & 3)));
13838     }
13839     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13840         for (i = 0; i < 17; ++i) {
13841             env->vfp.pregs[i].p[j] &= pmask;
13842         }
13843         pmask = 0;
13844     }
13845 }
13846
13847 /*
13848  * Notice a change in SVE vector size when changing EL.
13849  */
13850 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13851                            int new_el, bool el0_a64)
13852 {
13853     ARMCPU *cpu = env_archcpu(env);
13854     int old_len, new_len;
13855     bool old_a64, new_a64;
13856
13857     /* Nothing to do if no SVE.  */
13858     if (!cpu_isar_feature(aa64_sve, cpu)) {
13859         return;
13860     }
13861
13862     /* Nothing to do if FP is disabled in either EL.  */
13863     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13864         return;
13865     }
13866
13867     /*
13868      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13869      * at ELx, or not available because the EL is in AArch32 state, then
13870      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13871      * has an effective value of 0".
13872      *
13873      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13874      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13875      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13876      * we already have the correct register contents when encountering the
13877      * vq0->vq0 transition between EL0->EL1.
13878      */
13879     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13880     old_len = (old_a64 && !sve_exception_el(env, old_el)
13881                ? sve_zcr_len_for_el(env, old_el) : 0);
13882     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13883     new_len = (new_a64 && !sve_exception_el(env, new_el)
13884                ? sve_zcr_len_for_el(env, new_el) : 0);
13885
13886     /* When changing vector length, clear inaccessible state.  */
13887     if (new_len < old_len) {
13888         aarch64_sve_narrow_vq(env, new_len + 1);
13889     }
13890 }
13891 #endif
This page took 0.806738 seconds and 4 git commands to generate.