]> Git Repo - qemu.git/blob - target/arm/helper.c
target/arm: Implement AArch32 Hyp FARs
[qemu.git] / target / arm / helper.c
1 #include "qemu/osdep.h"
2 #include "target/arm/idau.h"
3 #include "trace.h"
4 #include "cpu.h"
5 #include "internals.h"
6 #include "exec/gdbstub.h"
7 #include "exec/helper-proto.h"
8 #include "qemu/host-utils.h"
9 #include "sysemu/arch_init.h"
10 #include "sysemu/sysemu.h"
11 #include "qemu/bitops.h"
12 #include "qemu/crc32c.h"
13 #include "exec/exec-all.h"
14 #include "exec/cpu_ldst.h"
15 #include "arm_ldst.h"
16 #include <zlib.h> /* For crc32 */
17 #include "exec/semihost.h"
18 #include "sysemu/kvm.h"
19 #include "fpu/softfloat.h"
20 #include "qemu/range.h"
21
22 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
23
24 #ifndef CONFIG_USER_ONLY
25 /* Cacheability and shareability attributes for a memory access */
26 typedef struct ARMCacheAttrs {
27     unsigned int attrs:8; /* as in the MAIR register encoding */
28     unsigned int shareability:2; /* as in the SH field of the VMSAv8-64 PTEs */
29 } ARMCacheAttrs;
30
31 static bool get_phys_addr(CPUARMState *env, target_ulong address,
32                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
33                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
34                           target_ulong *page_size,
35                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
36
37 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
38                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
39                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
40                                target_ulong *page_size_ptr,
41                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
42
43 /* Security attributes for an address, as returned by v8m_security_lookup. */
44 typedef struct V8M_SAttributes {
45     bool subpage; /* true if these attrs don't cover the whole TARGET_PAGE */
46     bool ns;
47     bool nsc;
48     uint8_t sregion;
49     bool srvalid;
50     uint8_t iregion;
51     bool irvalid;
52 } V8M_SAttributes;
53
54 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
55                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
56                                 V8M_SAttributes *sattrs);
57 #endif
58
59 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
60 {
61     int nregs;
62
63     /* VFP data registers are always little-endian.  */
64     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
65     if (reg < nregs) {
66         stq_le_p(buf, *aa32_vfp_dreg(env, reg));
67         return 8;
68     }
69     if (arm_feature(env, ARM_FEATURE_NEON)) {
70         /* Aliases for Q regs.  */
71         nregs += 16;
72         if (reg < nregs) {
73             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
74             stq_le_p(buf, q[0]);
75             stq_le_p(buf + 8, q[1]);
76             return 16;
77         }
78     }
79     switch (reg - nregs) {
80     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
81     case 1: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSCR]); return 4;
82     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
83     }
84     return 0;
85 }
86
87 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
88 {
89     int nregs;
90
91     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
92     if (reg < nregs) {
93         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
94         return 8;
95     }
96     if (arm_feature(env, ARM_FEATURE_NEON)) {
97         nregs += 16;
98         if (reg < nregs) {
99             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
100             q[0] = ldq_le_p(buf);
101             q[1] = ldq_le_p(buf + 8);
102             return 16;
103         }
104     }
105     switch (reg - nregs) {
106     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
107     case 1: env->vfp.xregs[ARM_VFP_FPSCR] = ldl_p(buf); return 4;
108     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
109     }
110     return 0;
111 }
112
113 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
114 {
115     switch (reg) {
116     case 0 ... 31:
117         /* 128 bit FP register */
118         {
119             uint64_t *q = aa64_vfp_qreg(env, reg);
120             stq_le_p(buf, q[0]);
121             stq_le_p(buf + 8, q[1]);
122             return 16;
123         }
124     case 32:
125         /* FPSR */
126         stl_p(buf, vfp_get_fpsr(env));
127         return 4;
128     case 33:
129         /* FPCR */
130         stl_p(buf, vfp_get_fpcr(env));
131         return 4;
132     default:
133         return 0;
134     }
135 }
136
137 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
138 {
139     switch (reg) {
140     case 0 ... 31:
141         /* 128 bit FP register */
142         {
143             uint64_t *q = aa64_vfp_qreg(env, reg);
144             q[0] = ldq_le_p(buf);
145             q[1] = ldq_le_p(buf + 8);
146             return 16;
147         }
148     case 32:
149         /* FPSR */
150         vfp_set_fpsr(env, ldl_p(buf));
151         return 4;
152     case 33:
153         /* FPCR */
154         vfp_set_fpcr(env, ldl_p(buf));
155         return 4;
156     default:
157         return 0;
158     }
159 }
160
161 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
162 {
163     assert(ri->fieldoffset);
164     if (cpreg_field_is_64bit(ri)) {
165         return CPREG_FIELD64(env, ri);
166     } else {
167         return CPREG_FIELD32(env, ri);
168     }
169 }
170
171 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
172                       uint64_t value)
173 {
174     assert(ri->fieldoffset);
175     if (cpreg_field_is_64bit(ri)) {
176         CPREG_FIELD64(env, ri) = value;
177     } else {
178         CPREG_FIELD32(env, ri) = value;
179     }
180 }
181
182 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
183 {
184     return (char *)env + ri->fieldoffset;
185 }
186
187 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
188 {
189     /* Raw read of a coprocessor register (as needed for migration, etc). */
190     if (ri->type & ARM_CP_CONST) {
191         return ri->resetvalue;
192     } else if (ri->raw_readfn) {
193         return ri->raw_readfn(env, ri);
194     } else if (ri->readfn) {
195         return ri->readfn(env, ri);
196     } else {
197         return raw_read(env, ri);
198     }
199 }
200
201 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
202                              uint64_t v)
203 {
204     /* Raw write of a coprocessor register (as needed for migration, etc).
205      * Note that constant registers are treated as write-ignored; the
206      * caller should check for success by whether a readback gives the
207      * value written.
208      */
209     if (ri->type & ARM_CP_CONST) {
210         return;
211     } else if (ri->raw_writefn) {
212         ri->raw_writefn(env, ri, v);
213     } else if (ri->writefn) {
214         ri->writefn(env, ri, v);
215     } else {
216         raw_write(env, ri, v);
217     }
218 }
219
220 static int arm_gdb_get_sysreg(CPUARMState *env, uint8_t *buf, int reg)
221 {
222     ARMCPU *cpu = arm_env_get_cpu(env);
223     const ARMCPRegInfo *ri;
224     uint32_t key;
225
226     key = cpu->dyn_xml.cpregs_keys[reg];
227     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
228     if (ri) {
229         if (cpreg_field_is_64bit(ri)) {
230             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
231         } else {
232             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
233         }
234     }
235     return 0;
236 }
237
238 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
239 {
240     return 0;
241 }
242
243 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
244 {
245    /* Return true if the regdef would cause an assertion if you called
246     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
247     * program bug for it not to have the NO_RAW flag).
248     * NB that returning false here doesn't necessarily mean that calling
249     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
250     * read/write access functions which are safe for raw use" from "has
251     * read/write access functions which have side effects but has forgotten
252     * to provide raw access functions".
253     * The tests here line up with the conditions in read/write_raw_cp_reg()
254     * and assertions in raw_read()/raw_write().
255     */
256     if ((ri->type & ARM_CP_CONST) ||
257         ri->fieldoffset ||
258         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
259         return false;
260     }
261     return true;
262 }
263
264 bool write_cpustate_to_list(ARMCPU *cpu)
265 {
266     /* Write the coprocessor state from cpu->env to the (index,value) list. */
267     int i;
268     bool ok = true;
269
270     for (i = 0; i < cpu->cpreg_array_len; i++) {
271         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
272         const ARMCPRegInfo *ri;
273
274         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
275         if (!ri) {
276             ok = false;
277             continue;
278         }
279         if (ri->type & ARM_CP_NO_RAW) {
280             continue;
281         }
282         cpu->cpreg_values[i] = read_raw_cp_reg(&cpu->env, ri);
283     }
284     return ok;
285 }
286
287 bool write_list_to_cpustate(ARMCPU *cpu)
288 {
289     int i;
290     bool ok = true;
291
292     for (i = 0; i < cpu->cpreg_array_len; i++) {
293         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
294         uint64_t v = cpu->cpreg_values[i];
295         const ARMCPRegInfo *ri;
296
297         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
298         if (!ri) {
299             ok = false;
300             continue;
301         }
302         if (ri->type & ARM_CP_NO_RAW) {
303             continue;
304         }
305         /* Write value and confirm it reads back as written
306          * (to catch read-only registers and partially read-only
307          * registers where the incoming migration value doesn't match)
308          */
309         write_raw_cp_reg(&cpu->env, ri, v);
310         if (read_raw_cp_reg(&cpu->env, ri) != v) {
311             ok = false;
312         }
313     }
314     return ok;
315 }
316
317 static void add_cpreg_to_list(gpointer key, gpointer opaque)
318 {
319     ARMCPU *cpu = opaque;
320     uint64_t regidx;
321     const ARMCPRegInfo *ri;
322
323     regidx = *(uint32_t *)key;
324     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
325
326     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
327         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
328         /* The value array need not be initialized at this point */
329         cpu->cpreg_array_len++;
330     }
331 }
332
333 static void count_cpreg(gpointer key, gpointer opaque)
334 {
335     ARMCPU *cpu = opaque;
336     uint64_t regidx;
337     const ARMCPRegInfo *ri;
338
339     regidx = *(uint32_t *)key;
340     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
341
342     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
343         cpu->cpreg_array_len++;
344     }
345 }
346
347 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
348 {
349     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
350     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
351
352     if (aidx > bidx) {
353         return 1;
354     }
355     if (aidx < bidx) {
356         return -1;
357     }
358     return 0;
359 }
360
361 void init_cpreg_list(ARMCPU *cpu)
362 {
363     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
364      * Note that we require cpreg_tuples[] to be sorted by key ID.
365      */
366     GList *keys;
367     int arraylen;
368
369     keys = g_hash_table_get_keys(cpu->cp_regs);
370     keys = g_list_sort(keys, cpreg_key_compare);
371
372     cpu->cpreg_array_len = 0;
373
374     g_list_foreach(keys, count_cpreg, cpu);
375
376     arraylen = cpu->cpreg_array_len;
377     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
378     cpu->cpreg_values = g_new(uint64_t, arraylen);
379     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
380     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
381     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
382     cpu->cpreg_array_len = 0;
383
384     g_list_foreach(keys, add_cpreg_to_list, cpu);
385
386     assert(cpu->cpreg_array_len == arraylen);
387
388     g_list_free(keys);
389 }
390
391 /*
392  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
393  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
394  *
395  * access_el3_aa32ns: Used to check AArch32 register views.
396  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
397  */
398 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
399                                         const ARMCPRegInfo *ri,
400                                         bool isread)
401 {
402     bool secure = arm_is_secure_below_el3(env);
403
404     assert(!arm_el_is_aa64(env, 3));
405     if (secure) {
406         return CP_ACCESS_TRAP_UNCATEGORIZED;
407     }
408     return CP_ACCESS_OK;
409 }
410
411 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
412                                                 const ARMCPRegInfo *ri,
413                                                 bool isread)
414 {
415     if (!arm_el_is_aa64(env, 3)) {
416         return access_el3_aa32ns(env, ri, isread);
417     }
418     return CP_ACCESS_OK;
419 }
420
421 /* Some secure-only AArch32 registers trap to EL3 if used from
422  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
423  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
424  * We assume that the .access field is set to PL1_RW.
425  */
426 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
427                                             const ARMCPRegInfo *ri,
428                                             bool isread)
429 {
430     if (arm_current_el(env) == 3) {
431         return CP_ACCESS_OK;
432     }
433     if (arm_is_secure_below_el3(env)) {
434         return CP_ACCESS_TRAP_EL3;
435     }
436     /* This will be EL1 NS and EL2 NS, which just UNDEF */
437     return CP_ACCESS_TRAP_UNCATEGORIZED;
438 }
439
440 /* Check for traps to "powerdown debug" registers, which are controlled
441  * by MDCR.TDOSA
442  */
443 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
444                                    bool isread)
445 {
446     int el = arm_current_el(env);
447     bool mdcr_el2_tdosa = (env->cp15.mdcr_el2 & MDCR_TDOSA) ||
448         (env->cp15.mdcr_el2 & MDCR_TDE) ||
449         (env->cp15.hcr_el2 & HCR_TGE);
450
451     if (el < 2 && mdcr_el2_tdosa && !arm_is_secure_below_el3(env)) {
452         return CP_ACCESS_TRAP_EL2;
453     }
454     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
455         return CP_ACCESS_TRAP_EL3;
456     }
457     return CP_ACCESS_OK;
458 }
459
460 /* Check for traps to "debug ROM" registers, which are controlled
461  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
462  */
463 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
464                                   bool isread)
465 {
466     int el = arm_current_el(env);
467     bool mdcr_el2_tdra = (env->cp15.mdcr_el2 & MDCR_TDRA) ||
468         (env->cp15.mdcr_el2 & MDCR_TDE) ||
469         (env->cp15.hcr_el2 & HCR_TGE);
470
471     if (el < 2 && mdcr_el2_tdra && !arm_is_secure_below_el3(env)) {
472         return CP_ACCESS_TRAP_EL2;
473     }
474     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
475         return CP_ACCESS_TRAP_EL3;
476     }
477     return CP_ACCESS_OK;
478 }
479
480 /* Check for traps to general debug registers, which are controlled
481  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
482  */
483 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
484                                   bool isread)
485 {
486     int el = arm_current_el(env);
487     bool mdcr_el2_tda = (env->cp15.mdcr_el2 & MDCR_TDA) ||
488         (env->cp15.mdcr_el2 & MDCR_TDE) ||
489         (env->cp15.hcr_el2 & HCR_TGE);
490
491     if (el < 2 && mdcr_el2_tda && !arm_is_secure_below_el3(env)) {
492         return CP_ACCESS_TRAP_EL2;
493     }
494     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
495         return CP_ACCESS_TRAP_EL3;
496     }
497     return CP_ACCESS_OK;
498 }
499
500 /* Check for traps to performance monitor registers, which are controlled
501  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
502  */
503 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
504                                  bool isread)
505 {
506     int el = arm_current_el(env);
507
508     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
509         && !arm_is_secure_below_el3(env)) {
510         return CP_ACCESS_TRAP_EL2;
511     }
512     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
513         return CP_ACCESS_TRAP_EL3;
514     }
515     return CP_ACCESS_OK;
516 }
517
518 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
519 {
520     ARMCPU *cpu = arm_env_get_cpu(env);
521
522     raw_write(env, ri, value);
523     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
524 }
525
526 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
527 {
528     ARMCPU *cpu = arm_env_get_cpu(env);
529
530     if (raw_read(env, ri) != value) {
531         /* Unlike real hardware the qemu TLB uses virtual addresses,
532          * not modified virtual addresses, so this causes a TLB flush.
533          */
534         tlb_flush(CPU(cpu));
535         raw_write(env, ri, value);
536     }
537 }
538
539 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
540                              uint64_t value)
541 {
542     ARMCPU *cpu = arm_env_get_cpu(env);
543
544     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
545         && !extended_addresses_enabled(env)) {
546         /* For VMSA (when not using the LPAE long descriptor page table
547          * format) this register includes the ASID, so do a TLB flush.
548          * For PMSA it is purely a process ID and no action is needed.
549          */
550         tlb_flush(CPU(cpu));
551     }
552     raw_write(env, ri, value);
553 }
554
555 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
556                           uint64_t value)
557 {
558     /* Invalidate all (TLBIALL) */
559     ARMCPU *cpu = arm_env_get_cpu(env);
560
561     tlb_flush(CPU(cpu));
562 }
563
564 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
565                           uint64_t value)
566 {
567     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
568     ARMCPU *cpu = arm_env_get_cpu(env);
569
570     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
571 }
572
573 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
574                            uint64_t value)
575 {
576     /* Invalidate by ASID (TLBIASID) */
577     ARMCPU *cpu = arm_env_get_cpu(env);
578
579     tlb_flush(CPU(cpu));
580 }
581
582 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
583                            uint64_t value)
584 {
585     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
586     ARMCPU *cpu = arm_env_get_cpu(env);
587
588     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
589 }
590
591 /* IS variants of TLB operations must affect all cores */
592 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
593                              uint64_t value)
594 {
595     CPUState *cs = ENV_GET_CPU(env);
596
597     tlb_flush_all_cpus_synced(cs);
598 }
599
600 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
601                              uint64_t value)
602 {
603     CPUState *cs = ENV_GET_CPU(env);
604
605     tlb_flush_all_cpus_synced(cs);
606 }
607
608 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
609                              uint64_t value)
610 {
611     CPUState *cs = ENV_GET_CPU(env);
612
613     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
614 }
615
616 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
617                              uint64_t value)
618 {
619     CPUState *cs = ENV_GET_CPU(env);
620
621     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
622 }
623
624 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
625                                uint64_t value)
626 {
627     CPUState *cs = ENV_GET_CPU(env);
628
629     tlb_flush_by_mmuidx(cs,
630                         ARMMMUIdxBit_S12NSE1 |
631                         ARMMMUIdxBit_S12NSE0 |
632                         ARMMMUIdxBit_S2NS);
633 }
634
635 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
636                                   uint64_t value)
637 {
638     CPUState *cs = ENV_GET_CPU(env);
639
640     tlb_flush_by_mmuidx_all_cpus_synced(cs,
641                                         ARMMMUIdxBit_S12NSE1 |
642                                         ARMMMUIdxBit_S12NSE0 |
643                                         ARMMMUIdxBit_S2NS);
644 }
645
646 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
647                             uint64_t value)
648 {
649     /* Invalidate by IPA. This has to invalidate any structures that
650      * contain only stage 2 translation information, but does not need
651      * to apply to structures that contain combined stage 1 and stage 2
652      * translation information.
653      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
654      */
655     CPUState *cs = ENV_GET_CPU(env);
656     uint64_t pageaddr;
657
658     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
659         return;
660     }
661
662     pageaddr = sextract64(value << 12, 0, 40);
663
664     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
665 }
666
667 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
668                                uint64_t value)
669 {
670     CPUState *cs = ENV_GET_CPU(env);
671     uint64_t pageaddr;
672
673     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
674         return;
675     }
676
677     pageaddr = sextract64(value << 12, 0, 40);
678
679     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
680                                              ARMMMUIdxBit_S2NS);
681 }
682
683 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
684                               uint64_t value)
685 {
686     CPUState *cs = ENV_GET_CPU(env);
687
688     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
689 }
690
691 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
692                                  uint64_t value)
693 {
694     CPUState *cs = ENV_GET_CPU(env);
695
696     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
697 }
698
699 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
700                               uint64_t value)
701 {
702     CPUState *cs = ENV_GET_CPU(env);
703     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
704
705     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
706 }
707
708 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
709                                  uint64_t value)
710 {
711     CPUState *cs = ENV_GET_CPU(env);
712     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
713
714     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
715                                              ARMMMUIdxBit_S1E2);
716 }
717
718 static const ARMCPRegInfo cp_reginfo[] = {
719     /* Define the secure and non-secure FCSE identifier CP registers
720      * separately because there is no secure bank in V8 (no _EL3).  This allows
721      * the secure register to be properly reset and migrated. There is also no
722      * v8 EL1 version of the register so the non-secure instance stands alone.
723      */
724     { .name = "FCSEIDR",
725       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
726       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
727       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
728       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
729     { .name = "FCSEIDR_S",
730       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
731       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
732       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
733       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
734     /* Define the secure and non-secure context identifier CP registers
735      * separately because there is no secure bank in V8 (no _EL3).  This allows
736      * the secure register to be properly reset and migrated.  In the
737      * non-secure case, the 32-bit register will have reset and migration
738      * disabled during registration as it is handled by the 64-bit instance.
739      */
740     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
741       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
742       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
743       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
744       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
745     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
746       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
747       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
748       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
749       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
750     REGINFO_SENTINEL
751 };
752
753 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
754     /* NB: Some of these registers exist in v8 but with more precise
755      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
756      */
757     /* MMU Domain access control / MPU write buffer control */
758     { .name = "DACR",
759       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
760       .access = PL1_RW, .resetvalue = 0,
761       .writefn = dacr_write, .raw_writefn = raw_write,
762       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
763                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
764     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
765      * For v6 and v5, these mappings are overly broad.
766      */
767     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
768       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
769     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
770       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
771     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
772       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
773     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
774       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
775     /* Cache maintenance ops; some of this space may be overridden later. */
776     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
777       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
778       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
779     REGINFO_SENTINEL
780 };
781
782 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
783     /* Not all pre-v6 cores implemented this WFI, so this is slightly
784      * over-broad.
785      */
786     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
787       .access = PL1_W, .type = ARM_CP_WFI },
788     REGINFO_SENTINEL
789 };
790
791 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
792     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
793      * is UNPREDICTABLE; we choose to NOP as most implementations do).
794      */
795     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
796       .access = PL1_W, .type = ARM_CP_WFI },
797     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
798      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
799      * OMAPCP will override this space.
800      */
801     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
802       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
803       .resetvalue = 0 },
804     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
805       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
806       .resetvalue = 0 },
807     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
808     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
809       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
810       .resetvalue = 0 },
811     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
812      * implementing it as RAZ means the "debug architecture version" bits
813      * will read as a reserved value, which should cause Linux to not try
814      * to use the debug hardware.
815      */
816     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
817       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
818     /* MMU TLB control. Note that the wildcarding means we cover not just
819      * the unified TLB ops but also the dside/iside/inner-shareable variants.
820      */
821     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
822       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
823       .type = ARM_CP_NO_RAW },
824     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
825       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
826       .type = ARM_CP_NO_RAW },
827     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
828       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
829       .type = ARM_CP_NO_RAW },
830     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
831       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
832       .type = ARM_CP_NO_RAW },
833     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
834       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
835     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
836       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
837     REGINFO_SENTINEL
838 };
839
840 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
841                         uint64_t value)
842 {
843     uint32_t mask = 0;
844
845     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
846     if (!arm_feature(env, ARM_FEATURE_V8)) {
847         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
848          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
849          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
850          */
851         if (arm_feature(env, ARM_FEATURE_VFP)) {
852             /* VFP coprocessor: cp10 & cp11 [23:20] */
853             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
854
855             if (!arm_feature(env, ARM_FEATURE_NEON)) {
856                 /* ASEDIS [31] bit is RAO/WI */
857                 value |= (1 << 31);
858             }
859
860             /* VFPv3 and upwards with NEON implement 32 double precision
861              * registers (D0-D31).
862              */
863             if (!arm_feature(env, ARM_FEATURE_NEON) ||
864                     !arm_feature(env, ARM_FEATURE_VFP3)) {
865                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
866                 value |= (1 << 30);
867             }
868         }
869         value &= mask;
870     }
871     env->cp15.cpacr_el1 = value;
872 }
873
874 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
875 {
876     /* Call cpacr_write() so that we reset with the correct RAO bits set
877      * for our CPU features.
878      */
879     cpacr_write(env, ri, 0);
880 }
881
882 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
883                                    bool isread)
884 {
885     if (arm_feature(env, ARM_FEATURE_V8)) {
886         /* Check if CPACR accesses are to be trapped to EL2 */
887         if (arm_current_el(env) == 1 &&
888             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
889             return CP_ACCESS_TRAP_EL2;
890         /* Check if CPACR accesses are to be trapped to EL3 */
891         } else if (arm_current_el(env) < 3 &&
892                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
893             return CP_ACCESS_TRAP_EL3;
894         }
895     }
896
897     return CP_ACCESS_OK;
898 }
899
900 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
901                                   bool isread)
902 {
903     /* Check if CPTR accesses are set to trap to EL3 */
904     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
905         return CP_ACCESS_TRAP_EL3;
906     }
907
908     return CP_ACCESS_OK;
909 }
910
911 static const ARMCPRegInfo v6_cp_reginfo[] = {
912     /* prefetch by MVA in v6, NOP in v7 */
913     { .name = "MVA_prefetch",
914       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
915       .access = PL1_W, .type = ARM_CP_NOP },
916     /* We need to break the TB after ISB to execute self-modifying code
917      * correctly and also to take any pending interrupts immediately.
918      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
919      */
920     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
921       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
922     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
923       .access = PL0_W, .type = ARM_CP_NOP },
924     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
925       .access = PL0_W, .type = ARM_CP_NOP },
926     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
927       .access = PL1_RW,
928       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
929                              offsetof(CPUARMState, cp15.ifar_ns) },
930       .resetvalue = 0, },
931     /* Watchpoint Fault Address Register : should actually only be present
932      * for 1136, 1176, 11MPCore.
933      */
934     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
935       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
936     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
937       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
938       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
939       .resetfn = cpacr_reset, .writefn = cpacr_write },
940     REGINFO_SENTINEL
941 };
942
943 /* Definitions for the PMU registers */
944 #define PMCRN_MASK  0xf800
945 #define PMCRN_SHIFT 11
946 #define PMCRD   0x8
947 #define PMCRC   0x4
948 #define PMCRE   0x1
949
950 static inline uint32_t pmu_num_counters(CPUARMState *env)
951 {
952   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
953 }
954
955 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
956 static inline uint64_t pmu_counter_mask(CPUARMState *env)
957 {
958   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
959 }
960
961 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
962                                    bool isread)
963 {
964     /* Performance monitor registers user accessibility is controlled
965      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
966      * trapping to EL2 or EL3 for other accesses.
967      */
968     int el = arm_current_el(env);
969
970     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
971         return CP_ACCESS_TRAP;
972     }
973     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
974         && !arm_is_secure_below_el3(env)) {
975         return CP_ACCESS_TRAP_EL2;
976     }
977     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
978         return CP_ACCESS_TRAP_EL3;
979     }
980
981     return CP_ACCESS_OK;
982 }
983
984 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
985                                            const ARMCPRegInfo *ri,
986                                            bool isread)
987 {
988     /* ER: event counter read trap control */
989     if (arm_feature(env, ARM_FEATURE_V8)
990         && arm_current_el(env) == 0
991         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
992         && isread) {
993         return CP_ACCESS_OK;
994     }
995
996     return pmreg_access(env, ri, isread);
997 }
998
999 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1000                                          const ARMCPRegInfo *ri,
1001                                          bool isread)
1002 {
1003     /* SW: software increment write trap control */
1004     if (arm_feature(env, ARM_FEATURE_V8)
1005         && arm_current_el(env) == 0
1006         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1007         && !isread) {
1008         return CP_ACCESS_OK;
1009     }
1010
1011     return pmreg_access(env, ri, isread);
1012 }
1013
1014 #ifndef CONFIG_USER_ONLY
1015
1016 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1017                                         const ARMCPRegInfo *ri,
1018                                         bool isread)
1019 {
1020     /* ER: event counter read trap control */
1021     if (arm_feature(env, ARM_FEATURE_V8)
1022         && arm_current_el(env) == 0
1023         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1024         return CP_ACCESS_OK;
1025     }
1026
1027     return pmreg_access(env, ri, isread);
1028 }
1029
1030 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1031                                          const ARMCPRegInfo *ri,
1032                                          bool isread)
1033 {
1034     /* CR: cycle counter read trap control */
1035     if (arm_feature(env, ARM_FEATURE_V8)
1036         && arm_current_el(env) == 0
1037         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1038         && isread) {
1039         return CP_ACCESS_OK;
1040     }
1041
1042     return pmreg_access(env, ri, isread);
1043 }
1044
1045 static inline bool arm_ccnt_enabled(CPUARMState *env)
1046 {
1047     /* This does not support checking PMCCFILTR_EL0 register */
1048
1049     if (!(env->cp15.c9_pmcr & PMCRE) || !(env->cp15.c9_pmcnten & (1 << 31))) {
1050         return false;
1051     }
1052
1053     return true;
1054 }
1055
1056 void pmccntr_sync(CPUARMState *env)
1057 {
1058     uint64_t temp_ticks;
1059
1060     temp_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1061                           ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1062
1063     if (env->cp15.c9_pmcr & PMCRD) {
1064         /* Increment once every 64 processor clock cycles */
1065         temp_ticks /= 64;
1066     }
1067
1068     if (arm_ccnt_enabled(env)) {
1069         env->cp15.c15_ccnt = temp_ticks - env->cp15.c15_ccnt;
1070     }
1071 }
1072
1073 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1074                        uint64_t value)
1075 {
1076     pmccntr_sync(env);
1077
1078     if (value & PMCRC) {
1079         /* The counter has been reset */
1080         env->cp15.c15_ccnt = 0;
1081     }
1082
1083     /* only the DP, X, D and E bits are writable */
1084     env->cp15.c9_pmcr &= ~0x39;
1085     env->cp15.c9_pmcr |= (value & 0x39);
1086
1087     pmccntr_sync(env);
1088 }
1089
1090 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1091 {
1092     uint64_t total_ticks;
1093
1094     if (!arm_ccnt_enabled(env)) {
1095         /* Counter is disabled, do not change value */
1096         return env->cp15.c15_ccnt;
1097     }
1098
1099     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1100                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1101
1102     if (env->cp15.c9_pmcr & PMCRD) {
1103         /* Increment once every 64 processor clock cycles */
1104         total_ticks /= 64;
1105     }
1106     return total_ticks - env->cp15.c15_ccnt;
1107 }
1108
1109 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1110                          uint64_t value)
1111 {
1112     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1113      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1114      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1115      * accessed.
1116      */
1117     env->cp15.c9_pmselr = value & 0x1f;
1118 }
1119
1120 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1121                         uint64_t value)
1122 {
1123     uint64_t total_ticks;
1124
1125     if (!arm_ccnt_enabled(env)) {
1126         /* Counter is disabled, set the absolute value */
1127         env->cp15.c15_ccnt = value;
1128         return;
1129     }
1130
1131     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1132                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1133
1134     if (env->cp15.c9_pmcr & PMCRD) {
1135         /* Increment once every 64 processor clock cycles */
1136         total_ticks /= 64;
1137     }
1138     env->cp15.c15_ccnt = total_ticks - value;
1139 }
1140
1141 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1142                             uint64_t value)
1143 {
1144     uint64_t cur_val = pmccntr_read(env, NULL);
1145
1146     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1147 }
1148
1149 #else /* CONFIG_USER_ONLY */
1150
1151 void pmccntr_sync(CPUARMState *env)
1152 {
1153 }
1154
1155 #endif
1156
1157 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1158                             uint64_t value)
1159 {
1160     pmccntr_sync(env);
1161     env->cp15.pmccfiltr_el0 = value & 0xfc000000;
1162     pmccntr_sync(env);
1163 }
1164
1165 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1166                             uint64_t value)
1167 {
1168     value &= pmu_counter_mask(env);
1169     env->cp15.c9_pmcnten |= value;
1170 }
1171
1172 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1173                              uint64_t value)
1174 {
1175     value &= pmu_counter_mask(env);
1176     env->cp15.c9_pmcnten &= ~value;
1177 }
1178
1179 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1180                          uint64_t value)
1181 {
1182     env->cp15.c9_pmovsr &= ~value;
1183 }
1184
1185 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1186                              uint64_t value)
1187 {
1188     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1189      * PMSELR value is equal to or greater than the number of implemented
1190      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1191      */
1192     if (env->cp15.c9_pmselr == 0x1f) {
1193         pmccfiltr_write(env, ri, value);
1194     }
1195 }
1196
1197 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1198 {
1199     /* We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1200      * are CONSTRAINED UNPREDICTABLE. See comments in pmxevtyper_write().
1201      */
1202     if (env->cp15.c9_pmselr == 0x1f) {
1203         return env->cp15.pmccfiltr_el0;
1204     } else {
1205         return 0;
1206     }
1207 }
1208
1209 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1210                             uint64_t value)
1211 {
1212     if (arm_feature(env, ARM_FEATURE_V8)) {
1213         env->cp15.c9_pmuserenr = value & 0xf;
1214     } else {
1215         env->cp15.c9_pmuserenr = value & 1;
1216     }
1217 }
1218
1219 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1220                              uint64_t value)
1221 {
1222     /* We have no event counters so only the C bit can be changed */
1223     value &= pmu_counter_mask(env);
1224     env->cp15.c9_pminten |= value;
1225 }
1226
1227 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1228                              uint64_t value)
1229 {
1230     value &= pmu_counter_mask(env);
1231     env->cp15.c9_pminten &= ~value;
1232 }
1233
1234 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1235                        uint64_t value)
1236 {
1237     /* Note that even though the AArch64 view of this register has bits
1238      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1239      * architectural requirements for bits which are RES0 only in some
1240      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1241      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1242      */
1243     raw_write(env, ri, value & ~0x1FULL);
1244 }
1245
1246 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1247 {
1248     /* We only mask off bits that are RES0 both for AArch64 and AArch32.
1249      * For bits that vary between AArch32/64, code needs to check the
1250      * current execution mode before directly using the feature bit.
1251      */
1252     uint32_t valid_mask = SCR_AARCH64_MASK | SCR_AARCH32_MASK;
1253
1254     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1255         valid_mask &= ~SCR_HCE;
1256
1257         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1258          * supported if EL2 exists. The bit is UNK/SBZP when
1259          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1260          * when EL2 is unavailable.
1261          * On ARMv8, this bit is always available.
1262          */
1263         if (arm_feature(env, ARM_FEATURE_V7) &&
1264             !arm_feature(env, ARM_FEATURE_V8)) {
1265             valid_mask &= ~SCR_SMD;
1266         }
1267     }
1268
1269     /* Clear all-context RES0 bits.  */
1270     value &= valid_mask;
1271     raw_write(env, ri, value);
1272 }
1273
1274 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1275 {
1276     ARMCPU *cpu = arm_env_get_cpu(env);
1277
1278     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1279      * bank
1280      */
1281     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1282                                         ri->secure & ARM_CP_SECSTATE_S);
1283
1284     return cpu->ccsidr[index];
1285 }
1286
1287 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1288                          uint64_t value)
1289 {
1290     raw_write(env, ri, value & 0xf);
1291 }
1292
1293 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1294 {
1295     CPUState *cs = ENV_GET_CPU(env);
1296     uint64_t ret = 0;
1297
1298     if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1299         ret |= CPSR_I;
1300     }
1301     if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1302         ret |= CPSR_F;
1303     }
1304     /* External aborts are not possible in QEMU so A bit is always clear */
1305     return ret;
1306 }
1307
1308 static const ARMCPRegInfo v7_cp_reginfo[] = {
1309     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1310     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1311       .access = PL1_W, .type = ARM_CP_NOP },
1312     /* Performance monitors are implementation defined in v7,
1313      * but with an ARM recommended set of registers, which we
1314      * follow (although we don't actually implement any counters)
1315      *
1316      * Performance registers fall into three categories:
1317      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1318      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1319      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1320      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1321      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1322      */
1323     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1324       .access = PL0_RW, .type = ARM_CP_ALIAS,
1325       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1326       .writefn = pmcntenset_write,
1327       .accessfn = pmreg_access,
1328       .raw_writefn = raw_write },
1329     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1330       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1331       .access = PL0_RW, .accessfn = pmreg_access,
1332       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1333       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1334     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1335       .access = PL0_RW,
1336       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1337       .accessfn = pmreg_access,
1338       .writefn = pmcntenclr_write,
1339       .type = ARM_CP_ALIAS },
1340     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1341       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1342       .access = PL0_RW, .accessfn = pmreg_access,
1343       .type = ARM_CP_ALIAS,
1344       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1345       .writefn = pmcntenclr_write },
1346     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1347       .access = PL0_RW,
1348       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1349       .accessfn = pmreg_access,
1350       .writefn = pmovsr_write,
1351       .raw_writefn = raw_write },
1352     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1353       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1354       .access = PL0_RW, .accessfn = pmreg_access,
1355       .type = ARM_CP_ALIAS,
1356       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1357       .writefn = pmovsr_write,
1358       .raw_writefn = raw_write },
1359     /* Unimplemented so WI. */
1360     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1361       .access = PL0_W, .accessfn = pmreg_access_swinc, .type = ARM_CP_NOP },
1362 #ifndef CONFIG_USER_ONLY
1363     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1364       .access = PL0_RW, .type = ARM_CP_ALIAS,
1365       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1366       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1367       .raw_writefn = raw_write},
1368     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1369       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1370       .access = PL0_RW, .accessfn = pmreg_access_selr,
1371       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1372       .writefn = pmselr_write, .raw_writefn = raw_write, },
1373     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1374       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
1375       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1376       .accessfn = pmreg_access_ccntr },
1377     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1378       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1379       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1380       .type = ARM_CP_IO,
1381       .readfn = pmccntr_read, .writefn = pmccntr_write, },
1382 #endif
1383     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1384       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1385       .writefn = pmccfiltr_write,
1386       .access = PL0_RW, .accessfn = pmreg_access,
1387       .type = ARM_CP_IO,
1388       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1389       .resetvalue = 0, },
1390     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1391       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1392       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1393     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1394       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1395       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1396       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1397     /* Unimplemented, RAZ/WI. */
1398     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
1399       .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0,
1400       .accessfn = pmreg_access_xevcntr },
1401     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
1402       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
1403       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
1404       .resetvalue = 0,
1405       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1406     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
1407       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
1408       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1409       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
1410       .resetvalue = 0,
1411       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1412     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
1413       .access = PL1_RW, .accessfn = access_tpm,
1414       .type = ARM_CP_ALIAS | ARM_CP_IO,
1415       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
1416       .resetvalue = 0,
1417       .writefn = pmintenset_write, .raw_writefn = raw_write },
1418     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
1419       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
1420       .access = PL1_RW, .accessfn = access_tpm,
1421       .type = ARM_CP_IO,
1422       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1423       .writefn = pmintenset_write, .raw_writefn = raw_write,
1424       .resetvalue = 0x0 },
1425     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
1426       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1427       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1428       .writefn = pmintenclr_write, },
1429     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
1430       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
1431       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1432       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1433       .writefn = pmintenclr_write },
1434     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
1435       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
1436       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
1437     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
1438       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
1439       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
1440       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
1441                              offsetof(CPUARMState, cp15.csselr_ns) } },
1442     /* Auxiliary ID register: this actually has an IMPDEF value but for now
1443      * just RAZ for all cores:
1444      */
1445     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
1446       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
1447       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
1448     /* Auxiliary fault status registers: these also are IMPDEF, and we
1449      * choose to RAZ/WI for all cores.
1450      */
1451     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
1452       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
1453       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1454     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
1455       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
1456       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1457     /* MAIR can just read-as-written because we don't implement caches
1458      * and so don't need to care about memory attributes.
1459      */
1460     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
1461       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
1462       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
1463       .resetvalue = 0 },
1464     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
1465       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
1466       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
1467       .resetvalue = 0 },
1468     /* For non-long-descriptor page tables these are PRRR and NMRR;
1469      * regardless they still act as reads-as-written for QEMU.
1470      */
1471      /* MAIR0/1 are defined separately from their 64-bit counterpart which
1472       * allows them to assign the correct fieldoffset based on the endianness
1473       * handled in the field definitions.
1474       */
1475     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
1476       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
1477       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
1478                              offsetof(CPUARMState, cp15.mair0_ns) },
1479       .resetfn = arm_cp_reset_ignore },
1480     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
1481       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
1482       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
1483                              offsetof(CPUARMState, cp15.mair1_ns) },
1484       .resetfn = arm_cp_reset_ignore },
1485     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
1486       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
1487       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
1488     /* 32 bit ITLB invalidates */
1489     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
1490       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1491     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
1492       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1493     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
1494       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1495     /* 32 bit DTLB invalidates */
1496     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
1497       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1498     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
1499       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1500     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
1501       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1502     /* 32 bit TLB invalidates */
1503     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
1504       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1505     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
1506       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1507     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
1508       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1509     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
1510       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
1511     REGINFO_SENTINEL
1512 };
1513
1514 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
1515     /* 32 bit TLB invalidates, Inner Shareable */
1516     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
1517       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
1518     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
1519       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
1520     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
1521       .type = ARM_CP_NO_RAW, .access = PL1_W,
1522       .writefn = tlbiasid_is_write },
1523     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
1524       .type = ARM_CP_NO_RAW, .access = PL1_W,
1525       .writefn = tlbimvaa_is_write },
1526     REGINFO_SENTINEL
1527 };
1528
1529 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1530                         uint64_t value)
1531 {
1532     value &= 1;
1533     env->teecr = value;
1534 }
1535
1536 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1537                                     bool isread)
1538 {
1539     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
1540         return CP_ACCESS_TRAP;
1541     }
1542     return CP_ACCESS_OK;
1543 }
1544
1545 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
1546     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
1547       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
1548       .resetvalue = 0,
1549       .writefn = teecr_write },
1550     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
1551       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
1552       .accessfn = teehbr_access, .resetvalue = 0 },
1553     REGINFO_SENTINEL
1554 };
1555
1556 static const ARMCPRegInfo v6k_cp_reginfo[] = {
1557     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
1558       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
1559       .access = PL0_RW,
1560       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
1561     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
1562       .access = PL0_RW,
1563       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
1564                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
1565       .resetfn = arm_cp_reset_ignore },
1566     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
1567       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
1568       .access = PL0_R|PL1_W,
1569       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
1570       .resetvalue = 0},
1571     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
1572       .access = PL0_R|PL1_W,
1573       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
1574                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
1575       .resetfn = arm_cp_reset_ignore },
1576     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
1577       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
1578       .access = PL1_RW,
1579       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
1580     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
1581       .access = PL1_RW,
1582       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
1583                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
1584       .resetvalue = 0 },
1585     REGINFO_SENTINEL
1586 };
1587
1588 #ifndef CONFIG_USER_ONLY
1589
1590 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
1591                                        bool isread)
1592 {
1593     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
1594      * Writable only at the highest implemented exception level.
1595      */
1596     int el = arm_current_el(env);
1597
1598     switch (el) {
1599     case 0:
1600         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
1601             return CP_ACCESS_TRAP;
1602         }
1603         break;
1604     case 1:
1605         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
1606             arm_is_secure_below_el3(env)) {
1607             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
1608             return CP_ACCESS_TRAP_UNCATEGORIZED;
1609         }
1610         break;
1611     case 2:
1612     case 3:
1613         break;
1614     }
1615
1616     if (!isread && el < arm_highest_el(env)) {
1617         return CP_ACCESS_TRAP_UNCATEGORIZED;
1618     }
1619
1620     return CP_ACCESS_OK;
1621 }
1622
1623 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
1624                                         bool isread)
1625 {
1626     unsigned int cur_el = arm_current_el(env);
1627     bool secure = arm_is_secure(env);
1628
1629     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
1630     if (cur_el == 0 &&
1631         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
1632         return CP_ACCESS_TRAP;
1633     }
1634
1635     if (arm_feature(env, ARM_FEATURE_EL2) &&
1636         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1637         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
1638         return CP_ACCESS_TRAP_EL2;
1639     }
1640     return CP_ACCESS_OK;
1641 }
1642
1643 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
1644                                       bool isread)
1645 {
1646     unsigned int cur_el = arm_current_el(env);
1647     bool secure = arm_is_secure(env);
1648
1649     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
1650      * EL0[PV]TEN is zero.
1651      */
1652     if (cur_el == 0 &&
1653         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
1654         return CP_ACCESS_TRAP;
1655     }
1656
1657     if (arm_feature(env, ARM_FEATURE_EL2) &&
1658         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1659         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
1660         return CP_ACCESS_TRAP_EL2;
1661     }
1662     return CP_ACCESS_OK;
1663 }
1664
1665 static CPAccessResult gt_pct_access(CPUARMState *env,
1666                                     const ARMCPRegInfo *ri,
1667                                     bool isread)
1668 {
1669     return gt_counter_access(env, GTIMER_PHYS, isread);
1670 }
1671
1672 static CPAccessResult gt_vct_access(CPUARMState *env,
1673                                     const ARMCPRegInfo *ri,
1674                                     bool isread)
1675 {
1676     return gt_counter_access(env, GTIMER_VIRT, isread);
1677 }
1678
1679 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1680                                        bool isread)
1681 {
1682     return gt_timer_access(env, GTIMER_PHYS, isread);
1683 }
1684
1685 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1686                                        bool isread)
1687 {
1688     return gt_timer_access(env, GTIMER_VIRT, isread);
1689 }
1690
1691 static CPAccessResult gt_stimer_access(CPUARMState *env,
1692                                        const ARMCPRegInfo *ri,
1693                                        bool isread)
1694 {
1695     /* The AArch64 register view of the secure physical timer is
1696      * always accessible from EL3, and configurably accessible from
1697      * Secure EL1.
1698      */
1699     switch (arm_current_el(env)) {
1700     case 1:
1701         if (!arm_is_secure(env)) {
1702             return CP_ACCESS_TRAP;
1703         }
1704         if (!(env->cp15.scr_el3 & SCR_ST)) {
1705             return CP_ACCESS_TRAP_EL3;
1706         }
1707         return CP_ACCESS_OK;
1708     case 0:
1709     case 2:
1710         return CP_ACCESS_TRAP;
1711     case 3:
1712         return CP_ACCESS_OK;
1713     default:
1714         g_assert_not_reached();
1715     }
1716 }
1717
1718 static uint64_t gt_get_countervalue(CPUARMState *env)
1719 {
1720     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
1721 }
1722
1723 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
1724 {
1725     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
1726
1727     if (gt->ctl & 1) {
1728         /* Timer enabled: calculate and set current ISTATUS, irq, and
1729          * reset timer to when ISTATUS next has to change
1730          */
1731         uint64_t offset = timeridx == GTIMER_VIRT ?
1732                                       cpu->env.cp15.cntvoff_el2 : 0;
1733         uint64_t count = gt_get_countervalue(&cpu->env);
1734         /* Note that this must be unsigned 64 bit arithmetic: */
1735         int istatus = count - offset >= gt->cval;
1736         uint64_t nexttick;
1737         int irqstate;
1738
1739         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
1740
1741         irqstate = (istatus && !(gt->ctl & 2));
1742         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1743
1744         if (istatus) {
1745             /* Next transition is when count rolls back over to zero */
1746             nexttick = UINT64_MAX;
1747         } else {
1748             /* Next transition is when we hit cval */
1749             nexttick = gt->cval + offset;
1750         }
1751         /* Note that the desired next expiry time might be beyond the
1752          * signed-64-bit range of a QEMUTimer -- in this case we just
1753          * set the timer for as far in the future as possible. When the
1754          * timer expires we will reset the timer for any remaining period.
1755          */
1756         if (nexttick > INT64_MAX / GTIMER_SCALE) {
1757             nexttick = INT64_MAX / GTIMER_SCALE;
1758         }
1759         timer_mod(cpu->gt_timer[timeridx], nexttick);
1760         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
1761     } else {
1762         /* Timer disabled: ISTATUS and timer output always clear */
1763         gt->ctl &= ~4;
1764         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
1765         timer_del(cpu->gt_timer[timeridx]);
1766         trace_arm_gt_recalc_disabled(timeridx);
1767     }
1768 }
1769
1770 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
1771                            int timeridx)
1772 {
1773     ARMCPU *cpu = arm_env_get_cpu(env);
1774
1775     timer_del(cpu->gt_timer[timeridx]);
1776 }
1777
1778 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1779 {
1780     return gt_get_countervalue(env);
1781 }
1782
1783 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1784 {
1785     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
1786 }
1787
1788 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1789                           int timeridx,
1790                           uint64_t value)
1791 {
1792     trace_arm_gt_cval_write(timeridx, value);
1793     env->cp15.c14_timer[timeridx].cval = value;
1794     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1795 }
1796
1797 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
1798                              int timeridx)
1799 {
1800     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1801
1802     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
1803                       (gt_get_countervalue(env) - offset));
1804 }
1805
1806 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1807                           int timeridx,
1808                           uint64_t value)
1809 {
1810     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1811
1812     trace_arm_gt_tval_write(timeridx, value);
1813     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
1814                                          sextract64(value, 0, 32);
1815     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1816 }
1817
1818 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1819                          int timeridx,
1820                          uint64_t value)
1821 {
1822     ARMCPU *cpu = arm_env_get_cpu(env);
1823     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
1824
1825     trace_arm_gt_ctl_write(timeridx, value);
1826     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
1827     if ((oldval ^ value) & 1) {
1828         /* Enable toggled */
1829         gt_recalc_timer(cpu, timeridx);
1830     } else if ((oldval ^ value) & 2) {
1831         /* IMASK toggled: don't need to recalculate,
1832          * just set the interrupt line based on ISTATUS
1833          */
1834         int irqstate = (oldval & 4) && !(value & 2);
1835
1836         trace_arm_gt_imask_toggle(timeridx, irqstate);
1837         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1838     }
1839 }
1840
1841 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1842 {
1843     gt_timer_reset(env, ri, GTIMER_PHYS);
1844 }
1845
1846 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1847                                uint64_t value)
1848 {
1849     gt_cval_write(env, ri, GTIMER_PHYS, value);
1850 }
1851
1852 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1853 {
1854     return gt_tval_read(env, ri, GTIMER_PHYS);
1855 }
1856
1857 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1858                                uint64_t value)
1859 {
1860     gt_tval_write(env, ri, GTIMER_PHYS, value);
1861 }
1862
1863 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1864                               uint64_t value)
1865 {
1866     gt_ctl_write(env, ri, GTIMER_PHYS, value);
1867 }
1868
1869 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1870 {
1871     gt_timer_reset(env, ri, GTIMER_VIRT);
1872 }
1873
1874 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1875                                uint64_t value)
1876 {
1877     gt_cval_write(env, ri, GTIMER_VIRT, value);
1878 }
1879
1880 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1881 {
1882     return gt_tval_read(env, ri, GTIMER_VIRT);
1883 }
1884
1885 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1886                                uint64_t value)
1887 {
1888     gt_tval_write(env, ri, GTIMER_VIRT, value);
1889 }
1890
1891 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1892                               uint64_t value)
1893 {
1894     gt_ctl_write(env, ri, GTIMER_VIRT, value);
1895 }
1896
1897 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
1898                               uint64_t value)
1899 {
1900     ARMCPU *cpu = arm_env_get_cpu(env);
1901
1902     trace_arm_gt_cntvoff_write(value);
1903     raw_write(env, ri, value);
1904     gt_recalc_timer(cpu, GTIMER_VIRT);
1905 }
1906
1907 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1908 {
1909     gt_timer_reset(env, ri, GTIMER_HYP);
1910 }
1911
1912 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1913                               uint64_t value)
1914 {
1915     gt_cval_write(env, ri, GTIMER_HYP, value);
1916 }
1917
1918 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1919 {
1920     return gt_tval_read(env, ri, GTIMER_HYP);
1921 }
1922
1923 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1924                               uint64_t value)
1925 {
1926     gt_tval_write(env, ri, GTIMER_HYP, value);
1927 }
1928
1929 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1930                               uint64_t value)
1931 {
1932     gt_ctl_write(env, ri, GTIMER_HYP, value);
1933 }
1934
1935 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1936 {
1937     gt_timer_reset(env, ri, GTIMER_SEC);
1938 }
1939
1940 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1941                               uint64_t value)
1942 {
1943     gt_cval_write(env, ri, GTIMER_SEC, value);
1944 }
1945
1946 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1947 {
1948     return gt_tval_read(env, ri, GTIMER_SEC);
1949 }
1950
1951 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1952                               uint64_t value)
1953 {
1954     gt_tval_write(env, ri, GTIMER_SEC, value);
1955 }
1956
1957 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1958                               uint64_t value)
1959 {
1960     gt_ctl_write(env, ri, GTIMER_SEC, value);
1961 }
1962
1963 void arm_gt_ptimer_cb(void *opaque)
1964 {
1965     ARMCPU *cpu = opaque;
1966
1967     gt_recalc_timer(cpu, GTIMER_PHYS);
1968 }
1969
1970 void arm_gt_vtimer_cb(void *opaque)
1971 {
1972     ARMCPU *cpu = opaque;
1973
1974     gt_recalc_timer(cpu, GTIMER_VIRT);
1975 }
1976
1977 void arm_gt_htimer_cb(void *opaque)
1978 {
1979     ARMCPU *cpu = opaque;
1980
1981     gt_recalc_timer(cpu, GTIMER_HYP);
1982 }
1983
1984 void arm_gt_stimer_cb(void *opaque)
1985 {
1986     ARMCPU *cpu = opaque;
1987
1988     gt_recalc_timer(cpu, GTIMER_SEC);
1989 }
1990
1991 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
1992     /* Note that CNTFRQ is purely reads-as-written for the benefit
1993      * of software; writing it doesn't actually change the timer frequency.
1994      * Our reset value matches the fixed frequency we implement the timer at.
1995      */
1996     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
1997       .type = ARM_CP_ALIAS,
1998       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1999       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2000     },
2001     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2002       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2003       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2004       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2005       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
2006     },
2007     /* overall control: mostly access permissions */
2008     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2009       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2010       .access = PL1_RW,
2011       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2012       .resetvalue = 0,
2013     },
2014     /* per-timer control */
2015     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2016       .secure = ARM_CP_SECSTATE_NS,
2017       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2018       .accessfn = gt_ptimer_access,
2019       .fieldoffset = offsetoflow32(CPUARMState,
2020                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2021       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2022     },
2023     { .name = "CNTP_CTL_S",
2024       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2025       .secure = ARM_CP_SECSTATE_S,
2026       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2027       .accessfn = gt_ptimer_access,
2028       .fieldoffset = offsetoflow32(CPUARMState,
2029                                    cp15.c14_timer[GTIMER_SEC].ctl),
2030       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2031     },
2032     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2033       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2034       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
2035       .accessfn = gt_ptimer_access,
2036       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2037       .resetvalue = 0,
2038       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2039     },
2040     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2041       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2042       .accessfn = gt_vtimer_access,
2043       .fieldoffset = offsetoflow32(CPUARMState,
2044                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2045       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2046     },
2047     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2048       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2049       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
2050       .accessfn = gt_vtimer_access,
2051       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2052       .resetvalue = 0,
2053       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2054     },
2055     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2056     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2057       .secure = ARM_CP_SECSTATE_NS,
2058       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2059       .accessfn = gt_ptimer_access,
2060       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2061     },
2062     { .name = "CNTP_TVAL_S",
2063       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2064       .secure = ARM_CP_SECSTATE_S,
2065       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2066       .accessfn = gt_ptimer_access,
2067       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2068     },
2069     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2070       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2071       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2072       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2073       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2074     },
2075     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2076       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2077       .accessfn = gt_vtimer_access,
2078       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2079     },
2080     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2081       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2082       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2083       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2084       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2085     },
2086     /* The counter itself */
2087     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2088       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2089       .accessfn = gt_pct_access,
2090       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2091     },
2092     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2093       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2094       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2095       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2096     },
2097     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2098       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2099       .accessfn = gt_vct_access,
2100       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2101     },
2102     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2103       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2104       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2105       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2106     },
2107     /* Comparison value, indicating when the timer goes off */
2108     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2109       .secure = ARM_CP_SECSTATE_NS,
2110       .access = PL1_RW | PL0_R,
2111       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2112       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2113       .accessfn = gt_ptimer_access,
2114       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2115     },
2116     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
2117       .secure = ARM_CP_SECSTATE_S,
2118       .access = PL1_RW | PL0_R,
2119       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2120       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2121       .accessfn = gt_ptimer_access,
2122       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2123     },
2124     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2125       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2126       .access = PL1_RW | PL0_R,
2127       .type = ARM_CP_IO,
2128       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2129       .resetvalue = 0, .accessfn = gt_ptimer_access,
2130       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2131     },
2132     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2133       .access = PL1_RW | PL0_R,
2134       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2135       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2136       .accessfn = gt_vtimer_access,
2137       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2138     },
2139     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2140       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2141       .access = PL1_RW | PL0_R,
2142       .type = ARM_CP_IO,
2143       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2144       .resetvalue = 0, .accessfn = gt_vtimer_access,
2145       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2146     },
2147     /* Secure timer -- this is actually restricted to only EL3
2148      * and configurably Secure-EL1 via the accessfn.
2149      */
2150     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2151       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2152       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2153       .accessfn = gt_stimer_access,
2154       .readfn = gt_sec_tval_read,
2155       .writefn = gt_sec_tval_write,
2156       .resetfn = gt_sec_timer_reset,
2157     },
2158     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2159       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2160       .type = ARM_CP_IO, .access = PL1_RW,
2161       .accessfn = gt_stimer_access,
2162       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2163       .resetvalue = 0,
2164       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2165     },
2166     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2167       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2168       .type = ARM_CP_IO, .access = PL1_RW,
2169       .accessfn = gt_stimer_access,
2170       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2171       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2172     },
2173     REGINFO_SENTINEL
2174 };
2175
2176 #else
2177
2178 /* In user-mode most of the generic timer registers are inaccessible
2179  * however modern kernels (4.12+) allow access to cntvct_el0
2180  */
2181
2182 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2183 {
2184     /* Currently we have no support for QEMUTimer in linux-user so we
2185      * can't call gt_get_countervalue(env), instead we directly
2186      * call the lower level functions.
2187      */
2188     return cpu_get_clock() / GTIMER_SCALE;
2189 }
2190
2191 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2192     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2193       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2194       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
2195       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2196       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
2197     },
2198     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2199       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2200       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2201       .readfn = gt_virt_cnt_read,
2202     },
2203     REGINFO_SENTINEL
2204 };
2205
2206 #endif
2207
2208 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2209 {
2210     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2211         raw_write(env, ri, value);
2212     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2213         raw_write(env, ri, value & 0xfffff6ff);
2214     } else {
2215         raw_write(env, ri, value & 0xfffff1ff);
2216     }
2217 }
2218
2219 #ifndef CONFIG_USER_ONLY
2220 /* get_phys_addr() isn't present for user-mode-only targets */
2221
2222 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2223                                  bool isread)
2224 {
2225     if (ri->opc2 & 4) {
2226         /* The ATS12NSO* operations must trap to EL3 if executed in
2227          * Secure EL1 (which can only happen if EL3 is AArch64).
2228          * They are simply UNDEF if executed from NS EL1.
2229          * They function normally from EL2 or EL3.
2230          */
2231         if (arm_current_el(env) == 1) {
2232             if (arm_is_secure_below_el3(env)) {
2233                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2234             }
2235             return CP_ACCESS_TRAP_UNCATEGORIZED;
2236         }
2237     }
2238     return CP_ACCESS_OK;
2239 }
2240
2241 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2242                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2243 {
2244     hwaddr phys_addr;
2245     target_ulong page_size;
2246     int prot;
2247     bool ret;
2248     uint64_t par64;
2249     bool format64 = false;
2250     MemTxAttrs attrs = {};
2251     ARMMMUFaultInfo fi = {};
2252     ARMCacheAttrs cacheattrs = {};
2253
2254     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2255                         &prot, &page_size, &fi, &cacheattrs);
2256
2257     if (is_a64(env)) {
2258         format64 = true;
2259     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
2260         /*
2261          * ATS1Cxx:
2262          * * TTBCR.EAE determines whether the result is returned using the
2263          *   32-bit or the 64-bit PAR format
2264          * * Instructions executed in Hyp mode always use the 64bit format
2265          *
2266          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
2267          * * The Non-secure TTBCR.EAE bit is set to 1
2268          * * The implementation includes EL2, and the value of HCR.VM is 1
2269          *
2270          * ATS1Hx always uses the 64bit format (not supported yet).
2271          */
2272         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
2273
2274         if (arm_feature(env, ARM_FEATURE_EL2)) {
2275             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
2276                 format64 |= env->cp15.hcr_el2 & HCR_VM;
2277             } else {
2278                 format64 |= arm_current_el(env) == 2;
2279             }
2280         }
2281     }
2282
2283     if (format64) {
2284         /* Create a 64-bit PAR */
2285         par64 = (1 << 11); /* LPAE bit always set */
2286         if (!ret) {
2287             par64 |= phys_addr & ~0xfffULL;
2288             if (!attrs.secure) {
2289                 par64 |= (1 << 9); /* NS */
2290             }
2291             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
2292             par64 |= cacheattrs.shareability << 7; /* SH */
2293         } else {
2294             uint32_t fsr = arm_fi_to_lfsc(&fi);
2295
2296             par64 |= 1; /* F */
2297             par64 |= (fsr & 0x3f) << 1; /* FS */
2298             /* Note that S2WLK and FSTAGE are always zero, because we don't
2299              * implement virtualization and therefore there can't be a stage 2
2300              * fault.
2301              */
2302         }
2303     } else {
2304         /* fsr is a DFSR/IFSR value for the short descriptor
2305          * translation table format (with WnR always clear).
2306          * Convert it to a 32-bit PAR.
2307          */
2308         if (!ret) {
2309             /* We do not set any attribute bits in the PAR */
2310             if (page_size == (1 << 24)
2311                 && arm_feature(env, ARM_FEATURE_V7)) {
2312                 par64 = (phys_addr & 0xff000000) | (1 << 1);
2313             } else {
2314                 par64 = phys_addr & 0xfffff000;
2315             }
2316             if (!attrs.secure) {
2317                 par64 |= (1 << 9); /* NS */
2318             }
2319         } else {
2320             uint32_t fsr = arm_fi_to_sfsc(&fi);
2321
2322             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
2323                     ((fsr & 0xf) << 1) | 1;
2324         }
2325     }
2326     return par64;
2327 }
2328
2329 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2330 {
2331     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2332     uint64_t par64;
2333     ARMMMUIdx mmu_idx;
2334     int el = arm_current_el(env);
2335     bool secure = arm_is_secure_below_el3(env);
2336
2337     switch (ri->opc2 & 6) {
2338     case 0:
2339         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
2340         switch (el) {
2341         case 3:
2342             mmu_idx = ARMMMUIdx_S1E3;
2343             break;
2344         case 2:
2345             mmu_idx = ARMMMUIdx_S1NSE1;
2346             break;
2347         case 1:
2348             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2349             break;
2350         default:
2351             g_assert_not_reached();
2352         }
2353         break;
2354     case 2:
2355         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
2356         switch (el) {
2357         case 3:
2358             mmu_idx = ARMMMUIdx_S1SE0;
2359             break;
2360         case 2:
2361             mmu_idx = ARMMMUIdx_S1NSE0;
2362             break;
2363         case 1:
2364             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2365             break;
2366         default:
2367             g_assert_not_reached();
2368         }
2369         break;
2370     case 4:
2371         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
2372         mmu_idx = ARMMMUIdx_S12NSE1;
2373         break;
2374     case 6:
2375         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
2376         mmu_idx = ARMMMUIdx_S12NSE0;
2377         break;
2378     default:
2379         g_assert_not_reached();
2380     }
2381
2382     par64 = do_ats_write(env, value, access_type, mmu_idx);
2383
2384     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2385 }
2386
2387 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
2388                         uint64_t value)
2389 {
2390     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2391     uint64_t par64;
2392
2393     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S2NS);
2394
2395     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2396 }
2397
2398 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
2399                                      bool isread)
2400 {
2401     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
2402         return CP_ACCESS_TRAP;
2403     }
2404     return CP_ACCESS_OK;
2405 }
2406
2407 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
2408                         uint64_t value)
2409 {
2410     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2411     ARMMMUIdx mmu_idx;
2412     int secure = arm_is_secure_below_el3(env);
2413
2414     switch (ri->opc2 & 6) {
2415     case 0:
2416         switch (ri->opc1) {
2417         case 0: /* AT S1E1R, AT S1E1W */
2418             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2419             break;
2420         case 4: /* AT S1E2R, AT S1E2W */
2421             mmu_idx = ARMMMUIdx_S1E2;
2422             break;
2423         case 6: /* AT S1E3R, AT S1E3W */
2424             mmu_idx = ARMMMUIdx_S1E3;
2425             break;
2426         default:
2427             g_assert_not_reached();
2428         }
2429         break;
2430     case 2: /* AT S1E0R, AT S1E0W */
2431         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2432         break;
2433     case 4: /* AT S12E1R, AT S12E1W */
2434         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
2435         break;
2436     case 6: /* AT S12E0R, AT S12E0W */
2437         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
2438         break;
2439     default:
2440         g_assert_not_reached();
2441     }
2442
2443     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
2444 }
2445 #endif
2446
2447 static const ARMCPRegInfo vapa_cp_reginfo[] = {
2448     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
2449       .access = PL1_RW, .resetvalue = 0,
2450       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
2451                              offsetoflow32(CPUARMState, cp15.par_ns) },
2452       .writefn = par_write },
2453 #ifndef CONFIG_USER_ONLY
2454     /* This underdecoding is safe because the reginfo is NO_RAW. */
2455     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
2456       .access = PL1_W, .accessfn = ats_access,
2457       .writefn = ats_write, .type = ARM_CP_NO_RAW },
2458 #endif
2459     REGINFO_SENTINEL
2460 };
2461
2462 /* Return basic MPU access permission bits.  */
2463 static uint32_t simple_mpu_ap_bits(uint32_t val)
2464 {
2465     uint32_t ret;
2466     uint32_t mask;
2467     int i;
2468     ret = 0;
2469     mask = 3;
2470     for (i = 0; i < 16; i += 2) {
2471         ret |= (val >> i) & mask;
2472         mask <<= 2;
2473     }
2474     return ret;
2475 }
2476
2477 /* Pad basic MPU access permission bits to extended format.  */
2478 static uint32_t extended_mpu_ap_bits(uint32_t val)
2479 {
2480     uint32_t ret;
2481     uint32_t mask;
2482     int i;
2483     ret = 0;
2484     mask = 3;
2485     for (i = 0; i < 16; i += 2) {
2486         ret |= (val & mask) << i;
2487         mask <<= 2;
2488     }
2489     return ret;
2490 }
2491
2492 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2493                                  uint64_t value)
2494 {
2495     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
2496 }
2497
2498 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2499 {
2500     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
2501 }
2502
2503 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2504                                  uint64_t value)
2505 {
2506     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
2507 }
2508
2509 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2510 {
2511     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
2512 }
2513
2514 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
2515 {
2516     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2517
2518     if (!u32p) {
2519         return 0;
2520     }
2521
2522     u32p += env->pmsav7.rnr[M_REG_NS];
2523     return *u32p;
2524 }
2525
2526 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
2527                          uint64_t value)
2528 {
2529     ARMCPU *cpu = arm_env_get_cpu(env);
2530     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2531
2532     if (!u32p) {
2533         return;
2534     }
2535
2536     u32p += env->pmsav7.rnr[M_REG_NS];
2537     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
2538     *u32p = value;
2539 }
2540
2541 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2542                               uint64_t value)
2543 {
2544     ARMCPU *cpu = arm_env_get_cpu(env);
2545     uint32_t nrgs = cpu->pmsav7_dregion;
2546
2547     if (value >= nrgs) {
2548         qemu_log_mask(LOG_GUEST_ERROR,
2549                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
2550                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
2551         return;
2552     }
2553
2554     raw_write(env, ri, value);
2555 }
2556
2557 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
2558     /* Reset for all these registers is handled in arm_cpu_reset(),
2559      * because the PMSAv7 is also used by M-profile CPUs, which do
2560      * not register cpregs but still need the state to be reset.
2561      */
2562     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
2563       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2564       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
2565       .readfn = pmsav7_read, .writefn = pmsav7_write,
2566       .resetfn = arm_cp_reset_ignore },
2567     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
2568       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2569       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
2570       .readfn = pmsav7_read, .writefn = pmsav7_write,
2571       .resetfn = arm_cp_reset_ignore },
2572     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
2573       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2574       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
2575       .readfn = pmsav7_read, .writefn = pmsav7_write,
2576       .resetfn = arm_cp_reset_ignore },
2577     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
2578       .access = PL1_RW,
2579       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
2580       .writefn = pmsav7_rgnr_write,
2581       .resetfn = arm_cp_reset_ignore },
2582     REGINFO_SENTINEL
2583 };
2584
2585 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
2586     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2587       .access = PL1_RW, .type = ARM_CP_ALIAS,
2588       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2589       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
2590     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2591       .access = PL1_RW, .type = ARM_CP_ALIAS,
2592       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2593       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
2594     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
2595       .access = PL1_RW,
2596       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2597       .resetvalue = 0, },
2598     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
2599       .access = PL1_RW,
2600       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2601       .resetvalue = 0, },
2602     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
2603       .access = PL1_RW,
2604       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
2605     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
2606       .access = PL1_RW,
2607       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
2608     /* Protection region base and size registers */
2609     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
2610       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2611       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
2612     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
2613       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2614       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
2615     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
2616       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2617       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
2618     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
2619       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2620       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
2621     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
2622       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2623       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
2624     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
2625       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2626       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
2627     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
2628       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2629       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
2630     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
2631       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2632       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
2633     REGINFO_SENTINEL
2634 };
2635
2636 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
2637                                  uint64_t value)
2638 {
2639     TCR *tcr = raw_ptr(env, ri);
2640     int maskshift = extract32(value, 0, 3);
2641
2642     if (!arm_feature(env, ARM_FEATURE_V8)) {
2643         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
2644             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
2645              * using Long-desciptor translation table format */
2646             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
2647         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
2648             /* In an implementation that includes the Security Extensions
2649              * TTBCR has additional fields PD0 [4] and PD1 [5] for
2650              * Short-descriptor translation table format.
2651              */
2652             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
2653         } else {
2654             value &= TTBCR_N;
2655         }
2656     }
2657
2658     /* Update the masks corresponding to the TCR bank being written
2659      * Note that we always calculate mask and base_mask, but
2660      * they are only used for short-descriptor tables (ie if EAE is 0);
2661      * for long-descriptor tables the TCR fields are used differently
2662      * and the mask and base_mask values are meaningless.
2663      */
2664     tcr->raw_tcr = value;
2665     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
2666     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
2667 }
2668
2669 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2670                              uint64_t value)
2671 {
2672     ARMCPU *cpu = arm_env_get_cpu(env);
2673
2674     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2675         /* With LPAE the TTBCR could result in a change of ASID
2676          * via the TTBCR.A1 bit, so do a TLB flush.
2677          */
2678         tlb_flush(CPU(cpu));
2679     }
2680     vmsa_ttbcr_raw_write(env, ri, value);
2681 }
2682
2683 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2684 {
2685     TCR *tcr = raw_ptr(env, ri);
2686
2687     /* Reset both the TCR as well as the masks corresponding to the bank of
2688      * the TCR being reset.
2689      */
2690     tcr->raw_tcr = 0;
2691     tcr->mask = 0;
2692     tcr->base_mask = 0xffffc000u;
2693 }
2694
2695 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
2696                                uint64_t value)
2697 {
2698     ARMCPU *cpu = arm_env_get_cpu(env);
2699     TCR *tcr = raw_ptr(env, ri);
2700
2701     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
2702     tlb_flush(CPU(cpu));
2703     tcr->raw_tcr = value;
2704 }
2705
2706 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2707                             uint64_t value)
2708 {
2709     /* 64 bit accesses to the TTBRs can change the ASID and so we
2710      * must flush the TLB.
2711      */
2712     if (cpreg_field_is_64bit(ri)) {
2713         ARMCPU *cpu = arm_env_get_cpu(env);
2714
2715         tlb_flush(CPU(cpu));
2716     }
2717     raw_write(env, ri, value);
2718 }
2719
2720 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2721                         uint64_t value)
2722 {
2723     ARMCPU *cpu = arm_env_get_cpu(env);
2724     CPUState *cs = CPU(cpu);
2725
2726     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
2727     if (raw_read(env, ri) != value) {
2728         tlb_flush_by_mmuidx(cs,
2729                             ARMMMUIdxBit_S12NSE1 |
2730                             ARMMMUIdxBit_S12NSE0 |
2731                             ARMMMUIdxBit_S2NS);
2732         raw_write(env, ri, value);
2733     }
2734 }
2735
2736 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
2737     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2738       .access = PL1_RW, .type = ARM_CP_ALIAS,
2739       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
2740                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
2741     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2742       .access = PL1_RW, .resetvalue = 0,
2743       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
2744                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
2745     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
2746       .access = PL1_RW, .resetvalue = 0,
2747       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
2748                              offsetof(CPUARMState, cp15.dfar_ns) } },
2749     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
2750       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
2751       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
2752       .resetvalue = 0, },
2753     REGINFO_SENTINEL
2754 };
2755
2756 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
2757     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
2758       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
2759       .access = PL1_RW,
2760       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
2761     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
2762       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
2763       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2764       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2765                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
2766     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
2767       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
2768       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2769       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2770                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
2771     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
2772       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2773       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
2774       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
2775       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
2776     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2777       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
2778       .raw_writefn = vmsa_ttbcr_raw_write,
2779       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
2780                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
2781     REGINFO_SENTINEL
2782 };
2783
2784 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
2785                                 uint64_t value)
2786 {
2787     env->cp15.c15_ticonfig = value & 0xe7;
2788     /* The OS_TYPE bit in this register changes the reported CPUID! */
2789     env->cp15.c0_cpuid = (value & (1 << 5)) ?
2790         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
2791 }
2792
2793 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
2794                                 uint64_t value)
2795 {
2796     env->cp15.c15_threadid = value & 0xffff;
2797 }
2798
2799 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
2800                            uint64_t value)
2801 {
2802     /* Wait-for-interrupt (deprecated) */
2803     cpu_interrupt(CPU(arm_env_get_cpu(env)), CPU_INTERRUPT_HALT);
2804 }
2805
2806 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
2807                                   uint64_t value)
2808 {
2809     /* On OMAP there are registers indicating the max/min index of dcache lines
2810      * containing a dirty line; cache flush operations have to reset these.
2811      */
2812     env->cp15.c15_i_max = 0x000;
2813     env->cp15.c15_i_min = 0xff0;
2814 }
2815
2816 static const ARMCPRegInfo omap_cp_reginfo[] = {
2817     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
2818       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
2819       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
2820       .resetvalue = 0, },
2821     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
2822       .access = PL1_RW, .type = ARM_CP_NOP },
2823     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
2824       .access = PL1_RW,
2825       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
2826       .writefn = omap_ticonfig_write },
2827     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
2828       .access = PL1_RW,
2829       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
2830     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
2831       .access = PL1_RW, .resetvalue = 0xff0,
2832       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
2833     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
2834       .access = PL1_RW,
2835       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
2836       .writefn = omap_threadid_write },
2837     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
2838       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2839       .type = ARM_CP_NO_RAW,
2840       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
2841     /* TODO: Peripheral port remap register:
2842      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
2843      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
2844      * when MMU is off.
2845      */
2846     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
2847       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
2848       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
2849       .writefn = omap_cachemaint_write },
2850     { .name = "C9", .cp = 15, .crn = 9,
2851       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
2852       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
2853     REGINFO_SENTINEL
2854 };
2855
2856 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2857                               uint64_t value)
2858 {
2859     env->cp15.c15_cpar = value & 0x3fff;
2860 }
2861
2862 static const ARMCPRegInfo xscale_cp_reginfo[] = {
2863     { .name = "XSCALE_CPAR",
2864       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2865       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
2866       .writefn = xscale_cpar_write, },
2867     { .name = "XSCALE_AUXCR",
2868       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
2869       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
2870       .resetvalue = 0, },
2871     /* XScale specific cache-lockdown: since we have no cache we NOP these
2872      * and hope the guest does not really rely on cache behaviour.
2873      */
2874     { .name = "XSCALE_LOCK_ICACHE_LINE",
2875       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
2876       .access = PL1_W, .type = ARM_CP_NOP },
2877     { .name = "XSCALE_UNLOCK_ICACHE",
2878       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
2879       .access = PL1_W, .type = ARM_CP_NOP },
2880     { .name = "XSCALE_DCACHE_LOCK",
2881       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
2882       .access = PL1_RW, .type = ARM_CP_NOP },
2883     { .name = "XSCALE_UNLOCK_DCACHE",
2884       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
2885       .access = PL1_W, .type = ARM_CP_NOP },
2886     REGINFO_SENTINEL
2887 };
2888
2889 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
2890     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
2891      * implementation of this implementation-defined space.
2892      * Ideally this should eventually disappear in favour of actually
2893      * implementing the correct behaviour for all cores.
2894      */
2895     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
2896       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2897       .access = PL1_RW,
2898       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
2899       .resetvalue = 0 },
2900     REGINFO_SENTINEL
2901 };
2902
2903 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
2904     /* Cache status: RAZ because we have no cache so it's always clean */
2905     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
2906       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2907       .resetvalue = 0 },
2908     REGINFO_SENTINEL
2909 };
2910
2911 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
2912     /* We never have a a block transfer operation in progress */
2913     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
2914       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2915       .resetvalue = 0 },
2916     /* The cache ops themselves: these all NOP for QEMU */
2917     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
2918       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2919     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
2920       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2921     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
2922       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2923     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
2924       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2925     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
2926       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2927     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
2928       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2929     REGINFO_SENTINEL
2930 };
2931
2932 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
2933     /* The cache test-and-clean instructions always return (1 << 30)
2934      * to indicate that there are no dirty cache lines.
2935      */
2936     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
2937       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2938       .resetvalue = (1 << 30) },
2939     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
2940       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2941       .resetvalue = (1 << 30) },
2942     REGINFO_SENTINEL
2943 };
2944
2945 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
2946     /* Ignore ReadBuffer accesses */
2947     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
2948       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2949       .access = PL1_RW, .resetvalue = 0,
2950       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
2951     REGINFO_SENTINEL
2952 };
2953
2954 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2955 {
2956     ARMCPU *cpu = arm_env_get_cpu(env);
2957     unsigned int cur_el = arm_current_el(env);
2958     bool secure = arm_is_secure(env);
2959
2960     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2961         return env->cp15.vpidr_el2;
2962     }
2963     return raw_read(env, ri);
2964 }
2965
2966 static uint64_t mpidr_read_val(CPUARMState *env)
2967 {
2968     ARMCPU *cpu = ARM_CPU(arm_env_get_cpu(env));
2969     uint64_t mpidr = cpu->mp_affinity;
2970
2971     if (arm_feature(env, ARM_FEATURE_V7MP)) {
2972         mpidr |= (1U << 31);
2973         /* Cores which are uniprocessor (non-coherent)
2974          * but still implement the MP extensions set
2975          * bit 30. (For instance, Cortex-R5).
2976          */
2977         if (cpu->mp_is_up) {
2978             mpidr |= (1u << 30);
2979         }
2980     }
2981     return mpidr;
2982 }
2983
2984 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2985 {
2986     unsigned int cur_el = arm_current_el(env);
2987     bool secure = arm_is_secure(env);
2988
2989     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2990         return env->cp15.vmpidr_el2;
2991     }
2992     return mpidr_read_val(env);
2993 }
2994
2995 static const ARMCPRegInfo mpidr_cp_reginfo[] = {
2996     { .name = "MPIDR", .state = ARM_CP_STATE_BOTH,
2997       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
2998       .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
2999     REGINFO_SENTINEL
3000 };
3001
3002 static const ARMCPRegInfo lpae_cp_reginfo[] = {
3003     /* NOP AMAIR0/1 */
3004     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
3005       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
3006       .access = PL1_RW, .type = ARM_CP_CONST,
3007       .resetvalue = 0 },
3008     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
3009     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
3010       .access = PL1_RW, .type = ARM_CP_CONST,
3011       .resetvalue = 0 },
3012     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
3013       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
3014       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
3015                              offsetof(CPUARMState, cp15.par_ns)} },
3016     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
3017       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3018       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3019                              offsetof(CPUARMState, cp15.ttbr0_ns) },
3020       .writefn = vmsa_ttbr_write, },
3021     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
3022       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3023       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3024                              offsetof(CPUARMState, cp15.ttbr1_ns) },
3025       .writefn = vmsa_ttbr_write, },
3026     REGINFO_SENTINEL
3027 };
3028
3029 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3030 {
3031     return vfp_get_fpcr(env);
3032 }
3033
3034 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3035                             uint64_t value)
3036 {
3037     vfp_set_fpcr(env, value);
3038 }
3039
3040 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3041 {
3042     return vfp_get_fpsr(env);
3043 }
3044
3045 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3046                             uint64_t value)
3047 {
3048     vfp_set_fpsr(env, value);
3049 }
3050
3051 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
3052                                        bool isread)
3053 {
3054     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
3055         return CP_ACCESS_TRAP;
3056     }
3057     return CP_ACCESS_OK;
3058 }
3059
3060 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3061                             uint64_t value)
3062 {
3063     env->daif = value & PSTATE_DAIF;
3064 }
3065
3066 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3067                                           const ARMCPRegInfo *ri,
3068                                           bool isread)
3069 {
3070     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3071      * SCTLR_EL1.UCI is set.
3072      */
3073     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3074         return CP_ACCESS_TRAP;
3075     }
3076     return CP_ACCESS_OK;
3077 }
3078
3079 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3080  * Page D4-1736 (DDI0487A.b)
3081  */
3082
3083 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3084                                     uint64_t value)
3085 {
3086     CPUState *cs = ENV_GET_CPU(env);
3087
3088     if (arm_is_secure_below_el3(env)) {
3089         tlb_flush_by_mmuidx(cs,
3090                             ARMMMUIdxBit_S1SE1 |
3091                             ARMMMUIdxBit_S1SE0);
3092     } else {
3093         tlb_flush_by_mmuidx(cs,
3094                             ARMMMUIdxBit_S12NSE1 |
3095                             ARMMMUIdxBit_S12NSE0);
3096     }
3097 }
3098
3099 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3100                                       uint64_t value)
3101 {
3102     CPUState *cs = ENV_GET_CPU(env);
3103     bool sec = arm_is_secure_below_el3(env);
3104
3105     if (sec) {
3106         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3107                                             ARMMMUIdxBit_S1SE1 |
3108                                             ARMMMUIdxBit_S1SE0);
3109     } else {
3110         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3111                                             ARMMMUIdxBit_S12NSE1 |
3112                                             ARMMMUIdxBit_S12NSE0);
3113     }
3114 }
3115
3116 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3117                                   uint64_t value)
3118 {
3119     /* Note that the 'ALL' scope must invalidate both stage 1 and
3120      * stage 2 translations, whereas most other scopes only invalidate
3121      * stage 1 translations.
3122      */
3123     ARMCPU *cpu = arm_env_get_cpu(env);
3124     CPUState *cs = CPU(cpu);
3125
3126     if (arm_is_secure_below_el3(env)) {
3127         tlb_flush_by_mmuidx(cs,
3128                             ARMMMUIdxBit_S1SE1 |
3129                             ARMMMUIdxBit_S1SE0);
3130     } else {
3131         if (arm_feature(env, ARM_FEATURE_EL2)) {
3132             tlb_flush_by_mmuidx(cs,
3133                                 ARMMMUIdxBit_S12NSE1 |
3134                                 ARMMMUIdxBit_S12NSE0 |
3135                                 ARMMMUIdxBit_S2NS);
3136         } else {
3137             tlb_flush_by_mmuidx(cs,
3138                                 ARMMMUIdxBit_S12NSE1 |
3139                                 ARMMMUIdxBit_S12NSE0);
3140         }
3141     }
3142 }
3143
3144 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3145                                   uint64_t value)
3146 {
3147     ARMCPU *cpu = arm_env_get_cpu(env);
3148     CPUState *cs = CPU(cpu);
3149
3150     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3151 }
3152
3153 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3154                                   uint64_t value)
3155 {
3156     ARMCPU *cpu = arm_env_get_cpu(env);
3157     CPUState *cs = CPU(cpu);
3158
3159     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3160 }
3161
3162 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3163                                     uint64_t value)
3164 {
3165     /* Note that the 'ALL' scope must invalidate both stage 1 and
3166      * stage 2 translations, whereas most other scopes only invalidate
3167      * stage 1 translations.
3168      */
3169     CPUState *cs = ENV_GET_CPU(env);
3170     bool sec = arm_is_secure_below_el3(env);
3171     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3172
3173     if (sec) {
3174         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3175                                             ARMMMUIdxBit_S1SE1 |
3176                                             ARMMMUIdxBit_S1SE0);
3177     } else if (has_el2) {
3178         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3179                                             ARMMMUIdxBit_S12NSE1 |
3180                                             ARMMMUIdxBit_S12NSE0 |
3181                                             ARMMMUIdxBit_S2NS);
3182     } else {
3183           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3184                                               ARMMMUIdxBit_S12NSE1 |
3185                                               ARMMMUIdxBit_S12NSE0);
3186     }
3187 }
3188
3189 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3190                                     uint64_t value)
3191 {
3192     CPUState *cs = ENV_GET_CPU(env);
3193
3194     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3195 }
3196
3197 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3198                                     uint64_t value)
3199 {
3200     CPUState *cs = ENV_GET_CPU(env);
3201
3202     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3203 }
3204
3205 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3206                                  uint64_t value)
3207 {
3208     /* Invalidate by VA, EL1&0 (AArch64 version).
3209      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3210      * since we don't support flush-for-specific-ASID-only or
3211      * flush-last-level-only.
3212      */
3213     ARMCPU *cpu = arm_env_get_cpu(env);
3214     CPUState *cs = CPU(cpu);
3215     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3216
3217     if (arm_is_secure_below_el3(env)) {
3218         tlb_flush_page_by_mmuidx(cs, pageaddr,
3219                                  ARMMMUIdxBit_S1SE1 |
3220                                  ARMMMUIdxBit_S1SE0);
3221     } else {
3222         tlb_flush_page_by_mmuidx(cs, pageaddr,
3223                                  ARMMMUIdxBit_S12NSE1 |
3224                                  ARMMMUIdxBit_S12NSE0);
3225     }
3226 }
3227
3228 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3229                                  uint64_t value)
3230 {
3231     /* Invalidate by VA, EL2
3232      * Currently handles both VAE2 and VALE2, since we don't support
3233      * flush-last-level-only.
3234      */
3235     ARMCPU *cpu = arm_env_get_cpu(env);
3236     CPUState *cs = CPU(cpu);
3237     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3238
3239     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3240 }
3241
3242 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3243                                  uint64_t value)
3244 {
3245     /* Invalidate by VA, EL3
3246      * Currently handles both VAE3 and VALE3, since we don't support
3247      * flush-last-level-only.
3248      */
3249     ARMCPU *cpu = arm_env_get_cpu(env);
3250     CPUState *cs = CPU(cpu);
3251     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3252
3253     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
3254 }
3255
3256 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3257                                    uint64_t value)
3258 {
3259     ARMCPU *cpu = arm_env_get_cpu(env);
3260     CPUState *cs = CPU(cpu);
3261     bool sec = arm_is_secure_below_el3(env);
3262     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3263
3264     if (sec) {
3265         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3266                                                  ARMMMUIdxBit_S1SE1 |
3267                                                  ARMMMUIdxBit_S1SE0);
3268     } else {
3269         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3270                                                  ARMMMUIdxBit_S12NSE1 |
3271                                                  ARMMMUIdxBit_S12NSE0);
3272     }
3273 }
3274
3275 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3276                                    uint64_t value)
3277 {
3278     CPUState *cs = ENV_GET_CPU(env);
3279     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3280
3281     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3282                                              ARMMMUIdxBit_S1E2);
3283 }
3284
3285 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3286                                    uint64_t value)
3287 {
3288     CPUState *cs = ENV_GET_CPU(env);
3289     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3290
3291     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3292                                              ARMMMUIdxBit_S1E3);
3293 }
3294
3295 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3296                                     uint64_t value)
3297 {
3298     /* Invalidate by IPA. This has to invalidate any structures that
3299      * contain only stage 2 translation information, but does not need
3300      * to apply to structures that contain combined stage 1 and stage 2
3301      * translation information.
3302      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
3303      */
3304     ARMCPU *cpu = arm_env_get_cpu(env);
3305     CPUState *cs = CPU(cpu);
3306     uint64_t pageaddr;
3307
3308     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3309         return;
3310     }
3311
3312     pageaddr = sextract64(value << 12, 0, 48);
3313
3314     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
3315 }
3316
3317 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3318                                       uint64_t value)
3319 {
3320     CPUState *cs = ENV_GET_CPU(env);
3321     uint64_t pageaddr;
3322
3323     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3324         return;
3325     }
3326
3327     pageaddr = sextract64(value << 12, 0, 48);
3328
3329     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3330                                              ARMMMUIdxBit_S2NS);
3331 }
3332
3333 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
3334                                       bool isread)
3335 {
3336     /* We don't implement EL2, so the only control on DC ZVA is the
3337      * bit in the SCTLR which can prohibit access for EL0.
3338      */
3339     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
3340         return CP_ACCESS_TRAP;
3341     }
3342     return CP_ACCESS_OK;
3343 }
3344
3345 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
3346 {
3347     ARMCPU *cpu = arm_env_get_cpu(env);
3348     int dzp_bit = 1 << 4;
3349
3350     /* DZP indicates whether DC ZVA access is allowed */
3351     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
3352         dzp_bit = 0;
3353     }
3354     return cpu->dcz_blocksize | dzp_bit;
3355 }
3356
3357 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
3358                                     bool isread)
3359 {
3360     if (!(env->pstate & PSTATE_SP)) {
3361         /* Access to SP_EL0 is undefined if it's being used as
3362          * the stack pointer.
3363          */
3364         return CP_ACCESS_TRAP_UNCATEGORIZED;
3365     }
3366     return CP_ACCESS_OK;
3367 }
3368
3369 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
3370 {
3371     return env->pstate & PSTATE_SP;
3372 }
3373
3374 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
3375 {
3376     update_spsel(env, val);
3377 }
3378
3379 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3380                         uint64_t value)
3381 {
3382     ARMCPU *cpu = arm_env_get_cpu(env);
3383
3384     if (raw_read(env, ri) == value) {
3385         /* Skip the TLB flush if nothing actually changed; Linux likes
3386          * to do a lot of pointless SCTLR writes.
3387          */
3388         return;
3389     }
3390
3391     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
3392         /* M bit is RAZ/WI for PMSA with no MPU implemented */
3393         value &= ~SCTLR_M;
3394     }
3395
3396     raw_write(env, ri, value);
3397     /* ??? Lots of these bits are not implemented.  */
3398     /* This may enable/disable the MMU, so do a TLB flush.  */
3399     tlb_flush(CPU(cpu));
3400 }
3401
3402 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
3403                                      bool isread)
3404 {
3405     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
3406         return CP_ACCESS_TRAP_FP_EL2;
3407     }
3408     if (env->cp15.cptr_el[3] & CPTR_TFP) {
3409         return CP_ACCESS_TRAP_FP_EL3;
3410     }
3411     return CP_ACCESS_OK;
3412 }
3413
3414 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3415                        uint64_t value)
3416 {
3417     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
3418 }
3419
3420 static const ARMCPRegInfo v8_cp_reginfo[] = {
3421     /* Minimal set of EL0-visible registers. This will need to be expanded
3422      * significantly for system emulation of AArch64 CPUs.
3423      */
3424     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
3425       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
3426       .access = PL0_RW, .type = ARM_CP_NZCV },
3427     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
3428       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
3429       .type = ARM_CP_NO_RAW,
3430       .access = PL0_RW, .accessfn = aa64_daif_access,
3431       .fieldoffset = offsetof(CPUARMState, daif),
3432       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
3433     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
3434       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
3435       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3436       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
3437     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
3438       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
3439       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3440       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
3441     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
3442       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
3443       .access = PL0_R, .type = ARM_CP_NO_RAW,
3444       .readfn = aa64_dczid_read },
3445     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
3446       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
3447       .access = PL0_W, .type = ARM_CP_DC_ZVA,
3448 #ifndef CONFIG_USER_ONLY
3449       /* Avoid overhead of an access check that always passes in user-mode */
3450       .accessfn = aa64_zva_access,
3451 #endif
3452     },
3453     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
3454       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
3455       .access = PL1_R, .type = ARM_CP_CURRENTEL },
3456     /* Cache ops: all NOPs since we don't emulate caches */
3457     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
3458       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3459       .access = PL1_W, .type = ARM_CP_NOP },
3460     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
3461       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3462       .access = PL1_W, .type = ARM_CP_NOP },
3463     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
3464       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
3465       .access = PL0_W, .type = ARM_CP_NOP,
3466       .accessfn = aa64_cacheop_access },
3467     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
3468       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3469       .access = PL1_W, .type = ARM_CP_NOP },
3470     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
3471       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3472       .access = PL1_W, .type = ARM_CP_NOP },
3473     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
3474       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
3475       .access = PL0_W, .type = ARM_CP_NOP,
3476       .accessfn = aa64_cacheop_access },
3477     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
3478       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3479       .access = PL1_W, .type = ARM_CP_NOP },
3480     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
3481       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
3482       .access = PL0_W, .type = ARM_CP_NOP,
3483       .accessfn = aa64_cacheop_access },
3484     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
3485       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
3486       .access = PL0_W, .type = ARM_CP_NOP,
3487       .accessfn = aa64_cacheop_access },
3488     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
3489       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3490       .access = PL1_W, .type = ARM_CP_NOP },
3491     /* TLBI operations */
3492     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
3493       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
3494       .access = PL1_W, .type = ARM_CP_NO_RAW,
3495       .writefn = tlbi_aa64_vmalle1is_write },
3496     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
3497       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
3498       .access = PL1_W, .type = ARM_CP_NO_RAW,
3499       .writefn = tlbi_aa64_vae1is_write },
3500     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
3501       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
3502       .access = PL1_W, .type = ARM_CP_NO_RAW,
3503       .writefn = tlbi_aa64_vmalle1is_write },
3504     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
3505       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
3506       .access = PL1_W, .type = ARM_CP_NO_RAW,
3507       .writefn = tlbi_aa64_vae1is_write },
3508     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
3509       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3510       .access = PL1_W, .type = ARM_CP_NO_RAW,
3511       .writefn = tlbi_aa64_vae1is_write },
3512     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
3513       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3514       .access = PL1_W, .type = ARM_CP_NO_RAW,
3515       .writefn = tlbi_aa64_vae1is_write },
3516     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
3517       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
3518       .access = PL1_W, .type = ARM_CP_NO_RAW,
3519       .writefn = tlbi_aa64_vmalle1_write },
3520     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
3521       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
3522       .access = PL1_W, .type = ARM_CP_NO_RAW,
3523       .writefn = tlbi_aa64_vae1_write },
3524     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
3525       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
3526       .access = PL1_W, .type = ARM_CP_NO_RAW,
3527       .writefn = tlbi_aa64_vmalle1_write },
3528     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
3529       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
3530       .access = PL1_W, .type = ARM_CP_NO_RAW,
3531       .writefn = tlbi_aa64_vae1_write },
3532     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
3533       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3534       .access = PL1_W, .type = ARM_CP_NO_RAW,
3535       .writefn = tlbi_aa64_vae1_write },
3536     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
3537       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3538       .access = PL1_W, .type = ARM_CP_NO_RAW,
3539       .writefn = tlbi_aa64_vae1_write },
3540     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
3541       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3542       .access = PL2_W, .type = ARM_CP_NO_RAW,
3543       .writefn = tlbi_aa64_ipas2e1is_write },
3544     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
3545       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3546       .access = PL2_W, .type = ARM_CP_NO_RAW,
3547       .writefn = tlbi_aa64_ipas2e1is_write },
3548     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
3549       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3550       .access = PL2_W, .type = ARM_CP_NO_RAW,
3551       .writefn = tlbi_aa64_alle1is_write },
3552     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
3553       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
3554       .access = PL2_W, .type = ARM_CP_NO_RAW,
3555       .writefn = tlbi_aa64_alle1is_write },
3556     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
3557       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3558       .access = PL2_W, .type = ARM_CP_NO_RAW,
3559       .writefn = tlbi_aa64_ipas2e1_write },
3560     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
3561       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3562       .access = PL2_W, .type = ARM_CP_NO_RAW,
3563       .writefn = tlbi_aa64_ipas2e1_write },
3564     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
3565       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3566       .access = PL2_W, .type = ARM_CP_NO_RAW,
3567       .writefn = tlbi_aa64_alle1_write },
3568     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
3569       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
3570       .access = PL2_W, .type = ARM_CP_NO_RAW,
3571       .writefn = tlbi_aa64_alle1is_write },
3572 #ifndef CONFIG_USER_ONLY
3573     /* 64 bit address translation operations */
3574     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
3575       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
3576       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3577     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
3578       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
3579       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3580     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
3581       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
3582       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3583     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
3584       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
3585       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3586     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
3587       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
3588       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3589     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
3590       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
3591       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3592     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
3593       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
3594       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3595     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
3596       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
3597       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3598     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
3599     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
3600       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
3601       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3602     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
3603       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
3604       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3605     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
3606       .type = ARM_CP_ALIAS,
3607       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
3608       .access = PL1_RW, .resetvalue = 0,
3609       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
3610       .writefn = par_write },
3611 #endif
3612     /* TLB invalidate last level of translation table walk */
3613     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3614       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
3615     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3616       .type = ARM_CP_NO_RAW, .access = PL1_W,
3617       .writefn = tlbimvaa_is_write },
3618     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3619       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
3620     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3621       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
3622     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3623       .type = ARM_CP_NO_RAW, .access = PL2_W,
3624       .writefn = tlbimva_hyp_write },
3625     { .name = "TLBIMVALHIS",
3626       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3627       .type = ARM_CP_NO_RAW, .access = PL2_W,
3628       .writefn = tlbimva_hyp_is_write },
3629     { .name = "TLBIIPAS2",
3630       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3631       .type = ARM_CP_NO_RAW, .access = PL2_W,
3632       .writefn = tlbiipas2_write },
3633     { .name = "TLBIIPAS2IS",
3634       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3635       .type = ARM_CP_NO_RAW, .access = PL2_W,
3636       .writefn = tlbiipas2_is_write },
3637     { .name = "TLBIIPAS2L",
3638       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3639       .type = ARM_CP_NO_RAW, .access = PL2_W,
3640       .writefn = tlbiipas2_write },
3641     { .name = "TLBIIPAS2LIS",
3642       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3643       .type = ARM_CP_NO_RAW, .access = PL2_W,
3644       .writefn = tlbiipas2_is_write },
3645     /* 32 bit cache operations */
3646     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3647       .type = ARM_CP_NOP, .access = PL1_W },
3648     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
3649       .type = ARM_CP_NOP, .access = PL1_W },
3650     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3651       .type = ARM_CP_NOP, .access = PL1_W },
3652     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
3653       .type = ARM_CP_NOP, .access = PL1_W },
3654     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
3655       .type = ARM_CP_NOP, .access = PL1_W },
3656     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
3657       .type = ARM_CP_NOP, .access = PL1_W },
3658     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3659       .type = ARM_CP_NOP, .access = PL1_W },
3660     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3661       .type = ARM_CP_NOP, .access = PL1_W },
3662     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
3663       .type = ARM_CP_NOP, .access = PL1_W },
3664     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3665       .type = ARM_CP_NOP, .access = PL1_W },
3666     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
3667       .type = ARM_CP_NOP, .access = PL1_W },
3668     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
3669       .type = ARM_CP_NOP, .access = PL1_W },
3670     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3671       .type = ARM_CP_NOP, .access = PL1_W },
3672     /* MMU Domain access control / MPU write buffer control */
3673     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
3674       .access = PL1_RW, .resetvalue = 0,
3675       .writefn = dacr_write, .raw_writefn = raw_write,
3676       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
3677                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
3678     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
3679       .type = ARM_CP_ALIAS,
3680       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
3681       .access = PL1_RW,
3682       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
3683     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
3684       .type = ARM_CP_ALIAS,
3685       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
3686       .access = PL1_RW,
3687       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
3688     /* We rely on the access checks not allowing the guest to write to the
3689      * state field when SPSel indicates that it's being used as the stack
3690      * pointer.
3691      */
3692     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
3693       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
3694       .access = PL1_RW, .accessfn = sp_el0_access,
3695       .type = ARM_CP_ALIAS,
3696       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
3697     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
3698       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
3699       .access = PL2_RW, .type = ARM_CP_ALIAS,
3700       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
3701     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
3702       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
3703       .type = ARM_CP_NO_RAW,
3704       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
3705     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
3706       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
3707       .type = ARM_CP_ALIAS,
3708       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
3709       .access = PL2_RW, .accessfn = fpexc32_access },
3710     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
3711       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
3712       .access = PL2_RW, .resetvalue = 0,
3713       .writefn = dacr_write, .raw_writefn = raw_write,
3714       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
3715     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
3716       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
3717       .access = PL2_RW, .resetvalue = 0,
3718       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
3719     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
3720       .type = ARM_CP_ALIAS,
3721       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
3722       .access = PL2_RW,
3723       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
3724     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
3725       .type = ARM_CP_ALIAS,
3726       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
3727       .access = PL2_RW,
3728       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
3729     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
3730       .type = ARM_CP_ALIAS,
3731       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
3732       .access = PL2_RW,
3733       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
3734     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
3735       .type = ARM_CP_ALIAS,
3736       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
3737       .access = PL2_RW,
3738       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
3739     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
3740       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
3741       .resetvalue = 0,
3742       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
3743     { .name = "SDCR", .type = ARM_CP_ALIAS,
3744       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
3745       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
3746       .writefn = sdcr_write,
3747       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
3748     REGINFO_SENTINEL
3749 };
3750
3751 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
3752 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
3753     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
3754       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3755       .access = PL2_RW,
3756       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3757     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3758       .type = ARM_CP_NO_RAW,
3759       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3760       .access = PL2_RW,
3761       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3762     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3763       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3764       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3765     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3766       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3767       .access = PL2_RW, .type = ARM_CP_CONST,
3768       .resetvalue = 0 },
3769     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3770       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3771       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3772     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3773       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3774       .access = PL2_RW, .type = ARM_CP_CONST,
3775       .resetvalue = 0 },
3776     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
3777       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3778       .access = PL2_RW, .type = ARM_CP_CONST,
3779       .resetvalue = 0 },
3780     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3781       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3782       .access = PL2_RW, .type = ARM_CP_CONST,
3783       .resetvalue = 0 },
3784     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3785       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3786       .access = PL2_RW, .type = ARM_CP_CONST,
3787       .resetvalue = 0 },
3788     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3789       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3790       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3791     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
3792       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3793       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3794       .type = ARM_CP_CONST, .resetvalue = 0 },
3795     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3796       .cp = 15, .opc1 = 6, .crm = 2,
3797       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3798       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
3799     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3800       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3801       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3802     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3803       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3804       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3805     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3806       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3807       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3808     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3809       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3810       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3811     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3812       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3813       .resetvalue = 0 },
3814     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3815       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3816       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3817     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
3818       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
3819       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3820     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
3821       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3822       .resetvalue = 0 },
3823     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
3824       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
3825       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3826     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
3827       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3828       .resetvalue = 0 },
3829     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
3830       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
3831       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3832     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
3833       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
3834       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3835     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
3836       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
3837       .access = PL2_RW, .accessfn = access_tda,
3838       .type = ARM_CP_CONST, .resetvalue = 0 },
3839     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
3840       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
3841       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3842       .type = ARM_CP_CONST, .resetvalue = 0 },
3843     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
3844       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
3845       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3846     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
3847       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
3848       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3849     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
3850       .type = ARM_CP_CONST,
3851       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
3852       .access = PL2_RW, .resetvalue = 0 },
3853     REGINFO_SENTINEL
3854 };
3855
3856 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3857 {
3858     ARMCPU *cpu = arm_env_get_cpu(env);
3859     uint64_t valid_mask = HCR_MASK;
3860
3861     if (arm_feature(env, ARM_FEATURE_EL3)) {
3862         valid_mask &= ~HCR_HCD;
3863     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
3864         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
3865          * However, if we're using the SMC PSCI conduit then QEMU is
3866          * effectively acting like EL3 firmware and so the guest at
3867          * EL2 should retain the ability to prevent EL1 from being
3868          * able to make SMC calls into the ersatz firmware, so in
3869          * that case HCR.TSC should be read/write.
3870          */
3871         valid_mask &= ~HCR_TSC;
3872     }
3873
3874     /* Clear RES0 bits.  */
3875     value &= valid_mask;
3876
3877     /* These bits change the MMU setup:
3878      * HCR_VM enables stage 2 translation
3879      * HCR_PTW forbids certain page-table setups
3880      * HCR_DC Disables stage1 and enables stage2 translation
3881      */
3882     if ((raw_read(env, ri) ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
3883         tlb_flush(CPU(cpu));
3884     }
3885     raw_write(env, ri, value);
3886 }
3887
3888 static const ARMCPRegInfo el2_cp_reginfo[] = {
3889     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3890       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3891       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
3892       .writefn = hcr_write },
3893     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
3894       .type = ARM_CP_ALIAS,
3895       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
3896       .access = PL2_RW,
3897       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
3898     { .name = "ESR_EL2", .state = ARM_CP_STATE_AA64,
3899       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
3900       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
3901     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
3902       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
3903       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
3904     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
3905       .type = ARM_CP_ALIAS,
3906       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
3907       .access = PL2_RW,
3908       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
3909     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
3910       .type = ARM_CP_ALIAS,
3911       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
3912       .access = PL2_RW,
3913       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
3914     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
3915       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3916       .access = PL2_RW, .writefn = vbar_write,
3917       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
3918       .resetvalue = 0 },
3919     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
3920       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
3921       .access = PL3_RW, .type = ARM_CP_ALIAS,
3922       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
3923     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3924       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3925       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
3926       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]) },
3927     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3928       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3929       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
3930       .resetvalue = 0 },
3931     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3932       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3933       .access = PL2_RW, .type = ARM_CP_ALIAS,
3934       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
3935     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3936       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3937       .access = PL2_RW, .type = ARM_CP_CONST,
3938       .resetvalue = 0 },
3939     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
3940     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
3941       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3942       .access = PL2_RW, .type = ARM_CP_CONST,
3943       .resetvalue = 0 },
3944     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3945       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3946       .access = PL2_RW, .type = ARM_CP_CONST,
3947       .resetvalue = 0 },
3948     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3949       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3950       .access = PL2_RW, .type = ARM_CP_CONST,
3951       .resetvalue = 0 },
3952     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3953       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3954       .access = PL2_RW,
3955       /* no .writefn needed as this can't cause an ASID change;
3956        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3957        */
3958       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
3959     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
3960       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3961       .type = ARM_CP_ALIAS,
3962       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3963       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3964     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
3965       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3966       .access = PL2_RW,
3967       /* no .writefn needed as this can't cause an ASID change;
3968        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3969        */
3970       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3971     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3972       .cp = 15, .opc1 = 6, .crm = 2,
3973       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3974       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3975       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
3976       .writefn = vttbr_write },
3977     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3978       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3979       .access = PL2_RW, .writefn = vttbr_write,
3980       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
3981     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3982       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3983       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
3984       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
3985     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3986       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3987       .access = PL2_RW, .resetvalue = 0,
3988       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
3989     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3990       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3991       .access = PL2_RW, .resetvalue = 0,
3992       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3993     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3994       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3995       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3996     { .name = "TLBIALLNSNH",
3997       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3998       .type = ARM_CP_NO_RAW, .access = PL2_W,
3999       .writefn = tlbiall_nsnh_write },
4000     { .name = "TLBIALLNSNHIS",
4001       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4002       .type = ARM_CP_NO_RAW, .access = PL2_W,
4003       .writefn = tlbiall_nsnh_is_write },
4004     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4005       .type = ARM_CP_NO_RAW, .access = PL2_W,
4006       .writefn = tlbiall_hyp_write },
4007     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4008       .type = ARM_CP_NO_RAW, .access = PL2_W,
4009       .writefn = tlbiall_hyp_is_write },
4010     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4011       .type = ARM_CP_NO_RAW, .access = PL2_W,
4012       .writefn = tlbimva_hyp_write },
4013     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4014       .type = ARM_CP_NO_RAW, .access = PL2_W,
4015       .writefn = tlbimva_hyp_is_write },
4016     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
4017       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4018       .type = ARM_CP_NO_RAW, .access = PL2_W,
4019       .writefn = tlbi_aa64_alle2_write },
4020     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
4021       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4022       .type = ARM_CP_NO_RAW, .access = PL2_W,
4023       .writefn = tlbi_aa64_vae2_write },
4024     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
4025       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4026       .access = PL2_W, .type = ARM_CP_NO_RAW,
4027       .writefn = tlbi_aa64_vae2_write },
4028     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
4029       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4030       .access = PL2_W, .type = ARM_CP_NO_RAW,
4031       .writefn = tlbi_aa64_alle2is_write },
4032     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
4033       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4034       .type = ARM_CP_NO_RAW, .access = PL2_W,
4035       .writefn = tlbi_aa64_vae2is_write },
4036     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
4037       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4038       .access = PL2_W, .type = ARM_CP_NO_RAW,
4039       .writefn = tlbi_aa64_vae2is_write },
4040 #ifndef CONFIG_USER_ONLY
4041     /* Unlike the other EL2-related AT operations, these must
4042      * UNDEF from EL3 if EL2 is not implemented, which is why we
4043      * define them here rather than with the rest of the AT ops.
4044      */
4045     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
4046       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4047       .access = PL2_W, .accessfn = at_s1e2_access,
4048       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4049     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
4050       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4051       .access = PL2_W, .accessfn = at_s1e2_access,
4052       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4053     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
4054      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
4055      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
4056      * to behave as if SCR.NS was 1.
4057      */
4058     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4059       .access = PL2_W,
4060       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4061     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4062       .access = PL2_W,
4063       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4064     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4065       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4066       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
4067        * reset values as IMPDEF. We choose to reset to 3 to comply with
4068        * both ARMv7 and ARMv8.
4069        */
4070       .access = PL2_RW, .resetvalue = 3,
4071       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
4072     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4073       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4074       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
4075       .writefn = gt_cntvoff_write,
4076       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4077     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4078       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
4079       .writefn = gt_cntvoff_write,
4080       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4081     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4082       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4083       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4084       .type = ARM_CP_IO, .access = PL2_RW,
4085       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4086     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4087       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4088       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
4089       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4090     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4091       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4092       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
4093       .resetfn = gt_hyp_timer_reset,
4094       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
4095     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4096       .type = ARM_CP_IO,
4097       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4098       .access = PL2_RW,
4099       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
4100       .resetvalue = 0,
4101       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
4102 #endif
4103     /* The only field of MDCR_EL2 that has a defined architectural reset value
4104      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
4105      * don't impelment any PMU event counters, so using zero as a reset
4106      * value for MDCR_EL2 is okay
4107      */
4108     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4109       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4110       .access = PL2_RW, .resetvalue = 0,
4111       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
4112     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
4113       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4114       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4115       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4116     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
4117       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4118       .access = PL2_RW,
4119       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4120     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4121       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4122       .access = PL2_RW,
4123       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
4124     REGINFO_SENTINEL
4125 };
4126
4127 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
4128                                    bool isread)
4129 {
4130     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
4131      * At Secure EL1 it traps to EL3.
4132      */
4133     if (arm_current_el(env) == 3) {
4134         return CP_ACCESS_OK;
4135     }
4136     if (arm_is_secure_below_el3(env)) {
4137         return CP_ACCESS_TRAP_EL3;
4138     }
4139     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
4140     if (isread) {
4141         return CP_ACCESS_OK;
4142     }
4143     return CP_ACCESS_TRAP_UNCATEGORIZED;
4144 }
4145
4146 static const ARMCPRegInfo el3_cp_reginfo[] = {
4147     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
4148       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
4149       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
4150       .resetvalue = 0, .writefn = scr_write },
4151     { .name = "SCR",  .type = ARM_CP_ALIAS,
4152       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
4153       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4154       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
4155       .writefn = scr_write },
4156     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
4157       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
4158       .access = PL3_RW, .resetvalue = 0,
4159       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
4160     { .name = "SDER",
4161       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
4162       .access = PL3_RW, .resetvalue = 0,
4163       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
4164     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
4165       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4166       .writefn = vbar_write, .resetvalue = 0,
4167       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
4168     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
4169       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
4170       .access = PL3_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
4171       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
4172     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
4173       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
4174       .access = PL3_RW,
4175       /* no .writefn needed as this can't cause an ASID change;
4176        * we must provide a .raw_writefn and .resetfn because we handle
4177        * reset and migration for the AArch32 TTBCR(S), which might be
4178        * using mask and base_mask.
4179        */
4180       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
4181       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
4182     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
4183       .type = ARM_CP_ALIAS,
4184       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
4185       .access = PL3_RW,
4186       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
4187     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
4188       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
4189       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
4190     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
4191       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
4192       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
4193     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
4194       .type = ARM_CP_ALIAS,
4195       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
4196       .access = PL3_RW,
4197       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
4198     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
4199       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
4200       .access = PL3_RW, .writefn = vbar_write,
4201       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
4202       .resetvalue = 0 },
4203     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
4204       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
4205       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
4206       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
4207     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
4208       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
4209       .access = PL3_RW, .resetvalue = 0,
4210       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
4211     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
4212       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
4213       .access = PL3_RW, .type = ARM_CP_CONST,
4214       .resetvalue = 0 },
4215     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
4216       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
4217       .access = PL3_RW, .type = ARM_CP_CONST,
4218       .resetvalue = 0 },
4219     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
4220       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
4221       .access = PL3_RW, .type = ARM_CP_CONST,
4222       .resetvalue = 0 },
4223     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
4224       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
4225       .access = PL3_W, .type = ARM_CP_NO_RAW,
4226       .writefn = tlbi_aa64_alle3is_write },
4227     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
4228       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
4229       .access = PL3_W, .type = ARM_CP_NO_RAW,
4230       .writefn = tlbi_aa64_vae3is_write },
4231     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
4232       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
4233       .access = PL3_W, .type = ARM_CP_NO_RAW,
4234       .writefn = tlbi_aa64_vae3is_write },
4235     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
4236       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
4237       .access = PL3_W, .type = ARM_CP_NO_RAW,
4238       .writefn = tlbi_aa64_alle3_write },
4239     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
4240       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
4241       .access = PL3_W, .type = ARM_CP_NO_RAW,
4242       .writefn = tlbi_aa64_vae3_write },
4243     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
4244       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
4245       .access = PL3_W, .type = ARM_CP_NO_RAW,
4246       .writefn = tlbi_aa64_vae3_write },
4247     REGINFO_SENTINEL
4248 };
4249
4250 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4251                                      bool isread)
4252 {
4253     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
4254      * but the AArch32 CTR has its own reginfo struct)
4255      */
4256     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
4257         return CP_ACCESS_TRAP;
4258     }
4259     return CP_ACCESS_OK;
4260 }
4261
4262 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4263                         uint64_t value)
4264 {
4265     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
4266      * read via a bit in OSLSR_EL1.
4267      */
4268     int oslock;
4269
4270     if (ri->state == ARM_CP_STATE_AA32) {
4271         oslock = (value == 0xC5ACCE55);
4272     } else {
4273         oslock = value & 1;
4274     }
4275
4276     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
4277 }
4278
4279 static const ARMCPRegInfo debug_cp_reginfo[] = {
4280     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
4281      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
4282      * unlike DBGDRAR it is never accessible from EL0.
4283      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
4284      * accessor.
4285      */
4286     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
4287       .access = PL0_R, .accessfn = access_tdra,
4288       .type = ARM_CP_CONST, .resetvalue = 0 },
4289     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
4290       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
4291       .access = PL1_R, .accessfn = access_tdra,
4292       .type = ARM_CP_CONST, .resetvalue = 0 },
4293     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
4294       .access = PL0_R, .accessfn = access_tdra,
4295       .type = ARM_CP_CONST, .resetvalue = 0 },
4296     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
4297     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
4298       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4299       .access = PL1_RW, .accessfn = access_tda,
4300       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
4301       .resetvalue = 0 },
4302     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
4303      * We don't implement the configurable EL0 access.
4304      */
4305     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
4306       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4307       .type = ARM_CP_ALIAS,
4308       .access = PL1_R, .accessfn = access_tda,
4309       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
4310     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
4311       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
4312       .access = PL1_W, .type = ARM_CP_NO_RAW,
4313       .accessfn = access_tdosa,
4314       .writefn = oslar_write },
4315     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
4316       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
4317       .access = PL1_R, .resetvalue = 10,
4318       .accessfn = access_tdosa,
4319       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
4320     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
4321     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
4322       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
4323       .access = PL1_RW, .accessfn = access_tdosa,
4324       .type = ARM_CP_NOP },
4325     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
4326      * implement vector catch debug events yet.
4327      */
4328     { .name = "DBGVCR",
4329       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4330       .access = PL1_RW, .accessfn = access_tda,
4331       .type = ARM_CP_NOP },
4332     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
4333      * to save and restore a 32-bit guest's DBGVCR)
4334      */
4335     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
4336       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
4337       .access = PL2_RW, .accessfn = access_tda,
4338       .type = ARM_CP_NOP },
4339     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
4340      * Channel but Linux may try to access this register. The 32-bit
4341      * alias is DBGDCCINT.
4342      */
4343     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
4344       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4345       .access = PL1_RW, .accessfn = access_tda,
4346       .type = ARM_CP_NOP },
4347     REGINFO_SENTINEL
4348 };
4349
4350 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
4351     /* 64 bit access versions of the (dummy) debug registers */
4352     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
4353       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4354     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
4355       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4356     REGINFO_SENTINEL
4357 };
4358
4359 /* Return the exception level to which SVE-disabled exceptions should
4360  * be taken, or 0 if SVE is enabled.
4361  */
4362 static int sve_exception_el(CPUARMState *env)
4363 {
4364 #ifndef CONFIG_USER_ONLY
4365     unsigned current_el = arm_current_el(env);
4366
4367     /* The CPACR.ZEN controls traps to EL1:
4368      * 0, 2 : trap EL0 and EL1 accesses
4369      * 1    : trap only EL0 accesses
4370      * 3    : trap no accesses
4371      */
4372     switch (extract32(env->cp15.cpacr_el1, 16, 2)) {
4373     default:
4374         if (current_el <= 1) {
4375             /* Trap to PL1, which might be EL1 or EL3 */
4376             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
4377                 return 3;
4378             }
4379             return 1;
4380         }
4381         break;
4382     case 1:
4383         if (current_el == 0) {
4384             return 1;
4385         }
4386         break;
4387     case 3:
4388         break;
4389     }
4390
4391     /* Similarly for CPACR.FPEN, after having checked ZEN.  */
4392     switch (extract32(env->cp15.cpacr_el1, 20, 2)) {
4393     default:
4394         if (current_el <= 1) {
4395             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
4396                 return 3;
4397             }
4398             return 1;
4399         }
4400         break;
4401     case 1:
4402         if (current_el == 0) {
4403             return 1;
4404         }
4405         break;
4406     case 3:
4407         break;
4408     }
4409
4410     /* CPTR_EL2.  Check both TZ and TFP.  */
4411     if (current_el <= 2
4412         && (env->cp15.cptr_el[2] & (CPTR_TFP | CPTR_TZ))
4413         && !arm_is_secure_below_el3(env)) {
4414         return 2;
4415     }
4416
4417     /* CPTR_EL3.  Check both EZ and TFP.  */
4418     if (!(env->cp15.cptr_el[3] & CPTR_EZ)
4419         || (env->cp15.cptr_el[3] & CPTR_TFP)) {
4420         return 3;
4421     }
4422 #endif
4423     return 0;
4424 }
4425
4426 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4427                       uint64_t value)
4428 {
4429     /* Bits other than [3:0] are RAZ/WI.  */
4430     raw_write(env, ri, value & 0xf);
4431 }
4432
4433 static const ARMCPRegInfo zcr_el1_reginfo = {
4434     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
4435     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
4436     .access = PL1_RW, .type = ARM_CP_SVE,
4437     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
4438     .writefn = zcr_write, .raw_writefn = raw_write
4439 };
4440
4441 static const ARMCPRegInfo zcr_el2_reginfo = {
4442     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4443     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4444     .access = PL2_RW, .type = ARM_CP_SVE,
4445     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
4446     .writefn = zcr_write, .raw_writefn = raw_write
4447 };
4448
4449 static const ARMCPRegInfo zcr_no_el2_reginfo = {
4450     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4451     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4452     .access = PL2_RW, .type = ARM_CP_SVE,
4453     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
4454 };
4455
4456 static const ARMCPRegInfo zcr_el3_reginfo = {
4457     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
4458     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
4459     .access = PL3_RW, .type = ARM_CP_SVE,
4460     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
4461     .writefn = zcr_write, .raw_writefn = raw_write
4462 };
4463
4464 void hw_watchpoint_update(ARMCPU *cpu, int n)
4465 {
4466     CPUARMState *env = &cpu->env;
4467     vaddr len = 0;
4468     vaddr wvr = env->cp15.dbgwvr[n];
4469     uint64_t wcr = env->cp15.dbgwcr[n];
4470     int mask;
4471     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
4472
4473     if (env->cpu_watchpoint[n]) {
4474         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
4475         env->cpu_watchpoint[n] = NULL;
4476     }
4477
4478     if (!extract64(wcr, 0, 1)) {
4479         /* E bit clear : watchpoint disabled */
4480         return;
4481     }
4482
4483     switch (extract64(wcr, 3, 2)) {
4484     case 0:
4485         /* LSC 00 is reserved and must behave as if the wp is disabled */
4486         return;
4487     case 1:
4488         flags |= BP_MEM_READ;
4489         break;
4490     case 2:
4491         flags |= BP_MEM_WRITE;
4492         break;
4493     case 3:
4494         flags |= BP_MEM_ACCESS;
4495         break;
4496     }
4497
4498     /* Attempts to use both MASK and BAS fields simultaneously are
4499      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
4500      * thus generating a watchpoint for every byte in the masked region.
4501      */
4502     mask = extract64(wcr, 24, 4);
4503     if (mask == 1 || mask == 2) {
4504         /* Reserved values of MASK; we must act as if the mask value was
4505          * some non-reserved value, or as if the watchpoint were disabled.
4506          * We choose the latter.
4507          */
4508         return;
4509     } else if (mask) {
4510         /* Watchpoint covers an aligned area up to 2GB in size */
4511         len = 1ULL << mask;
4512         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
4513          * whether the watchpoint fires when the unmasked bits match; we opt
4514          * to generate the exceptions.
4515          */
4516         wvr &= ~(len - 1);
4517     } else {
4518         /* Watchpoint covers bytes defined by the byte address select bits */
4519         int bas = extract64(wcr, 5, 8);
4520         int basstart;
4521
4522         if (bas == 0) {
4523             /* This must act as if the watchpoint is disabled */
4524             return;
4525         }
4526
4527         if (extract64(wvr, 2, 1)) {
4528             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
4529              * ignored, and BAS[3:0] define which bytes to watch.
4530              */
4531             bas &= 0xf;
4532         }
4533         /* The BAS bits are supposed to be programmed to indicate a contiguous
4534          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
4535          * we fire for each byte in the word/doubleword addressed by the WVR.
4536          * We choose to ignore any non-zero bits after the first range of 1s.
4537          */
4538         basstart = ctz32(bas);
4539         len = cto32(bas >> basstart);
4540         wvr += basstart;
4541     }
4542
4543     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
4544                           &env->cpu_watchpoint[n]);
4545 }
4546
4547 void hw_watchpoint_update_all(ARMCPU *cpu)
4548 {
4549     int i;
4550     CPUARMState *env = &cpu->env;
4551
4552     /* Completely clear out existing QEMU watchpoints and our array, to
4553      * avoid possible stale entries following migration load.
4554      */
4555     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
4556     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
4557
4558     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
4559         hw_watchpoint_update(cpu, i);
4560     }
4561 }
4562
4563 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4564                          uint64_t value)
4565 {
4566     ARMCPU *cpu = arm_env_get_cpu(env);
4567     int i = ri->crm;
4568
4569     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
4570      * register reads and behaves as if values written are sign extended.
4571      * Bits [1:0] are RES0.
4572      */
4573     value = sextract64(value, 0, 49) & ~3ULL;
4574
4575     raw_write(env, ri, value);
4576     hw_watchpoint_update(cpu, i);
4577 }
4578
4579 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4580                          uint64_t value)
4581 {
4582     ARMCPU *cpu = arm_env_get_cpu(env);
4583     int i = ri->crm;
4584
4585     raw_write(env, ri, value);
4586     hw_watchpoint_update(cpu, i);
4587 }
4588
4589 void hw_breakpoint_update(ARMCPU *cpu, int n)
4590 {
4591     CPUARMState *env = &cpu->env;
4592     uint64_t bvr = env->cp15.dbgbvr[n];
4593     uint64_t bcr = env->cp15.dbgbcr[n];
4594     vaddr addr;
4595     int bt;
4596     int flags = BP_CPU;
4597
4598     if (env->cpu_breakpoint[n]) {
4599         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
4600         env->cpu_breakpoint[n] = NULL;
4601     }
4602
4603     if (!extract64(bcr, 0, 1)) {
4604         /* E bit clear : watchpoint disabled */
4605         return;
4606     }
4607
4608     bt = extract64(bcr, 20, 4);
4609
4610     switch (bt) {
4611     case 4: /* unlinked address mismatch (reserved if AArch64) */
4612     case 5: /* linked address mismatch (reserved if AArch64) */
4613         qemu_log_mask(LOG_UNIMP,
4614                       "arm: address mismatch breakpoint types not implemented\n");
4615         return;
4616     case 0: /* unlinked address match */
4617     case 1: /* linked address match */
4618     {
4619         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
4620          * we behave as if the register was sign extended. Bits [1:0] are
4621          * RES0. The BAS field is used to allow setting breakpoints on 16
4622          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
4623          * a bp will fire if the addresses covered by the bp and the addresses
4624          * covered by the insn overlap but the insn doesn't start at the
4625          * start of the bp address range. We choose to require the insn and
4626          * the bp to have the same address. The constraints on writing to
4627          * BAS enforced in dbgbcr_write mean we have only four cases:
4628          *  0b0000  => no breakpoint
4629          *  0b0011  => breakpoint on addr
4630          *  0b1100  => breakpoint on addr + 2
4631          *  0b1111  => breakpoint on addr
4632          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
4633          */
4634         int bas = extract64(bcr, 5, 4);
4635         addr = sextract64(bvr, 0, 49) & ~3ULL;
4636         if (bas == 0) {
4637             return;
4638         }
4639         if (bas == 0xc) {
4640             addr += 2;
4641         }
4642         break;
4643     }
4644     case 2: /* unlinked context ID match */
4645     case 8: /* unlinked VMID match (reserved if no EL2) */
4646     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
4647         qemu_log_mask(LOG_UNIMP,
4648                       "arm: unlinked context breakpoint types not implemented\n");
4649         return;
4650     case 9: /* linked VMID match (reserved if no EL2) */
4651     case 11: /* linked context ID and VMID match (reserved if no EL2) */
4652     case 3: /* linked context ID match */
4653     default:
4654         /* We must generate no events for Linked context matches (unless
4655          * they are linked to by some other bp/wp, which is handled in
4656          * updates for the linking bp/wp). We choose to also generate no events
4657          * for reserved values.
4658          */
4659         return;
4660     }
4661
4662     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
4663 }
4664
4665 void hw_breakpoint_update_all(ARMCPU *cpu)
4666 {
4667     int i;
4668     CPUARMState *env = &cpu->env;
4669
4670     /* Completely clear out existing QEMU breakpoints and our array, to
4671      * avoid possible stale entries following migration load.
4672      */
4673     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
4674     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
4675
4676     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
4677         hw_breakpoint_update(cpu, i);
4678     }
4679 }
4680
4681 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4682                          uint64_t value)
4683 {
4684     ARMCPU *cpu = arm_env_get_cpu(env);
4685     int i = ri->crm;
4686
4687     raw_write(env, ri, value);
4688     hw_breakpoint_update(cpu, i);
4689 }
4690
4691 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4692                          uint64_t value)
4693 {
4694     ARMCPU *cpu = arm_env_get_cpu(env);
4695     int i = ri->crm;
4696
4697     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
4698      * copy of BAS[0].
4699      */
4700     value = deposit64(value, 6, 1, extract64(value, 5, 1));
4701     value = deposit64(value, 8, 1, extract64(value, 7, 1));
4702
4703     raw_write(env, ri, value);
4704     hw_breakpoint_update(cpu, i);
4705 }
4706
4707 static void define_debug_regs(ARMCPU *cpu)
4708 {
4709     /* Define v7 and v8 architectural debug registers.
4710      * These are just dummy implementations for now.
4711      */
4712     int i;
4713     int wrps, brps, ctx_cmps;
4714     ARMCPRegInfo dbgdidr = {
4715         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
4716         .access = PL0_R, .accessfn = access_tda,
4717         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
4718     };
4719
4720     /* Note that all these register fields hold "number of Xs minus 1". */
4721     brps = extract32(cpu->dbgdidr, 24, 4);
4722     wrps = extract32(cpu->dbgdidr, 28, 4);
4723     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
4724
4725     assert(ctx_cmps <= brps);
4726
4727     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
4728      * of the debug registers such as number of breakpoints;
4729      * check that if they both exist then they agree.
4730      */
4731     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
4732         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
4733         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
4734         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
4735     }
4736
4737     define_one_arm_cp_reg(cpu, &dbgdidr);
4738     define_arm_cp_regs(cpu, debug_cp_reginfo);
4739
4740     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
4741         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
4742     }
4743
4744     for (i = 0; i < brps + 1; i++) {
4745         ARMCPRegInfo dbgregs[] = {
4746             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
4747               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
4748               .access = PL1_RW, .accessfn = access_tda,
4749               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
4750               .writefn = dbgbvr_write, .raw_writefn = raw_write
4751             },
4752             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
4753               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
4754               .access = PL1_RW, .accessfn = access_tda,
4755               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
4756               .writefn = dbgbcr_write, .raw_writefn = raw_write
4757             },
4758             REGINFO_SENTINEL
4759         };
4760         define_arm_cp_regs(cpu, dbgregs);
4761     }
4762
4763     for (i = 0; i < wrps + 1; i++) {
4764         ARMCPRegInfo dbgregs[] = {
4765             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
4766               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
4767               .access = PL1_RW, .accessfn = access_tda,
4768               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
4769               .writefn = dbgwvr_write, .raw_writefn = raw_write
4770             },
4771             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
4772               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
4773               .access = PL1_RW, .accessfn = access_tda,
4774               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
4775               .writefn = dbgwcr_write, .raw_writefn = raw_write
4776             },
4777             REGINFO_SENTINEL
4778         };
4779         define_arm_cp_regs(cpu, dbgregs);
4780     }
4781 }
4782
4783 /* We don't know until after realize whether there's a GICv3
4784  * attached, and that is what registers the gicv3 sysregs.
4785  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
4786  * at runtime.
4787  */
4788 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
4789 {
4790     ARMCPU *cpu = arm_env_get_cpu(env);
4791     uint64_t pfr1 = cpu->id_pfr1;
4792
4793     if (env->gicv3state) {
4794         pfr1 |= 1 << 28;
4795     }
4796     return pfr1;
4797 }
4798
4799 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
4800 {
4801     ARMCPU *cpu = arm_env_get_cpu(env);
4802     uint64_t pfr0 = cpu->id_aa64pfr0;
4803
4804     if (env->gicv3state) {
4805         pfr0 |= 1 << 24;
4806     }
4807     return pfr0;
4808 }
4809
4810 void register_cp_regs_for_features(ARMCPU *cpu)
4811 {
4812     /* Register all the coprocessor registers based on feature bits */
4813     CPUARMState *env = &cpu->env;
4814     if (arm_feature(env, ARM_FEATURE_M)) {
4815         /* M profile has no coprocessor registers */
4816         return;
4817     }
4818
4819     define_arm_cp_regs(cpu, cp_reginfo);
4820     if (!arm_feature(env, ARM_FEATURE_V8)) {
4821         /* Must go early as it is full of wildcards that may be
4822          * overridden by later definitions.
4823          */
4824         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
4825     }
4826
4827     if (arm_feature(env, ARM_FEATURE_V6)) {
4828         /* The ID registers all have impdef reset values */
4829         ARMCPRegInfo v6_idregs[] = {
4830             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
4831               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4832               .access = PL1_R, .type = ARM_CP_CONST,
4833               .resetvalue = cpu->id_pfr0 },
4834             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
4835              * the value of the GIC field until after we define these regs.
4836              */
4837             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
4838               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
4839               .access = PL1_R, .type = ARM_CP_NO_RAW,
4840               .readfn = id_pfr1_read,
4841               .writefn = arm_cp_write_ignore },
4842             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
4843               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
4844               .access = PL1_R, .type = ARM_CP_CONST,
4845               .resetvalue = cpu->id_dfr0 },
4846             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
4847               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
4848               .access = PL1_R, .type = ARM_CP_CONST,
4849               .resetvalue = cpu->id_afr0 },
4850             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
4851               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
4852               .access = PL1_R, .type = ARM_CP_CONST,
4853               .resetvalue = cpu->id_mmfr0 },
4854             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
4855               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
4856               .access = PL1_R, .type = ARM_CP_CONST,
4857               .resetvalue = cpu->id_mmfr1 },
4858             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
4859               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
4860               .access = PL1_R, .type = ARM_CP_CONST,
4861               .resetvalue = cpu->id_mmfr2 },
4862             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
4863               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
4864               .access = PL1_R, .type = ARM_CP_CONST,
4865               .resetvalue = cpu->id_mmfr3 },
4866             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
4867               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4868               .access = PL1_R, .type = ARM_CP_CONST,
4869               .resetvalue = cpu->id_isar0 },
4870             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
4871               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
4872               .access = PL1_R, .type = ARM_CP_CONST,
4873               .resetvalue = cpu->id_isar1 },
4874             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
4875               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4876               .access = PL1_R, .type = ARM_CP_CONST,
4877               .resetvalue = cpu->id_isar2 },
4878             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
4879               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
4880               .access = PL1_R, .type = ARM_CP_CONST,
4881               .resetvalue = cpu->id_isar3 },
4882             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
4883               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
4884               .access = PL1_R, .type = ARM_CP_CONST,
4885               .resetvalue = cpu->id_isar4 },
4886             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
4887               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
4888               .access = PL1_R, .type = ARM_CP_CONST,
4889               .resetvalue = cpu->id_isar5 },
4890             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
4891               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
4892               .access = PL1_R, .type = ARM_CP_CONST,
4893               .resetvalue = cpu->id_mmfr4 },
4894             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
4895               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
4896               .access = PL1_R, .type = ARM_CP_CONST,
4897               .resetvalue = cpu->id_isar6 },
4898             REGINFO_SENTINEL
4899         };
4900         define_arm_cp_regs(cpu, v6_idregs);
4901         define_arm_cp_regs(cpu, v6_cp_reginfo);
4902     } else {
4903         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
4904     }
4905     if (arm_feature(env, ARM_FEATURE_V6K)) {
4906         define_arm_cp_regs(cpu, v6k_cp_reginfo);
4907     }
4908     if (arm_feature(env, ARM_FEATURE_V7MP) &&
4909         !arm_feature(env, ARM_FEATURE_PMSA)) {
4910         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
4911     }
4912     if (arm_feature(env, ARM_FEATURE_V7)) {
4913         /* v7 performance monitor control register: same implementor
4914          * field as main ID register, and we implement only the cycle
4915          * count register.
4916          */
4917 #ifndef CONFIG_USER_ONLY
4918         ARMCPRegInfo pmcr = {
4919             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
4920             .access = PL0_RW,
4921             .type = ARM_CP_IO | ARM_CP_ALIAS,
4922             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
4923             .accessfn = pmreg_access, .writefn = pmcr_write,
4924             .raw_writefn = raw_write,
4925         };
4926         ARMCPRegInfo pmcr64 = {
4927             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
4928             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
4929             .access = PL0_RW, .accessfn = pmreg_access,
4930             .type = ARM_CP_IO,
4931             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
4932             .resetvalue = cpu->midr & 0xff000000,
4933             .writefn = pmcr_write, .raw_writefn = raw_write,
4934         };
4935         define_one_arm_cp_reg(cpu, &pmcr);
4936         define_one_arm_cp_reg(cpu, &pmcr64);
4937 #endif
4938         ARMCPRegInfo clidr = {
4939             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
4940             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
4941             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
4942         };
4943         define_one_arm_cp_reg(cpu, &clidr);
4944         define_arm_cp_regs(cpu, v7_cp_reginfo);
4945         define_debug_regs(cpu);
4946     } else {
4947         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
4948     }
4949     if (arm_feature(env, ARM_FEATURE_V8)) {
4950         /* AArch64 ID registers, which all have impdef reset values.
4951          * Note that within the ID register ranges the unused slots
4952          * must all RAZ, not UNDEF; future architecture versions may
4953          * define new registers here.
4954          */
4955         ARMCPRegInfo v8_idregs[] = {
4956             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
4957              * know the right value for the GIC field until after we
4958              * define these regs.
4959              */
4960             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
4961               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
4962               .access = PL1_R, .type = ARM_CP_NO_RAW,
4963               .readfn = id_aa64pfr0_read,
4964               .writefn = arm_cp_write_ignore },
4965             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
4966               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
4967               .access = PL1_R, .type = ARM_CP_CONST,
4968               .resetvalue = cpu->id_aa64pfr1},
4969             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4970               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
4971               .access = PL1_R, .type = ARM_CP_CONST,
4972               .resetvalue = 0 },
4973             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4974               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
4975               .access = PL1_R, .type = ARM_CP_CONST,
4976               .resetvalue = 0 },
4977             { .name = "ID_AA64PFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4978               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
4979               .access = PL1_R, .type = ARM_CP_CONST,
4980               .resetvalue = 0 },
4981             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4982               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
4983               .access = PL1_R, .type = ARM_CP_CONST,
4984               .resetvalue = 0 },
4985             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4986               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
4987               .access = PL1_R, .type = ARM_CP_CONST,
4988               .resetvalue = 0 },
4989             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4990               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
4991               .access = PL1_R, .type = ARM_CP_CONST,
4992               .resetvalue = 0 },
4993             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
4994               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
4995               .access = PL1_R, .type = ARM_CP_CONST,
4996               .resetvalue = cpu->id_aa64dfr0 },
4997             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
4998               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
4999               .access = PL1_R, .type = ARM_CP_CONST,
5000               .resetvalue = cpu->id_aa64dfr1 },
5001             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5002               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
5003               .access = PL1_R, .type = ARM_CP_CONST,
5004               .resetvalue = 0 },
5005             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5006               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
5007               .access = PL1_R, .type = ARM_CP_CONST,
5008               .resetvalue = 0 },
5009             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
5010               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
5011               .access = PL1_R, .type = ARM_CP_CONST,
5012               .resetvalue = cpu->id_aa64afr0 },
5013             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
5014               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
5015               .access = PL1_R, .type = ARM_CP_CONST,
5016               .resetvalue = cpu->id_aa64afr1 },
5017             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5018               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
5019               .access = PL1_R, .type = ARM_CP_CONST,
5020               .resetvalue = 0 },
5021             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5022               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
5023               .access = PL1_R, .type = ARM_CP_CONST,
5024               .resetvalue = 0 },
5025             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
5026               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
5027               .access = PL1_R, .type = ARM_CP_CONST,
5028               .resetvalue = cpu->id_aa64isar0 },
5029             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
5030               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
5031               .access = PL1_R, .type = ARM_CP_CONST,
5032               .resetvalue = cpu->id_aa64isar1 },
5033             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5034               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
5035               .access = PL1_R, .type = ARM_CP_CONST,
5036               .resetvalue = 0 },
5037             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5038               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
5039               .access = PL1_R, .type = ARM_CP_CONST,
5040               .resetvalue = 0 },
5041             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5042               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
5043               .access = PL1_R, .type = ARM_CP_CONST,
5044               .resetvalue = 0 },
5045             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5046               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
5047               .access = PL1_R, .type = ARM_CP_CONST,
5048               .resetvalue = 0 },
5049             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5050               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
5051               .access = PL1_R, .type = ARM_CP_CONST,
5052               .resetvalue = 0 },
5053             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5054               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
5055               .access = PL1_R, .type = ARM_CP_CONST,
5056               .resetvalue = 0 },
5057             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
5058               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5059               .access = PL1_R, .type = ARM_CP_CONST,
5060               .resetvalue = cpu->id_aa64mmfr0 },
5061             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
5062               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
5063               .access = PL1_R, .type = ARM_CP_CONST,
5064               .resetvalue = cpu->id_aa64mmfr1 },
5065             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5066               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
5067               .access = PL1_R, .type = ARM_CP_CONST,
5068               .resetvalue = 0 },
5069             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5070               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
5071               .access = PL1_R, .type = ARM_CP_CONST,
5072               .resetvalue = 0 },
5073             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5074               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
5075               .access = PL1_R, .type = ARM_CP_CONST,
5076               .resetvalue = 0 },
5077             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5078               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
5079               .access = PL1_R, .type = ARM_CP_CONST,
5080               .resetvalue = 0 },
5081             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5082               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
5083               .access = PL1_R, .type = ARM_CP_CONST,
5084               .resetvalue = 0 },
5085             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5086               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
5087               .access = PL1_R, .type = ARM_CP_CONST,
5088               .resetvalue = 0 },
5089             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
5090               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
5091               .access = PL1_R, .type = ARM_CP_CONST,
5092               .resetvalue = cpu->mvfr0 },
5093             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
5094               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
5095               .access = PL1_R, .type = ARM_CP_CONST,
5096               .resetvalue = cpu->mvfr1 },
5097             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
5098               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
5099               .access = PL1_R, .type = ARM_CP_CONST,
5100               .resetvalue = cpu->mvfr2 },
5101             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5102               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
5103               .access = PL1_R, .type = ARM_CP_CONST,
5104               .resetvalue = 0 },
5105             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5106               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
5107               .access = PL1_R, .type = ARM_CP_CONST,
5108               .resetvalue = 0 },
5109             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5110               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
5111               .access = PL1_R, .type = ARM_CP_CONST,
5112               .resetvalue = 0 },
5113             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5114               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
5115               .access = PL1_R, .type = ARM_CP_CONST,
5116               .resetvalue = 0 },
5117             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5118               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
5119               .access = PL1_R, .type = ARM_CP_CONST,
5120               .resetvalue = 0 },
5121             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
5122               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
5123               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5124               .resetvalue = cpu->pmceid0 },
5125             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
5126               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
5127               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5128               .resetvalue = cpu->pmceid0 },
5129             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
5130               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
5131               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5132               .resetvalue = cpu->pmceid1 },
5133             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
5134               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
5135               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5136               .resetvalue = cpu->pmceid1 },
5137             REGINFO_SENTINEL
5138         };
5139         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
5140         if (!arm_feature(env, ARM_FEATURE_EL3) &&
5141             !arm_feature(env, ARM_FEATURE_EL2)) {
5142             ARMCPRegInfo rvbar = {
5143                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
5144                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5145                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
5146             };
5147             define_one_arm_cp_reg(cpu, &rvbar);
5148         }
5149         define_arm_cp_regs(cpu, v8_idregs);
5150         define_arm_cp_regs(cpu, v8_cp_reginfo);
5151     }
5152     if (arm_feature(env, ARM_FEATURE_EL2)) {
5153         uint64_t vmpidr_def = mpidr_read_val(env);
5154         ARMCPRegInfo vpidr_regs[] = {
5155             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
5156               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5157               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5158               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
5159               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
5160             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
5161               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5162               .access = PL2_RW, .resetvalue = cpu->midr,
5163               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5164             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
5165               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5166               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5167               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
5168               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
5169             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
5170               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5171               .access = PL2_RW,
5172               .resetvalue = vmpidr_def,
5173               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
5174             REGINFO_SENTINEL
5175         };
5176         define_arm_cp_regs(cpu, vpidr_regs);
5177         define_arm_cp_regs(cpu, el2_cp_reginfo);
5178         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
5179         if (!arm_feature(env, ARM_FEATURE_EL3)) {
5180             ARMCPRegInfo rvbar = {
5181                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
5182                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
5183                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
5184             };
5185             define_one_arm_cp_reg(cpu, &rvbar);
5186         }
5187     } else {
5188         /* If EL2 is missing but higher ELs are enabled, we need to
5189          * register the no_el2 reginfos.
5190          */
5191         if (arm_feature(env, ARM_FEATURE_EL3)) {
5192             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
5193              * of MIDR_EL1 and MPIDR_EL1.
5194              */
5195             ARMCPRegInfo vpidr_regs[] = {
5196                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5197                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5198                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5199                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
5200                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5201                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5202                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5203                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5204                   .type = ARM_CP_NO_RAW,
5205                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
5206                 REGINFO_SENTINEL
5207             };
5208             define_arm_cp_regs(cpu, vpidr_regs);
5209             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
5210         }
5211     }
5212     if (arm_feature(env, ARM_FEATURE_EL3)) {
5213         define_arm_cp_regs(cpu, el3_cp_reginfo);
5214         ARMCPRegInfo el3_regs[] = {
5215             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
5216               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
5217               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
5218             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
5219               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
5220               .access = PL3_RW,
5221               .raw_writefn = raw_write, .writefn = sctlr_write,
5222               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
5223               .resetvalue = cpu->reset_sctlr },
5224             REGINFO_SENTINEL
5225         };
5226
5227         define_arm_cp_regs(cpu, el3_regs);
5228     }
5229     /* The behaviour of NSACR is sufficiently various that we don't
5230      * try to describe it in a single reginfo:
5231      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
5232      *     reads as constant 0xc00 from NS EL1 and NS EL2
5233      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
5234      *  if v7 without EL3, register doesn't exist
5235      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
5236      */
5237     if (arm_feature(env, ARM_FEATURE_EL3)) {
5238         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5239             ARMCPRegInfo nsacr = {
5240                 .name = "NSACR", .type = ARM_CP_CONST,
5241                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5242                 .access = PL1_RW, .accessfn = nsacr_access,
5243                 .resetvalue = 0xc00
5244             };
5245             define_one_arm_cp_reg(cpu, &nsacr);
5246         } else {
5247             ARMCPRegInfo nsacr = {
5248                 .name = "NSACR",
5249                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5250                 .access = PL3_RW | PL1_R,
5251                 .resetvalue = 0,
5252                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
5253             };
5254             define_one_arm_cp_reg(cpu, &nsacr);
5255         }
5256     } else {
5257         if (arm_feature(env, ARM_FEATURE_V8)) {
5258             ARMCPRegInfo nsacr = {
5259                 .name = "NSACR", .type = ARM_CP_CONST,
5260                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5261                 .access = PL1_R,
5262                 .resetvalue = 0xc00
5263             };
5264             define_one_arm_cp_reg(cpu, &nsacr);
5265         }
5266     }
5267
5268     if (arm_feature(env, ARM_FEATURE_PMSA)) {
5269         if (arm_feature(env, ARM_FEATURE_V6)) {
5270             /* PMSAv6 not implemented */
5271             assert(arm_feature(env, ARM_FEATURE_V7));
5272             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5273             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
5274         } else {
5275             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
5276         }
5277     } else {
5278         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5279         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
5280     }
5281     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
5282         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
5283     }
5284     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
5285         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
5286     }
5287     if (arm_feature(env, ARM_FEATURE_VAPA)) {
5288         define_arm_cp_regs(cpu, vapa_cp_reginfo);
5289     }
5290     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
5291         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
5292     }
5293     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
5294         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
5295     }
5296     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
5297         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
5298     }
5299     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
5300         define_arm_cp_regs(cpu, omap_cp_reginfo);
5301     }
5302     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
5303         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
5304     }
5305     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5306         define_arm_cp_regs(cpu, xscale_cp_reginfo);
5307     }
5308     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
5309         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
5310     }
5311     if (arm_feature(env, ARM_FEATURE_LPAE)) {
5312         define_arm_cp_regs(cpu, lpae_cp_reginfo);
5313     }
5314     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
5315      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
5316      * be read-only (ie write causes UNDEF exception).
5317      */
5318     {
5319         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
5320             /* Pre-v8 MIDR space.
5321              * Note that the MIDR isn't a simple constant register because
5322              * of the TI925 behaviour where writes to another register can
5323              * cause the MIDR value to change.
5324              *
5325              * Unimplemented registers in the c15 0 0 0 space default to
5326              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
5327              * and friends override accordingly.
5328              */
5329             { .name = "MIDR",
5330               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
5331               .access = PL1_R, .resetvalue = cpu->midr,
5332               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
5333               .readfn = midr_read,
5334               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5335               .type = ARM_CP_OVERRIDE },
5336             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
5337             { .name = "DUMMY",
5338               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
5339               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5340             { .name = "DUMMY",
5341               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
5342               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5343             { .name = "DUMMY",
5344               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
5345               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5346             { .name = "DUMMY",
5347               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
5348               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5349             { .name = "DUMMY",
5350               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
5351               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5352             REGINFO_SENTINEL
5353         };
5354         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
5355             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
5356               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
5357               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
5358               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5359               .readfn = midr_read },
5360             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
5361             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5362               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5363               .access = PL1_R, .resetvalue = cpu->midr },
5364             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5365               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
5366               .access = PL1_R, .resetvalue = cpu->midr },
5367             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
5368               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
5369               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
5370             REGINFO_SENTINEL
5371         };
5372         ARMCPRegInfo id_cp_reginfo[] = {
5373             /* These are common to v8 and pre-v8 */
5374             { .name = "CTR",
5375               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
5376               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5377             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
5378               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
5379               .access = PL0_R, .accessfn = ctr_el0_access,
5380               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5381             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
5382             { .name = "TCMTR",
5383               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
5384               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5385             REGINFO_SENTINEL
5386         };
5387         /* TLBTR is specific to VMSA */
5388         ARMCPRegInfo id_tlbtr_reginfo = {
5389               .name = "TLBTR",
5390               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
5391               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
5392         };
5393         /* MPUIR is specific to PMSA V6+ */
5394         ARMCPRegInfo id_mpuir_reginfo = {
5395               .name = "MPUIR",
5396               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5397               .access = PL1_R, .type = ARM_CP_CONST,
5398               .resetvalue = cpu->pmsav7_dregion << 8
5399         };
5400         ARMCPRegInfo crn0_wi_reginfo = {
5401             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
5402             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
5403             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
5404         };
5405         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
5406             arm_feature(env, ARM_FEATURE_STRONGARM)) {
5407             ARMCPRegInfo *r;
5408             /* Register the blanket "writes ignored" value first to cover the
5409              * whole space. Then update the specific ID registers to allow write
5410              * access, so that they ignore writes rather than causing them to
5411              * UNDEF.
5412              */
5413             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
5414             for (r = id_pre_v8_midr_cp_reginfo;
5415                  r->type != ARM_CP_SENTINEL; r++) {
5416                 r->access = PL1_RW;
5417             }
5418             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
5419                 r->access = PL1_RW;
5420             }
5421             id_mpuir_reginfo.access = PL1_RW;
5422             id_tlbtr_reginfo.access = PL1_RW;
5423         }
5424         if (arm_feature(env, ARM_FEATURE_V8)) {
5425             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
5426         } else {
5427             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
5428         }
5429         define_arm_cp_regs(cpu, id_cp_reginfo);
5430         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
5431             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
5432         } else if (arm_feature(env, ARM_FEATURE_V7)) {
5433             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
5434         }
5435     }
5436
5437     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
5438         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
5439     }
5440
5441     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
5442         ARMCPRegInfo auxcr_reginfo[] = {
5443             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
5444               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
5445               .access = PL1_RW, .type = ARM_CP_CONST,
5446               .resetvalue = cpu->reset_auxcr },
5447             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
5448               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
5449               .access = PL2_RW, .type = ARM_CP_CONST,
5450               .resetvalue = 0 },
5451             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
5452               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
5453               .access = PL3_RW, .type = ARM_CP_CONST,
5454               .resetvalue = 0 },
5455             REGINFO_SENTINEL
5456         };
5457         define_arm_cp_regs(cpu, auxcr_reginfo);
5458     }
5459
5460     if (arm_feature(env, ARM_FEATURE_CBAR)) {
5461         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5462             /* 32 bit view is [31:18] 0...0 [43:32]. */
5463             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
5464                 | extract64(cpu->reset_cbar, 32, 12);
5465             ARMCPRegInfo cbar_reginfo[] = {
5466                 { .name = "CBAR",
5467                   .type = ARM_CP_CONST,
5468                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5469                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
5470                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
5471                   .type = ARM_CP_CONST,
5472                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
5473                   .access = PL1_R, .resetvalue = cbar32 },
5474                 REGINFO_SENTINEL
5475             };
5476             /* We don't implement a r/w 64 bit CBAR currently */
5477             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
5478             define_arm_cp_regs(cpu, cbar_reginfo);
5479         } else {
5480             ARMCPRegInfo cbar = {
5481                 .name = "CBAR",
5482                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5483                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
5484                 .fieldoffset = offsetof(CPUARMState,
5485                                         cp15.c15_config_base_address)
5486             };
5487             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
5488                 cbar.access = PL1_R;
5489                 cbar.fieldoffset = 0;
5490                 cbar.type = ARM_CP_CONST;
5491             }
5492             define_one_arm_cp_reg(cpu, &cbar);
5493         }
5494     }
5495
5496     if (arm_feature(env, ARM_FEATURE_VBAR)) {
5497         ARMCPRegInfo vbar_cp_reginfo[] = {
5498             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
5499               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
5500               .access = PL1_RW, .writefn = vbar_write,
5501               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
5502                                      offsetof(CPUARMState, cp15.vbar_ns) },
5503               .resetvalue = 0 },
5504             REGINFO_SENTINEL
5505         };
5506         define_arm_cp_regs(cpu, vbar_cp_reginfo);
5507     }
5508
5509     /* Generic registers whose values depend on the implementation */
5510     {
5511         ARMCPRegInfo sctlr = {
5512             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
5513             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5514             .access = PL1_RW,
5515             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
5516                                    offsetof(CPUARMState, cp15.sctlr_ns) },
5517             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
5518             .raw_writefn = raw_write,
5519         };
5520         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5521             /* Normally we would always end the TB on an SCTLR write, but Linux
5522              * arch/arm/mach-pxa/sleep.S expects two instructions following
5523              * an MMU enable to execute from cache.  Imitate this behaviour.
5524              */
5525             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
5526         }
5527         define_one_arm_cp_reg(cpu, &sctlr);
5528     }
5529
5530     if (arm_feature(env, ARM_FEATURE_SVE)) {
5531         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
5532         if (arm_feature(env, ARM_FEATURE_EL2)) {
5533             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
5534         } else {
5535             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
5536         }
5537         if (arm_feature(env, ARM_FEATURE_EL3)) {
5538             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
5539         }
5540     }
5541 }
5542
5543 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
5544 {
5545     CPUState *cs = CPU(cpu);
5546     CPUARMState *env = &cpu->env;
5547
5548     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5549         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
5550                                  aarch64_fpu_gdb_set_reg,
5551                                  34, "aarch64-fpu.xml", 0);
5552     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
5553         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5554                                  51, "arm-neon.xml", 0);
5555     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
5556         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5557                                  35, "arm-vfp3.xml", 0);
5558     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
5559         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5560                                  19, "arm-vfp.xml", 0);
5561     }
5562     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
5563                              arm_gen_dynamic_xml(cs),
5564                              "system-registers.xml", 0);
5565 }
5566
5567 /* Sort alphabetically by type name, except for "any". */
5568 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
5569 {
5570     ObjectClass *class_a = (ObjectClass *)a;
5571     ObjectClass *class_b = (ObjectClass *)b;
5572     const char *name_a, *name_b;
5573
5574     name_a = object_class_get_name(class_a);
5575     name_b = object_class_get_name(class_b);
5576     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
5577         return 1;
5578     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
5579         return -1;
5580     } else {
5581         return strcmp(name_a, name_b);
5582     }
5583 }
5584
5585 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
5586 {
5587     ObjectClass *oc = data;
5588     CPUListState *s = user_data;
5589     const char *typename;
5590     char *name;
5591
5592     typename = object_class_get_name(oc);
5593     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
5594     (*s->cpu_fprintf)(s->file, "  %s\n",
5595                       name);
5596     g_free(name);
5597 }
5598
5599 void arm_cpu_list(FILE *f, fprintf_function cpu_fprintf)
5600 {
5601     CPUListState s = {
5602         .file = f,
5603         .cpu_fprintf = cpu_fprintf,
5604     };
5605     GSList *list;
5606
5607     list = object_class_get_list(TYPE_ARM_CPU, false);
5608     list = g_slist_sort(list, arm_cpu_list_compare);
5609     (*cpu_fprintf)(f, "Available CPUs:\n");
5610     g_slist_foreach(list, arm_cpu_list_entry, &s);
5611     g_slist_free(list);
5612 }
5613
5614 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
5615 {
5616     ObjectClass *oc = data;
5617     CpuDefinitionInfoList **cpu_list = user_data;
5618     CpuDefinitionInfoList *entry;
5619     CpuDefinitionInfo *info;
5620     const char *typename;
5621
5622     typename = object_class_get_name(oc);
5623     info = g_malloc0(sizeof(*info));
5624     info->name = g_strndup(typename,
5625                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
5626     info->q_typename = g_strdup(typename);
5627
5628     entry = g_malloc0(sizeof(*entry));
5629     entry->value = info;
5630     entry->next = *cpu_list;
5631     *cpu_list = entry;
5632 }
5633
5634 CpuDefinitionInfoList *arch_query_cpu_definitions(Error **errp)
5635 {
5636     CpuDefinitionInfoList *cpu_list = NULL;
5637     GSList *list;
5638
5639     list = object_class_get_list(TYPE_ARM_CPU, false);
5640     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
5641     g_slist_free(list);
5642
5643     return cpu_list;
5644 }
5645
5646 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
5647                                    void *opaque, int state, int secstate,
5648                                    int crm, int opc1, int opc2,
5649                                    const char *name)
5650 {
5651     /* Private utility function for define_one_arm_cp_reg_with_opaque():
5652      * add a single reginfo struct to the hash table.
5653      */
5654     uint32_t *key = g_new(uint32_t, 1);
5655     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
5656     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
5657     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
5658
5659     r2->name = g_strdup(name);
5660     /* Reset the secure state to the specific incoming state.  This is
5661      * necessary as the register may have been defined with both states.
5662      */
5663     r2->secure = secstate;
5664
5665     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5666         /* Register is banked (using both entries in array).
5667          * Overwriting fieldoffset as the array is only used to define
5668          * banked registers but later only fieldoffset is used.
5669          */
5670         r2->fieldoffset = r->bank_fieldoffsets[ns];
5671     }
5672
5673     if (state == ARM_CP_STATE_AA32) {
5674         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5675             /* If the register is banked then we don't need to migrate or
5676              * reset the 32-bit instance in certain cases:
5677              *
5678              * 1) If the register has both 32-bit and 64-bit instances then we
5679              *    can count on the 64-bit instance taking care of the
5680              *    non-secure bank.
5681              * 2) If ARMv8 is enabled then we can count on a 64-bit version
5682              *    taking care of the secure bank.  This requires that separate
5683              *    32 and 64-bit definitions are provided.
5684              */
5685             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
5686                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
5687                 r2->type |= ARM_CP_ALIAS;
5688             }
5689         } else if ((secstate != r->secure) && !ns) {
5690             /* The register is not banked so we only want to allow migration of
5691              * the non-secure instance.
5692              */
5693             r2->type |= ARM_CP_ALIAS;
5694         }
5695
5696         if (r->state == ARM_CP_STATE_BOTH) {
5697             /* We assume it is a cp15 register if the .cp field is left unset.
5698              */
5699             if (r2->cp == 0) {
5700                 r2->cp = 15;
5701             }
5702
5703 #ifdef HOST_WORDS_BIGENDIAN
5704             if (r2->fieldoffset) {
5705                 r2->fieldoffset += sizeof(uint32_t);
5706             }
5707 #endif
5708         }
5709     }
5710     if (state == ARM_CP_STATE_AA64) {
5711         /* To allow abbreviation of ARMCPRegInfo
5712          * definitions, we treat cp == 0 as equivalent to
5713          * the value for "standard guest-visible sysreg".
5714          * STATE_BOTH definitions are also always "standard
5715          * sysreg" in their AArch64 view (the .cp value may
5716          * be non-zero for the benefit of the AArch32 view).
5717          */
5718         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
5719             r2->cp = CP_REG_ARM64_SYSREG_CP;
5720         }
5721         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
5722                                   r2->opc0, opc1, opc2);
5723     } else {
5724         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
5725     }
5726     if (opaque) {
5727         r2->opaque = opaque;
5728     }
5729     /* reginfo passed to helpers is correct for the actual access,
5730      * and is never ARM_CP_STATE_BOTH:
5731      */
5732     r2->state = state;
5733     /* Make sure reginfo passed to helpers for wildcarded regs
5734      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
5735      */
5736     r2->crm = crm;
5737     r2->opc1 = opc1;
5738     r2->opc2 = opc2;
5739     /* By convention, for wildcarded registers only the first
5740      * entry is used for migration; the others are marked as
5741      * ALIAS so we don't try to transfer the register
5742      * multiple times. Special registers (ie NOP/WFI) are
5743      * never migratable and not even raw-accessible.
5744      */
5745     if ((r->type & ARM_CP_SPECIAL)) {
5746         r2->type |= ARM_CP_NO_RAW;
5747     }
5748     if (((r->crm == CP_ANY) && crm != 0) ||
5749         ((r->opc1 == CP_ANY) && opc1 != 0) ||
5750         ((r->opc2 == CP_ANY) && opc2 != 0)) {
5751         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
5752     }
5753
5754     /* Check that raw accesses are either forbidden or handled. Note that
5755      * we can't assert this earlier because the setup of fieldoffset for
5756      * banked registers has to be done first.
5757      */
5758     if (!(r2->type & ARM_CP_NO_RAW)) {
5759         assert(!raw_accessors_invalid(r2));
5760     }
5761
5762     /* Overriding of an existing definition must be explicitly
5763      * requested.
5764      */
5765     if (!(r->type & ARM_CP_OVERRIDE)) {
5766         ARMCPRegInfo *oldreg;
5767         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
5768         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
5769             fprintf(stderr, "Register redefined: cp=%d %d bit "
5770                     "crn=%d crm=%d opc1=%d opc2=%d, "
5771                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
5772                     r2->crn, r2->crm, r2->opc1, r2->opc2,
5773                     oldreg->name, r2->name);
5774             g_assert_not_reached();
5775         }
5776     }
5777     g_hash_table_insert(cpu->cp_regs, key, r2);
5778 }
5779
5780
5781 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
5782                                        const ARMCPRegInfo *r, void *opaque)
5783 {
5784     /* Define implementations of coprocessor registers.
5785      * We store these in a hashtable because typically
5786      * there are less than 150 registers in a space which
5787      * is 16*16*16*8*8 = 262144 in size.
5788      * Wildcarding is supported for the crm, opc1 and opc2 fields.
5789      * If a register is defined twice then the second definition is
5790      * used, so this can be used to define some generic registers and
5791      * then override them with implementation specific variations.
5792      * At least one of the original and the second definition should
5793      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
5794      * against accidental use.
5795      *
5796      * The state field defines whether the register is to be
5797      * visible in the AArch32 or AArch64 execution state. If the
5798      * state is set to ARM_CP_STATE_BOTH then we synthesise a
5799      * reginfo structure for the AArch32 view, which sees the lower
5800      * 32 bits of the 64 bit register.
5801      *
5802      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
5803      * be wildcarded. AArch64 registers are always considered to be 64
5804      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
5805      * the register, if any.
5806      */
5807     int crm, opc1, opc2, state;
5808     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
5809     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
5810     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
5811     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
5812     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
5813     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
5814     /* 64 bit registers have only CRm and Opc1 fields */
5815     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
5816     /* op0 only exists in the AArch64 encodings */
5817     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
5818     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
5819     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
5820     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
5821      * encodes a minimum access level for the register. We roll this
5822      * runtime check into our general permission check code, so check
5823      * here that the reginfo's specified permissions are strict enough
5824      * to encompass the generic architectural permission check.
5825      */
5826     if (r->state != ARM_CP_STATE_AA32) {
5827         int mask = 0;
5828         switch (r->opc1) {
5829         case 0: case 1: case 2:
5830             /* min_EL EL1 */
5831             mask = PL1_RW;
5832             break;
5833         case 3:
5834             /* min_EL EL0 */
5835             mask = PL0_RW;
5836             break;
5837         case 4:
5838             /* min_EL EL2 */
5839             mask = PL2_RW;
5840             break;
5841         case 5:
5842             /* unallocated encoding, so not possible */
5843             assert(false);
5844             break;
5845         case 6:
5846             /* min_EL EL3 */
5847             mask = PL3_RW;
5848             break;
5849         case 7:
5850             /* min_EL EL1, secure mode only (we don't check the latter) */
5851             mask = PL1_RW;
5852             break;
5853         default:
5854             /* broken reginfo with out-of-range opc1 */
5855             assert(false);
5856             break;
5857         }
5858         /* assert our permissions are not too lax (stricter is fine) */
5859         assert((r->access & ~mask) == 0);
5860     }
5861
5862     /* Check that the register definition has enough info to handle
5863      * reads and writes if they are permitted.
5864      */
5865     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
5866         if (r->access & PL3_R) {
5867             assert((r->fieldoffset ||
5868                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5869                    r->readfn);
5870         }
5871         if (r->access & PL3_W) {
5872             assert((r->fieldoffset ||
5873                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5874                    r->writefn);
5875         }
5876     }
5877     /* Bad type field probably means missing sentinel at end of reg list */
5878     assert(cptype_valid(r->type));
5879     for (crm = crmmin; crm <= crmmax; crm++) {
5880         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
5881             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
5882                 for (state = ARM_CP_STATE_AA32;
5883                      state <= ARM_CP_STATE_AA64; state++) {
5884                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
5885                         continue;
5886                     }
5887                     if (state == ARM_CP_STATE_AA32) {
5888                         /* Under AArch32 CP registers can be common
5889                          * (same for secure and non-secure world) or banked.
5890                          */
5891                         char *name;
5892
5893                         switch (r->secure) {
5894                         case ARM_CP_SECSTATE_S:
5895                         case ARM_CP_SECSTATE_NS:
5896                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5897                                                    r->secure, crm, opc1, opc2,
5898                                                    r->name);
5899                             break;
5900                         default:
5901                             name = g_strdup_printf("%s_S", r->name);
5902                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5903                                                    ARM_CP_SECSTATE_S,
5904                                                    crm, opc1, opc2, name);
5905                             g_free(name);
5906                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5907                                                    ARM_CP_SECSTATE_NS,
5908                                                    crm, opc1, opc2, r->name);
5909                             break;
5910                         }
5911                     } else {
5912                         /* AArch64 registers get mapped to non-secure instance
5913                          * of AArch32 */
5914                         add_cpreg_to_hashtable(cpu, r, opaque, state,
5915                                                ARM_CP_SECSTATE_NS,
5916                                                crm, opc1, opc2, r->name);
5917                     }
5918                 }
5919             }
5920         }
5921     }
5922 }
5923
5924 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
5925                                     const ARMCPRegInfo *regs, void *opaque)
5926 {
5927     /* Define a whole list of registers */
5928     const ARMCPRegInfo *r;
5929     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
5930         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
5931     }
5932 }
5933
5934 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
5935 {
5936     return g_hash_table_lookup(cpregs, &encoded_cp);
5937 }
5938
5939 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
5940                          uint64_t value)
5941 {
5942     /* Helper coprocessor write function for write-ignore registers */
5943 }
5944
5945 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
5946 {
5947     /* Helper coprocessor write function for read-as-zero registers */
5948     return 0;
5949 }
5950
5951 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
5952 {
5953     /* Helper coprocessor reset function for do-nothing-on-reset registers */
5954 }
5955
5956 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
5957 {
5958     /* Return true if it is not valid for us to switch to
5959      * this CPU mode (ie all the UNPREDICTABLE cases in
5960      * the ARM ARM CPSRWriteByInstr pseudocode).
5961      */
5962
5963     /* Changes to or from Hyp via MSR and CPS are illegal. */
5964     if (write_type == CPSRWriteByInstr &&
5965         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
5966          mode == ARM_CPU_MODE_HYP)) {
5967         return 1;
5968     }
5969
5970     switch (mode) {
5971     case ARM_CPU_MODE_USR:
5972         return 0;
5973     case ARM_CPU_MODE_SYS:
5974     case ARM_CPU_MODE_SVC:
5975     case ARM_CPU_MODE_ABT:
5976     case ARM_CPU_MODE_UND:
5977     case ARM_CPU_MODE_IRQ:
5978     case ARM_CPU_MODE_FIQ:
5979         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
5980          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
5981          */
5982         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
5983          * and CPS are treated as illegal mode changes.
5984          */
5985         if (write_type == CPSRWriteByInstr &&
5986             (env->cp15.hcr_el2 & HCR_TGE) &&
5987             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
5988             !arm_is_secure_below_el3(env)) {
5989             return 1;
5990         }
5991         return 0;
5992     case ARM_CPU_MODE_HYP:
5993         return !arm_feature(env, ARM_FEATURE_EL2)
5994             || arm_current_el(env) < 2 || arm_is_secure(env);
5995     case ARM_CPU_MODE_MON:
5996         return arm_current_el(env) < 3;
5997     default:
5998         return 1;
5999     }
6000 }
6001
6002 uint32_t cpsr_read(CPUARMState *env)
6003 {
6004     int ZF;
6005     ZF = (env->ZF == 0);
6006     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
6007         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
6008         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
6009         | ((env->condexec_bits & 0xfc) << 8)
6010         | (env->GE << 16) | (env->daif & CPSR_AIF);
6011 }
6012
6013 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
6014                 CPSRWriteType write_type)
6015 {
6016     uint32_t changed_daif;
6017
6018     if (mask & CPSR_NZCV) {
6019         env->ZF = (~val) & CPSR_Z;
6020         env->NF = val;
6021         env->CF = (val >> 29) & 1;
6022         env->VF = (val << 3) & 0x80000000;
6023     }
6024     if (mask & CPSR_Q)
6025         env->QF = ((val & CPSR_Q) != 0);
6026     if (mask & CPSR_T)
6027         env->thumb = ((val & CPSR_T) != 0);
6028     if (mask & CPSR_IT_0_1) {
6029         env->condexec_bits &= ~3;
6030         env->condexec_bits |= (val >> 25) & 3;
6031     }
6032     if (mask & CPSR_IT_2_7) {
6033         env->condexec_bits &= 3;
6034         env->condexec_bits |= (val >> 8) & 0xfc;
6035     }
6036     if (mask & CPSR_GE) {
6037         env->GE = (val >> 16) & 0xf;
6038     }
6039
6040     /* In a V7 implementation that includes the security extensions but does
6041      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
6042      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
6043      * bits respectively.
6044      *
6045      * In a V8 implementation, it is permitted for privileged software to
6046      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
6047      */
6048     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
6049         arm_feature(env, ARM_FEATURE_EL3) &&
6050         !arm_feature(env, ARM_FEATURE_EL2) &&
6051         !arm_is_secure(env)) {
6052
6053         changed_daif = (env->daif ^ val) & mask;
6054
6055         if (changed_daif & CPSR_A) {
6056             /* Check to see if we are allowed to change the masking of async
6057              * abort exceptions from a non-secure state.
6058              */
6059             if (!(env->cp15.scr_el3 & SCR_AW)) {
6060                 qemu_log_mask(LOG_GUEST_ERROR,
6061                               "Ignoring attempt to switch CPSR_A flag from "
6062                               "non-secure world with SCR.AW bit clear\n");
6063                 mask &= ~CPSR_A;
6064             }
6065         }
6066
6067         if (changed_daif & CPSR_F) {
6068             /* Check to see if we are allowed to change the masking of FIQ
6069              * exceptions from a non-secure state.
6070              */
6071             if (!(env->cp15.scr_el3 & SCR_FW)) {
6072                 qemu_log_mask(LOG_GUEST_ERROR,
6073                               "Ignoring attempt to switch CPSR_F flag from "
6074                               "non-secure world with SCR.FW bit clear\n");
6075                 mask &= ~CPSR_F;
6076             }
6077
6078             /* Check whether non-maskable FIQ (NMFI) support is enabled.
6079              * If this bit is set software is not allowed to mask
6080              * FIQs, but is allowed to set CPSR_F to 0.
6081              */
6082             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
6083                 (val & CPSR_F)) {
6084                 qemu_log_mask(LOG_GUEST_ERROR,
6085                               "Ignoring attempt to enable CPSR_F flag "
6086                               "(non-maskable FIQ [NMFI] support enabled)\n");
6087                 mask &= ~CPSR_F;
6088             }
6089         }
6090     }
6091
6092     env->daif &= ~(CPSR_AIF & mask);
6093     env->daif |= val & CPSR_AIF & mask;
6094
6095     if (write_type != CPSRWriteRaw &&
6096         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
6097         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
6098             /* Note that we can only get here in USR mode if this is a
6099              * gdb stub write; for this case we follow the architectural
6100              * behaviour for guest writes in USR mode of ignoring an attempt
6101              * to switch mode. (Those are caught by translate.c for writes
6102              * triggered by guest instructions.)
6103              */
6104             mask &= ~CPSR_M;
6105         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
6106             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
6107              * v7, and has defined behaviour in v8:
6108              *  + leave CPSR.M untouched
6109              *  + allow changes to the other CPSR fields
6110              *  + set PSTATE.IL
6111              * For user changes via the GDB stub, we don't set PSTATE.IL,
6112              * as this would be unnecessarily harsh for a user error.
6113              */
6114             mask &= ~CPSR_M;
6115             if (write_type != CPSRWriteByGDBStub &&
6116                 arm_feature(env, ARM_FEATURE_V8)) {
6117                 mask |= CPSR_IL;
6118                 val |= CPSR_IL;
6119             }
6120         } else {
6121             switch_mode(env, val & CPSR_M);
6122         }
6123     }
6124     mask &= ~CACHED_CPSR_BITS;
6125     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
6126 }
6127
6128 /* Sign/zero extend */
6129 uint32_t HELPER(sxtb16)(uint32_t x)
6130 {
6131     uint32_t res;
6132     res = (uint16_t)(int8_t)x;
6133     res |= (uint32_t)(int8_t)(x >> 16) << 16;
6134     return res;
6135 }
6136
6137 uint32_t HELPER(uxtb16)(uint32_t x)
6138 {
6139     uint32_t res;
6140     res = (uint16_t)(uint8_t)x;
6141     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
6142     return res;
6143 }
6144
6145 int32_t HELPER(sdiv)(int32_t num, int32_t den)
6146 {
6147     if (den == 0)
6148       return 0;
6149     if (num == INT_MIN && den == -1)
6150       return INT_MIN;
6151     return num / den;
6152 }
6153
6154 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
6155 {
6156     if (den == 0)
6157       return 0;
6158     return num / den;
6159 }
6160
6161 uint32_t HELPER(rbit)(uint32_t x)
6162 {
6163     return revbit32(x);
6164 }
6165
6166 #if defined(CONFIG_USER_ONLY)
6167
6168 /* These should probably raise undefined insn exceptions.  */
6169 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
6170 {
6171     ARMCPU *cpu = arm_env_get_cpu(env);
6172
6173     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
6174 }
6175
6176 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
6177 {
6178     ARMCPU *cpu = arm_env_get_cpu(env);
6179
6180     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
6181     return 0;
6182 }
6183
6184 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6185 {
6186     /* translate.c should never generate calls here in user-only mode */
6187     g_assert_not_reached();
6188 }
6189
6190 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6191 {
6192     /* translate.c should never generate calls here in user-only mode */
6193     g_assert_not_reached();
6194 }
6195
6196 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
6197 {
6198     /* The TT instructions can be used by unprivileged code, but in
6199      * user-only emulation we don't have the MPU.
6200      * Luckily since we know we are NonSecure unprivileged (and that in
6201      * turn means that the A flag wasn't specified), all the bits in the
6202      * register must be zero:
6203      *  IREGION: 0 because IRVALID is 0
6204      *  IRVALID: 0 because NS
6205      *  S: 0 because NS
6206      *  NSRW: 0 because NS
6207      *  NSR: 0 because NS
6208      *  RW: 0 because unpriv and A flag not set
6209      *  R: 0 because unpriv and A flag not set
6210      *  SRVALID: 0 because NS
6211      *  MRVALID: 0 because unpriv and A flag not set
6212      *  SREGION: 0 becaus SRVALID is 0
6213      *  MREGION: 0 because MRVALID is 0
6214      */
6215     return 0;
6216 }
6217
6218 void switch_mode(CPUARMState *env, int mode)
6219 {
6220     ARMCPU *cpu = arm_env_get_cpu(env);
6221
6222     if (mode != ARM_CPU_MODE_USR) {
6223         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
6224     }
6225 }
6226
6227 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6228                                  uint32_t cur_el, bool secure)
6229 {
6230     return 1;
6231 }
6232
6233 void aarch64_sync_64_to_32(CPUARMState *env)
6234 {
6235     g_assert_not_reached();
6236 }
6237
6238 #else
6239
6240 void switch_mode(CPUARMState *env, int mode)
6241 {
6242     int old_mode;
6243     int i;
6244
6245     old_mode = env->uncached_cpsr & CPSR_M;
6246     if (mode == old_mode)
6247         return;
6248
6249     if (old_mode == ARM_CPU_MODE_FIQ) {
6250         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
6251         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
6252     } else if (mode == ARM_CPU_MODE_FIQ) {
6253         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
6254         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
6255     }
6256
6257     i = bank_number(old_mode);
6258     env->banked_r13[i] = env->regs[13];
6259     env->banked_r14[i] = env->regs[14];
6260     env->banked_spsr[i] = env->spsr;
6261
6262     i = bank_number(mode);
6263     env->regs[13] = env->banked_r13[i];
6264     env->regs[14] = env->banked_r14[i];
6265     env->spsr = env->banked_spsr[i];
6266 }
6267
6268 /* Physical Interrupt Target EL Lookup Table
6269  *
6270  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
6271  *
6272  * The below multi-dimensional table is used for looking up the target
6273  * exception level given numerous condition criteria.  Specifically, the
6274  * target EL is based on SCR and HCR routing controls as well as the
6275  * currently executing EL and secure state.
6276  *
6277  *    Dimensions:
6278  *    target_el_table[2][2][2][2][2][4]
6279  *                    |  |  |  |  |  +--- Current EL
6280  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
6281  *                    |  |  |  +--------- HCR mask override
6282  *                    |  |  +------------ SCR exec state control
6283  *                    |  +--------------- SCR mask override
6284  *                    +------------------ 32-bit(0)/64-bit(1) EL3
6285  *
6286  *    The table values are as such:
6287  *    0-3 = EL0-EL3
6288  *     -1 = Cannot occur
6289  *
6290  * The ARM ARM target EL table includes entries indicating that an "exception
6291  * is not taken".  The two cases where this is applicable are:
6292  *    1) An exception is taken from EL3 but the SCR does not have the exception
6293  *    routed to EL3.
6294  *    2) An exception is taken from EL2 but the HCR does not have the exception
6295  *    routed to EL2.
6296  * In these two cases, the below table contain a target of EL1.  This value is
6297  * returned as it is expected that the consumer of the table data will check
6298  * for "target EL >= current EL" to ensure the exception is not taken.
6299  *
6300  *            SCR     HCR
6301  *         64  EA     AMO                 From
6302  *        BIT IRQ     IMO      Non-secure         Secure
6303  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
6304  */
6305 static const int8_t target_el_table[2][2][2][2][2][4] = {
6306     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6307        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
6308       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6309        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
6310      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6311        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
6312       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6313        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
6314     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
6315        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
6316       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
6317        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
6318      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6319        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
6320       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6321        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
6322 };
6323
6324 /*
6325  * Determine the target EL for physical exceptions
6326  */
6327 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6328                                  uint32_t cur_el, bool secure)
6329 {
6330     CPUARMState *env = cs->env_ptr;
6331     int rw;
6332     int scr;
6333     int hcr;
6334     int target_el;
6335     /* Is the highest EL AArch64? */
6336     int is64 = arm_feature(env, ARM_FEATURE_AARCH64);
6337
6338     if (arm_feature(env, ARM_FEATURE_EL3)) {
6339         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
6340     } else {
6341         /* Either EL2 is the highest EL (and so the EL2 register width
6342          * is given by is64); or there is no EL2 or EL3, in which case
6343          * the value of 'rw' does not affect the table lookup anyway.
6344          */
6345         rw = is64;
6346     }
6347
6348     switch (excp_idx) {
6349     case EXCP_IRQ:
6350         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
6351         hcr = arm_hcr_el2_imo(env);
6352         break;
6353     case EXCP_FIQ:
6354         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
6355         hcr = arm_hcr_el2_fmo(env);
6356         break;
6357     default:
6358         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
6359         hcr = arm_hcr_el2_amo(env);
6360         break;
6361     };
6362
6363     /* If HCR.TGE is set then HCR is treated as being 1 */
6364     hcr |= ((env->cp15.hcr_el2 & HCR_TGE) == HCR_TGE);
6365
6366     /* Perform a table-lookup for the target EL given the current state */
6367     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
6368
6369     assert(target_el > 0);
6370
6371     return target_el;
6372 }
6373
6374 static bool v7m_stack_write(ARMCPU *cpu, uint32_t addr, uint32_t value,
6375                             ARMMMUIdx mmu_idx, bool ignfault)
6376 {
6377     CPUState *cs = CPU(cpu);
6378     CPUARMState *env = &cpu->env;
6379     MemTxAttrs attrs = {};
6380     MemTxResult txres;
6381     target_ulong page_size;
6382     hwaddr physaddr;
6383     int prot;
6384     ARMMMUFaultInfo fi;
6385     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6386     int exc;
6387     bool exc_secure;
6388
6389     if (get_phys_addr(env, addr, MMU_DATA_STORE, mmu_idx, &physaddr,
6390                       &attrs, &prot, &page_size, &fi, NULL)) {
6391         /* MPU/SAU lookup failed */
6392         if (fi.type == ARMFault_QEMU_SFault) {
6393             qemu_log_mask(CPU_LOG_INT,
6394                           "...SecureFault with SFSR.AUVIOL during stacking\n");
6395             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
6396             env->v7m.sfar = addr;
6397             exc = ARMV7M_EXCP_SECURE;
6398             exc_secure = false;
6399         } else {
6400             qemu_log_mask(CPU_LOG_INT, "...MemManageFault with CFSR.MSTKERR\n");
6401             env->v7m.cfsr[secure] |= R_V7M_CFSR_MSTKERR_MASK;
6402             exc = ARMV7M_EXCP_MEM;
6403             exc_secure = secure;
6404         }
6405         goto pend_fault;
6406     }
6407     address_space_stl_le(arm_addressspace(cs, attrs), physaddr, value,
6408                          attrs, &txres);
6409     if (txres != MEMTX_OK) {
6410         /* BusFault trying to write the data */
6411         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.STKERR\n");
6412         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_STKERR_MASK;
6413         exc = ARMV7M_EXCP_BUS;
6414         exc_secure = false;
6415         goto pend_fault;
6416     }
6417     return true;
6418
6419 pend_fault:
6420     /* By pending the exception at this point we are making
6421      * the IMPDEF choice "overridden exceptions pended" (see the
6422      * MergeExcInfo() pseudocode). The other choice would be to not
6423      * pend them now and then make a choice about which to throw away
6424      * later if we have two derived exceptions.
6425      * The only case when we must not pend the exception but instead
6426      * throw it away is if we are doing the push of the callee registers
6427      * and we've already generated a derived exception. Even in this
6428      * case we will still update the fault status registers.
6429      */
6430     if (!ignfault) {
6431         armv7m_nvic_set_pending_derived(env->nvic, exc, exc_secure);
6432     }
6433     return false;
6434 }
6435
6436 static bool v7m_stack_read(ARMCPU *cpu, uint32_t *dest, uint32_t addr,
6437                            ARMMMUIdx mmu_idx)
6438 {
6439     CPUState *cs = CPU(cpu);
6440     CPUARMState *env = &cpu->env;
6441     MemTxAttrs attrs = {};
6442     MemTxResult txres;
6443     target_ulong page_size;
6444     hwaddr physaddr;
6445     int prot;
6446     ARMMMUFaultInfo fi;
6447     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6448     int exc;
6449     bool exc_secure;
6450     uint32_t value;
6451
6452     if (get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &physaddr,
6453                       &attrs, &prot, &page_size, &fi, NULL)) {
6454         /* MPU/SAU lookup failed */
6455         if (fi.type == ARMFault_QEMU_SFault) {
6456             qemu_log_mask(CPU_LOG_INT,
6457                           "...SecureFault with SFSR.AUVIOL during unstack\n");
6458             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
6459             env->v7m.sfar = addr;
6460             exc = ARMV7M_EXCP_SECURE;
6461             exc_secure = false;
6462         } else {
6463             qemu_log_mask(CPU_LOG_INT,
6464                           "...MemManageFault with CFSR.MUNSTKERR\n");
6465             env->v7m.cfsr[secure] |= R_V7M_CFSR_MUNSTKERR_MASK;
6466             exc = ARMV7M_EXCP_MEM;
6467             exc_secure = secure;
6468         }
6469         goto pend_fault;
6470     }
6471
6472     value = address_space_ldl(arm_addressspace(cs, attrs), physaddr,
6473                               attrs, &txres);
6474     if (txres != MEMTX_OK) {
6475         /* BusFault trying to read the data */
6476         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.UNSTKERR\n");
6477         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_UNSTKERR_MASK;
6478         exc = ARMV7M_EXCP_BUS;
6479         exc_secure = false;
6480         goto pend_fault;
6481     }
6482
6483     *dest = value;
6484     return true;
6485
6486 pend_fault:
6487     /* By pending the exception at this point we are making
6488      * the IMPDEF choice "overridden exceptions pended" (see the
6489      * MergeExcInfo() pseudocode). The other choice would be to not
6490      * pend them now and then make a choice about which to throw away
6491      * later if we have two derived exceptions.
6492      */
6493     armv7m_nvic_set_pending(env->nvic, exc, exc_secure);
6494     return false;
6495 }
6496
6497 /* Return true if we're using the process stack pointer (not the MSP) */
6498 static bool v7m_using_psp(CPUARMState *env)
6499 {
6500     /* Handler mode always uses the main stack; for thread mode
6501      * the CONTROL.SPSEL bit determines the answer.
6502      * Note that in v7M it is not possible to be in Handler mode with
6503      * CONTROL.SPSEL non-zero, but in v8M it is, so we must check both.
6504      */
6505     return !arm_v7m_is_handler_mode(env) &&
6506         env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_SPSEL_MASK;
6507 }
6508
6509 /* Write to v7M CONTROL.SPSEL bit for the specified security bank.
6510  * This may change the current stack pointer between Main and Process
6511  * stack pointers if it is done for the CONTROL register for the current
6512  * security state.
6513  */
6514 static void write_v7m_control_spsel_for_secstate(CPUARMState *env,
6515                                                  bool new_spsel,
6516                                                  bool secstate)
6517 {
6518     bool old_is_psp = v7m_using_psp(env);
6519
6520     env->v7m.control[secstate] =
6521         deposit32(env->v7m.control[secstate],
6522                   R_V7M_CONTROL_SPSEL_SHIFT,
6523                   R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);
6524
6525     if (secstate == env->v7m.secure) {
6526         bool new_is_psp = v7m_using_psp(env);
6527         uint32_t tmp;
6528
6529         if (old_is_psp != new_is_psp) {
6530             tmp = env->v7m.other_sp;
6531             env->v7m.other_sp = env->regs[13];
6532             env->regs[13] = tmp;
6533         }
6534     }
6535 }
6536
6537 /* Write to v7M CONTROL.SPSEL bit. This may change the current
6538  * stack pointer between Main and Process stack pointers.
6539  */
6540 static void write_v7m_control_spsel(CPUARMState *env, bool new_spsel)
6541 {
6542     write_v7m_control_spsel_for_secstate(env, new_spsel, env->v7m.secure);
6543 }
6544
6545 void write_v7m_exception(CPUARMState *env, uint32_t new_exc)
6546 {
6547     /* Write a new value to v7m.exception, thus transitioning into or out
6548      * of Handler mode; this may result in a change of active stack pointer.
6549      */
6550     bool new_is_psp, old_is_psp = v7m_using_psp(env);
6551     uint32_t tmp;
6552
6553     env->v7m.exception = new_exc;
6554
6555     new_is_psp = v7m_using_psp(env);
6556
6557     if (old_is_psp != new_is_psp) {
6558         tmp = env->v7m.other_sp;
6559         env->v7m.other_sp = env->regs[13];
6560         env->regs[13] = tmp;
6561     }
6562 }
6563
6564 /* Switch M profile security state between NS and S */
6565 static void switch_v7m_security_state(CPUARMState *env, bool new_secstate)
6566 {
6567     uint32_t new_ss_msp, new_ss_psp;
6568
6569     if (env->v7m.secure == new_secstate) {
6570         return;
6571     }
6572
6573     /* All the banked state is accessed by looking at env->v7m.secure
6574      * except for the stack pointer; rearrange the SP appropriately.
6575      */
6576     new_ss_msp = env->v7m.other_ss_msp;
6577     new_ss_psp = env->v7m.other_ss_psp;
6578
6579     if (v7m_using_psp(env)) {
6580         env->v7m.other_ss_psp = env->regs[13];
6581         env->v7m.other_ss_msp = env->v7m.other_sp;
6582     } else {
6583         env->v7m.other_ss_msp = env->regs[13];
6584         env->v7m.other_ss_psp = env->v7m.other_sp;
6585     }
6586
6587     env->v7m.secure = new_secstate;
6588
6589     if (v7m_using_psp(env)) {
6590         env->regs[13] = new_ss_psp;
6591         env->v7m.other_sp = new_ss_msp;
6592     } else {
6593         env->regs[13] = new_ss_msp;
6594         env->v7m.other_sp = new_ss_psp;
6595     }
6596 }
6597
6598 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6599 {
6600     /* Handle v7M BXNS:
6601      *  - if the return value is a magic value, do exception return (like BX)
6602      *  - otherwise bit 0 of the return value is the target security state
6603      */
6604     uint32_t min_magic;
6605
6606     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6607         /* Covers FNC_RETURN and EXC_RETURN magic */
6608         min_magic = FNC_RETURN_MIN_MAGIC;
6609     } else {
6610         /* EXC_RETURN magic only */
6611         min_magic = EXC_RETURN_MIN_MAGIC;
6612     }
6613
6614     if (dest >= min_magic) {
6615         /* This is an exception return magic value; put it where
6616          * do_v7m_exception_exit() expects and raise EXCEPTION_EXIT.
6617          * Note that if we ever add gen_ss_advance() singlestep support to
6618          * M profile this should count as an "instruction execution complete"
6619          * event (compare gen_bx_excret_final_code()).
6620          */
6621         env->regs[15] = dest & ~1;
6622         env->thumb = dest & 1;
6623         HELPER(exception_internal)(env, EXCP_EXCEPTION_EXIT);
6624         /* notreached */
6625     }
6626
6627     /* translate.c should have made BXNS UNDEF unless we're secure */
6628     assert(env->v7m.secure);
6629
6630     switch_v7m_security_state(env, dest & 1);
6631     env->thumb = 1;
6632     env->regs[15] = dest & ~1;
6633 }
6634
6635 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6636 {
6637     /* Handle v7M BLXNS:
6638      *  - bit 0 of the destination address is the target security state
6639      */
6640
6641     /* At this point regs[15] is the address just after the BLXNS */
6642     uint32_t nextinst = env->regs[15] | 1;
6643     uint32_t sp = env->regs[13] - 8;
6644     uint32_t saved_psr;
6645
6646     /* translate.c will have made BLXNS UNDEF unless we're secure */
6647     assert(env->v7m.secure);
6648
6649     if (dest & 1) {
6650         /* target is Secure, so this is just a normal BLX,
6651          * except that the low bit doesn't indicate Thumb/not.
6652          */
6653         env->regs[14] = nextinst;
6654         env->thumb = 1;
6655         env->regs[15] = dest & ~1;
6656         return;
6657     }
6658
6659     /* Target is non-secure: first push a stack frame */
6660     if (!QEMU_IS_ALIGNED(sp, 8)) {
6661         qemu_log_mask(LOG_GUEST_ERROR,
6662                       "BLXNS with misaligned SP is UNPREDICTABLE\n");
6663     }
6664
6665     saved_psr = env->v7m.exception;
6666     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK) {
6667         saved_psr |= XPSR_SFPA;
6668     }
6669
6670     /* Note that these stores can throw exceptions on MPU faults */
6671     cpu_stl_data(env, sp, nextinst);
6672     cpu_stl_data(env, sp + 4, saved_psr);
6673
6674     env->regs[13] = sp;
6675     env->regs[14] = 0xfeffffff;
6676     if (arm_v7m_is_handler_mode(env)) {
6677         /* Write a dummy value to IPSR, to avoid leaking the current secure
6678          * exception number to non-secure code. This is guaranteed not
6679          * to cause write_v7m_exception() to actually change stacks.
6680          */
6681         write_v7m_exception(env, 1);
6682     }
6683     switch_v7m_security_state(env, 0);
6684     env->thumb = 1;
6685     env->regs[15] = dest;
6686 }
6687
6688 static uint32_t *get_v7m_sp_ptr(CPUARMState *env, bool secure, bool threadmode,
6689                                 bool spsel)
6690 {
6691     /* Return a pointer to the location where we currently store the
6692      * stack pointer for the requested security state and thread mode.
6693      * This pointer will become invalid if the CPU state is updated
6694      * such that the stack pointers are switched around (eg changing
6695      * the SPSEL control bit).
6696      * Compare the v8M ARM ARM pseudocode LookUpSP_with_security_mode().
6697      * Unlike that pseudocode, we require the caller to pass us in the
6698      * SPSEL control bit value; this is because we also use this
6699      * function in handling of pushing of the callee-saves registers
6700      * part of the v8M stack frame (pseudocode PushCalleeStack()),
6701      * and in the tailchain codepath the SPSEL bit comes from the exception
6702      * return magic LR value from the previous exception. The pseudocode
6703      * opencodes the stack-selection in PushCalleeStack(), but we prefer
6704      * to make this utility function generic enough to do the job.
6705      */
6706     bool want_psp = threadmode && spsel;
6707
6708     if (secure == env->v7m.secure) {
6709         if (want_psp == v7m_using_psp(env)) {
6710             return &env->regs[13];
6711         } else {
6712             return &env->v7m.other_sp;
6713         }
6714     } else {
6715         if (want_psp) {
6716             return &env->v7m.other_ss_psp;
6717         } else {
6718             return &env->v7m.other_ss_msp;
6719         }
6720     }
6721 }
6722
6723 static bool arm_v7m_load_vector(ARMCPU *cpu, int exc, bool targets_secure,
6724                                 uint32_t *pvec)
6725 {
6726     CPUState *cs = CPU(cpu);
6727     CPUARMState *env = &cpu->env;
6728     MemTxResult result;
6729     uint32_t addr = env->v7m.vecbase[targets_secure] + exc * 4;
6730     uint32_t vector_entry;
6731     MemTxAttrs attrs = {};
6732     ARMMMUIdx mmu_idx;
6733     bool exc_secure;
6734
6735     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targets_secure, true);
6736
6737     /* We don't do a get_phys_addr() here because the rules for vector
6738      * loads are special: they always use the default memory map, and
6739      * the default memory map permits reads from all addresses.
6740      * Since there's no easy way to pass through to pmsav8_mpu_lookup()
6741      * that we want this special case which would always say "yes",
6742      * we just do the SAU lookup here followed by a direct physical load.
6743      */
6744     attrs.secure = targets_secure;
6745     attrs.user = false;
6746
6747     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6748         V8M_SAttributes sattrs = {};
6749
6750         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
6751         if (sattrs.ns) {
6752             attrs.secure = false;
6753         } else if (!targets_secure) {
6754             /* NS access to S memory */
6755             goto load_fail;
6756         }
6757     }
6758
6759     vector_entry = address_space_ldl(arm_addressspace(cs, attrs), addr,
6760                                      attrs, &result);
6761     if (result != MEMTX_OK) {
6762         goto load_fail;
6763     }
6764     *pvec = vector_entry;
6765     return true;
6766
6767 load_fail:
6768     /* All vector table fetch fails are reported as HardFault, with
6769      * HFSR.VECTTBL and .FORCED set. (FORCED is set because
6770      * technically the underlying exception is a MemManage or BusFault
6771      * that is escalated to HardFault.) This is a terminal exception,
6772      * so we will either take the HardFault immediately or else enter
6773      * lockup (the latter case is handled in armv7m_nvic_set_pending_derived()).
6774      */
6775     exc_secure = targets_secure ||
6776         !(cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK);
6777     env->v7m.hfsr |= R_V7M_HFSR_VECTTBL_MASK | R_V7M_HFSR_FORCED_MASK;
6778     armv7m_nvic_set_pending_derived(env->nvic, ARMV7M_EXCP_HARD, exc_secure);
6779     return false;
6780 }
6781
6782 static bool v7m_push_callee_stack(ARMCPU *cpu, uint32_t lr, bool dotailchain,
6783                                   bool ignore_faults)
6784 {
6785     /* For v8M, push the callee-saves register part of the stack frame.
6786      * Compare the v8M pseudocode PushCalleeStack().
6787      * In the tailchaining case this may not be the current stack.
6788      */
6789     CPUARMState *env = &cpu->env;
6790     uint32_t *frame_sp_p;
6791     uint32_t frameptr;
6792     ARMMMUIdx mmu_idx;
6793     bool stacked_ok;
6794
6795     if (dotailchain) {
6796         bool mode = lr & R_V7M_EXCRET_MODE_MASK;
6797         bool priv = !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_NPRIV_MASK) ||
6798             !mode;
6799
6800         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, M_REG_S, priv);
6801         frame_sp_p = get_v7m_sp_ptr(env, M_REG_S, mode,
6802                                     lr & R_V7M_EXCRET_SPSEL_MASK);
6803     } else {
6804         mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
6805         frame_sp_p = &env->regs[13];
6806     }
6807
6808     frameptr = *frame_sp_p - 0x28;
6809
6810     /* Write as much of the stack frame as we can. A write failure may
6811      * cause us to pend a derived exception.
6812      */
6813     stacked_ok =
6814         v7m_stack_write(cpu, frameptr, 0xfefa125b, mmu_idx, ignore_faults) &&
6815         v7m_stack_write(cpu, frameptr + 0x8, env->regs[4], mmu_idx,
6816                         ignore_faults) &&
6817         v7m_stack_write(cpu, frameptr + 0xc, env->regs[5], mmu_idx,
6818                         ignore_faults) &&
6819         v7m_stack_write(cpu, frameptr + 0x10, env->regs[6], mmu_idx,
6820                         ignore_faults) &&
6821         v7m_stack_write(cpu, frameptr + 0x14, env->regs[7], mmu_idx,
6822                         ignore_faults) &&
6823         v7m_stack_write(cpu, frameptr + 0x18, env->regs[8], mmu_idx,
6824                         ignore_faults) &&
6825         v7m_stack_write(cpu, frameptr + 0x1c, env->regs[9], mmu_idx,
6826                         ignore_faults) &&
6827         v7m_stack_write(cpu, frameptr + 0x20, env->regs[10], mmu_idx,
6828                         ignore_faults) &&
6829         v7m_stack_write(cpu, frameptr + 0x24, env->regs[11], mmu_idx,
6830                         ignore_faults);
6831
6832     /* Update SP regardless of whether any of the stack accesses failed.
6833      * When we implement v8M stack limit checking then this attempt to
6834      * update SP might also fail and result in a derived exception.
6835      */
6836     *frame_sp_p = frameptr;
6837
6838     return !stacked_ok;
6839 }
6840
6841 static void v7m_exception_taken(ARMCPU *cpu, uint32_t lr, bool dotailchain,
6842                                 bool ignore_stackfaults)
6843 {
6844     /* Do the "take the exception" parts of exception entry,
6845      * but not the pushing of state to the stack. This is
6846      * similar to the pseudocode ExceptionTaken() function.
6847      */
6848     CPUARMState *env = &cpu->env;
6849     uint32_t addr;
6850     bool targets_secure;
6851     int exc;
6852     bool push_failed = false;
6853
6854     armv7m_nvic_get_pending_irq_info(env->nvic, &exc, &targets_secure);
6855     qemu_log_mask(CPU_LOG_INT, "...taking pending %s exception %d\n",
6856                   targets_secure ? "secure" : "nonsecure", exc);
6857
6858     if (arm_feature(env, ARM_FEATURE_V8)) {
6859         if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
6860             (lr & R_V7M_EXCRET_S_MASK)) {
6861             /* The background code (the owner of the registers in the
6862              * exception frame) is Secure. This means it may either already
6863              * have or now needs to push callee-saves registers.
6864              */
6865             if (targets_secure) {
6866                 if (dotailchain && !(lr & R_V7M_EXCRET_ES_MASK)) {
6867                     /* We took an exception from Secure to NonSecure
6868                      * (which means the callee-saved registers got stacked)
6869                      * and are now tailchaining to a Secure exception.
6870                      * Clear DCRS so eventual return from this Secure
6871                      * exception unstacks the callee-saved registers.
6872                      */
6873                     lr &= ~R_V7M_EXCRET_DCRS_MASK;
6874                 }
6875             } else {
6876                 /* We're going to a non-secure exception; push the
6877                  * callee-saves registers to the stack now, if they're
6878                  * not already saved.
6879                  */
6880                 if (lr & R_V7M_EXCRET_DCRS_MASK &&
6881                     !(dotailchain && (lr & R_V7M_EXCRET_ES_MASK))) {
6882                     push_failed = v7m_push_callee_stack(cpu, lr, dotailchain,
6883                                                         ignore_stackfaults);
6884                 }
6885                 lr |= R_V7M_EXCRET_DCRS_MASK;
6886             }
6887         }
6888
6889         lr &= ~R_V7M_EXCRET_ES_MASK;
6890         if (targets_secure || !arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6891             lr |= R_V7M_EXCRET_ES_MASK;
6892         }
6893         lr &= ~R_V7M_EXCRET_SPSEL_MASK;
6894         if (env->v7m.control[targets_secure] & R_V7M_CONTROL_SPSEL_MASK) {
6895             lr |= R_V7M_EXCRET_SPSEL_MASK;
6896         }
6897
6898         /* Clear registers if necessary to prevent non-secure exception
6899          * code being able to see register values from secure code.
6900          * Where register values become architecturally UNKNOWN we leave
6901          * them with their previous values.
6902          */
6903         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6904             if (!targets_secure) {
6905                 /* Always clear the caller-saved registers (they have been
6906                  * pushed to the stack earlier in v7m_push_stack()).
6907                  * Clear callee-saved registers if the background code is
6908                  * Secure (in which case these regs were saved in
6909                  * v7m_push_callee_stack()).
6910                  */
6911                 int i;
6912
6913                 for (i = 0; i < 13; i++) {
6914                     /* r4..r11 are callee-saves, zero only if EXCRET.S == 1 */
6915                     if (i < 4 || i > 11 || (lr & R_V7M_EXCRET_S_MASK)) {
6916                         env->regs[i] = 0;
6917                     }
6918                 }
6919                 /* Clear EAPSR */
6920                 xpsr_write(env, 0, XPSR_NZCV | XPSR_Q | XPSR_GE | XPSR_IT);
6921             }
6922         }
6923     }
6924
6925     if (push_failed && !ignore_stackfaults) {
6926         /* Derived exception on callee-saves register stacking:
6927          * we might now want to take a different exception which
6928          * targets a different security state, so try again from the top.
6929          */
6930         qemu_log_mask(CPU_LOG_INT,
6931                       "...derived exception on callee-saves register stacking");
6932         v7m_exception_taken(cpu, lr, true, true);
6933         return;
6934     }
6935
6936     if (!arm_v7m_load_vector(cpu, exc, targets_secure, &addr)) {
6937         /* Vector load failed: derived exception */
6938         qemu_log_mask(CPU_LOG_INT, "...derived exception on vector table load");
6939         v7m_exception_taken(cpu, lr, true, true);
6940         return;
6941     }
6942
6943     /* Now we've done everything that might cause a derived exception
6944      * we can go ahead and activate whichever exception we're going to
6945      * take (which might now be the derived exception).
6946      */
6947     armv7m_nvic_acknowledge_irq(env->nvic);
6948
6949     /* Switch to target security state -- must do this before writing SPSEL */
6950     switch_v7m_security_state(env, targets_secure);
6951     write_v7m_control_spsel(env, 0);
6952     arm_clear_exclusive(env);
6953     /* Clear IT bits */
6954     env->condexec_bits = 0;
6955     env->regs[14] = lr;
6956     env->regs[15] = addr & 0xfffffffe;
6957     env->thumb = addr & 1;
6958 }
6959
6960 static bool v7m_push_stack(ARMCPU *cpu)
6961 {
6962     /* Do the "set up stack frame" part of exception entry,
6963      * similar to pseudocode PushStack().
6964      * Return true if we generate a derived exception (and so
6965      * should ignore further stack faults trying to process
6966      * that derived exception.)
6967      */
6968     bool stacked_ok;
6969     CPUARMState *env = &cpu->env;
6970     uint32_t xpsr = xpsr_read(env);
6971     uint32_t frameptr = env->regs[13];
6972     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
6973
6974     /* Align stack pointer if the guest wants that */
6975     if ((frameptr & 4) &&
6976         (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKALIGN_MASK)) {
6977         frameptr -= 4;
6978         xpsr |= XPSR_SPREALIGN;
6979     }
6980
6981     frameptr -= 0x20;
6982
6983     /* Write as much of the stack frame as we can. If we fail a stack
6984      * write this will result in a derived exception being pended
6985      * (which may be taken in preference to the one we started with
6986      * if it has higher priority).
6987      */
6988     stacked_ok =
6989         v7m_stack_write(cpu, frameptr, env->regs[0], mmu_idx, false) &&
6990         v7m_stack_write(cpu, frameptr + 4, env->regs[1], mmu_idx, false) &&
6991         v7m_stack_write(cpu, frameptr + 8, env->regs[2], mmu_idx, false) &&
6992         v7m_stack_write(cpu, frameptr + 12, env->regs[3], mmu_idx, false) &&
6993         v7m_stack_write(cpu, frameptr + 16, env->regs[12], mmu_idx, false) &&
6994         v7m_stack_write(cpu, frameptr + 20, env->regs[14], mmu_idx, false) &&
6995         v7m_stack_write(cpu, frameptr + 24, env->regs[15], mmu_idx, false) &&
6996         v7m_stack_write(cpu, frameptr + 28, xpsr, mmu_idx, false);
6997
6998     /* Update SP regardless of whether any of the stack accesses failed.
6999      * When we implement v8M stack limit checking then this attempt to
7000      * update SP might also fail and result in a derived exception.
7001      */
7002     env->regs[13] = frameptr;
7003
7004     return !stacked_ok;
7005 }
7006
7007 static void do_v7m_exception_exit(ARMCPU *cpu)
7008 {
7009     CPUARMState *env = &cpu->env;
7010     uint32_t excret;
7011     uint32_t xpsr;
7012     bool ufault = false;
7013     bool sfault = false;
7014     bool return_to_sp_process;
7015     bool return_to_handler;
7016     bool rettobase = false;
7017     bool exc_secure = false;
7018     bool return_to_secure;
7019
7020     /* If we're not in Handler mode then jumps to magic exception-exit
7021      * addresses don't have magic behaviour. However for the v8M
7022      * security extensions the magic secure-function-return has to
7023      * work in thread mode too, so to avoid doing an extra check in
7024      * the generated code we allow exception-exit magic to also cause the
7025      * internal exception and bring us here in thread mode. Correct code
7026      * will never try to do this (the following insn fetch will always
7027      * fault) so we the overhead of having taken an unnecessary exception
7028      * doesn't matter.
7029      */
7030     if (!arm_v7m_is_handler_mode(env)) {
7031         return;
7032     }
7033
7034     /* In the spec pseudocode ExceptionReturn() is called directly
7035      * from BXWritePC() and gets the full target PC value including
7036      * bit zero. In QEMU's implementation we treat it as a normal
7037      * jump-to-register (which is then caught later on), and so split
7038      * the target value up between env->regs[15] and env->thumb in
7039      * gen_bx(). Reconstitute it.
7040      */
7041     excret = env->regs[15];
7042     if (env->thumb) {
7043         excret |= 1;
7044     }
7045
7046     qemu_log_mask(CPU_LOG_INT, "Exception return: magic PC %" PRIx32
7047                   " previous exception %d\n",
7048                   excret, env->v7m.exception);
7049
7050     if ((excret & R_V7M_EXCRET_RES1_MASK) != R_V7M_EXCRET_RES1_MASK) {
7051         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero high bits in exception "
7052                       "exit PC value 0x%" PRIx32 " are UNPREDICTABLE\n",
7053                       excret);
7054     }
7055
7056     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7057         /* EXC_RETURN.ES validation check (R_SMFL). We must do this before
7058          * we pick which FAULTMASK to clear.
7059          */
7060         if (!env->v7m.secure &&
7061             ((excret & R_V7M_EXCRET_ES_MASK) ||
7062              !(excret & R_V7M_EXCRET_DCRS_MASK))) {
7063             sfault = 1;
7064             /* For all other purposes, treat ES as 0 (R_HXSR) */
7065             excret &= ~R_V7M_EXCRET_ES_MASK;
7066         }
7067         exc_secure = excret & R_V7M_EXCRET_ES_MASK;
7068     }
7069
7070     if (env->v7m.exception != ARMV7M_EXCP_NMI) {
7071         /* Auto-clear FAULTMASK on return from other than NMI.
7072          * If the security extension is implemented then this only
7073          * happens if the raw execution priority is >= 0; the
7074          * value of the ES bit in the exception return value indicates
7075          * which security state's faultmask to clear. (v8M ARM ARM R_KBNF.)
7076          */
7077         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7078             if (armv7m_nvic_raw_execution_priority(env->nvic) >= 0) {
7079                 env->v7m.faultmask[exc_secure] = 0;
7080             }
7081         } else {
7082             env->v7m.faultmask[M_REG_NS] = 0;
7083         }
7084     }
7085
7086     switch (armv7m_nvic_complete_irq(env->nvic, env->v7m.exception,
7087                                      exc_secure)) {
7088     case -1:
7089         /* attempt to exit an exception that isn't active */
7090         ufault = true;
7091         break;
7092     case 0:
7093         /* still an irq active now */
7094         break;
7095     case 1:
7096         /* we returned to base exception level, no nesting.
7097          * (In the pseudocode this is written using "NestedActivation != 1"
7098          * where we have 'rettobase == false'.)
7099          */
7100         rettobase = true;
7101         break;
7102     default:
7103         g_assert_not_reached();
7104     }
7105
7106     return_to_handler = !(excret & R_V7M_EXCRET_MODE_MASK);
7107     return_to_sp_process = excret & R_V7M_EXCRET_SPSEL_MASK;
7108     return_to_secure = arm_feature(env, ARM_FEATURE_M_SECURITY) &&
7109         (excret & R_V7M_EXCRET_S_MASK);
7110
7111     if (arm_feature(env, ARM_FEATURE_V8)) {
7112         if (!arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7113             /* UNPREDICTABLE if S == 1 or DCRS == 0 or ES == 1 (R_XLCP);
7114              * we choose to take the UsageFault.
7115              */
7116             if ((excret & R_V7M_EXCRET_S_MASK) ||
7117                 (excret & R_V7M_EXCRET_ES_MASK) ||
7118                 !(excret & R_V7M_EXCRET_DCRS_MASK)) {
7119                 ufault = true;
7120             }
7121         }
7122         if (excret & R_V7M_EXCRET_RES0_MASK) {
7123             ufault = true;
7124         }
7125     } else {
7126         /* For v7M we only recognize certain combinations of the low bits */
7127         switch (excret & 0xf) {
7128         case 1: /* Return to Handler */
7129             break;
7130         case 13: /* Return to Thread using Process stack */
7131         case 9: /* Return to Thread using Main stack */
7132             /* We only need to check NONBASETHRDENA for v7M, because in
7133              * v8M this bit does not exist (it is RES1).
7134              */
7135             if (!rettobase &&
7136                 !(env->v7m.ccr[env->v7m.secure] &
7137                   R_V7M_CCR_NONBASETHRDENA_MASK)) {
7138                 ufault = true;
7139             }
7140             break;
7141         default:
7142             ufault = true;
7143         }
7144     }
7145
7146     /*
7147      * Set CONTROL.SPSEL from excret.SPSEL. Since we're still in
7148      * Handler mode (and will be until we write the new XPSR.Interrupt
7149      * field) this does not switch around the current stack pointer.
7150      * We must do this before we do any kind of tailchaining, including
7151      * for the derived exceptions on integrity check failures, or we will
7152      * give the guest an incorrect EXCRET.SPSEL value on exception entry.
7153      */
7154     write_v7m_control_spsel_for_secstate(env, return_to_sp_process, exc_secure);
7155
7156     if (sfault) {
7157         env->v7m.sfsr |= R_V7M_SFSR_INVER_MASK;
7158         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7159         qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7160                       "stackframe: failed EXC_RETURN.ES validity check\n");
7161         v7m_exception_taken(cpu, excret, true, false);
7162         return;
7163     }
7164
7165     if (ufault) {
7166         /* Bad exception return: instead of popping the exception
7167          * stack, directly take a usage fault on the current stack.
7168          */
7169         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7170         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7171         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7172                       "stackframe: failed exception return integrity check\n");
7173         v7m_exception_taken(cpu, excret, true, false);
7174         return;
7175     }
7176
7177     /*
7178      * Tailchaining: if there is currently a pending exception that
7179      * is high enough priority to preempt execution at the level we're
7180      * about to return to, then just directly take that exception now,
7181      * avoiding an unstack-and-then-stack. Note that now we have
7182      * deactivated the previous exception by calling armv7m_nvic_complete_irq()
7183      * our current execution priority is already the execution priority we are
7184      * returning to -- none of the state we would unstack or set based on
7185      * the EXCRET value affects it.
7186      */
7187     if (armv7m_nvic_can_take_pending_exception(env->nvic)) {
7188         qemu_log_mask(CPU_LOG_INT, "...tailchaining to pending exception\n");
7189         v7m_exception_taken(cpu, excret, true, false);
7190         return;
7191     }
7192
7193     switch_v7m_security_state(env, return_to_secure);
7194
7195     {
7196         /* The stack pointer we should be reading the exception frame from
7197          * depends on bits in the magic exception return type value (and
7198          * for v8M isn't necessarily the stack pointer we will eventually
7199          * end up resuming execution with). Get a pointer to the location
7200          * in the CPU state struct where the SP we need is currently being
7201          * stored; we will use and modify it in place.
7202          * We use this limited C variable scope so we don't accidentally
7203          * use 'frame_sp_p' after we do something that makes it invalid.
7204          */
7205         uint32_t *frame_sp_p = get_v7m_sp_ptr(env,
7206                                               return_to_secure,
7207                                               !return_to_handler,
7208                                               return_to_sp_process);
7209         uint32_t frameptr = *frame_sp_p;
7210         bool pop_ok = true;
7211         ARMMMUIdx mmu_idx;
7212         bool return_to_priv = return_to_handler ||
7213             !(env->v7m.control[return_to_secure] & R_V7M_CONTROL_NPRIV_MASK);
7214
7215         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, return_to_secure,
7216                                                         return_to_priv);
7217
7218         if (!QEMU_IS_ALIGNED(frameptr, 8) &&
7219             arm_feature(env, ARM_FEATURE_V8)) {
7220             qemu_log_mask(LOG_GUEST_ERROR,
7221                           "M profile exception return with non-8-aligned SP "
7222                           "for destination state is UNPREDICTABLE\n");
7223         }
7224
7225         /* Do we need to pop callee-saved registers? */
7226         if (return_to_secure &&
7227             ((excret & R_V7M_EXCRET_ES_MASK) == 0 ||
7228              (excret & R_V7M_EXCRET_DCRS_MASK) == 0)) {
7229             uint32_t expected_sig = 0xfefa125b;
7230             uint32_t actual_sig;
7231
7232             pop_ok = v7m_stack_read(cpu, &actual_sig, frameptr, mmu_idx);
7233
7234             if (pop_ok && expected_sig != actual_sig) {
7235                 /* Take a SecureFault on the current stack */
7236                 env->v7m.sfsr |= R_V7M_SFSR_INVIS_MASK;
7237                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7238                 qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7239                               "stackframe: failed exception return integrity "
7240                               "signature check\n");
7241                 v7m_exception_taken(cpu, excret, true, false);
7242                 return;
7243             }
7244
7245             pop_ok = pop_ok &&
7246                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
7247                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
7248                 v7m_stack_read(cpu, &env->regs[5], frameptr + 0xc, mmu_idx) &&
7249                 v7m_stack_read(cpu, &env->regs[6], frameptr + 0x10, mmu_idx) &&
7250                 v7m_stack_read(cpu, &env->regs[7], frameptr + 0x14, mmu_idx) &&
7251                 v7m_stack_read(cpu, &env->regs[8], frameptr + 0x18, mmu_idx) &&
7252                 v7m_stack_read(cpu, &env->regs[9], frameptr + 0x1c, mmu_idx) &&
7253                 v7m_stack_read(cpu, &env->regs[10], frameptr + 0x20, mmu_idx) &&
7254                 v7m_stack_read(cpu, &env->regs[11], frameptr + 0x24, mmu_idx);
7255
7256             frameptr += 0x28;
7257         }
7258
7259         /* Pop registers */
7260         pop_ok = pop_ok &&
7261             v7m_stack_read(cpu, &env->regs[0], frameptr, mmu_idx) &&
7262             v7m_stack_read(cpu, &env->regs[1], frameptr + 0x4, mmu_idx) &&
7263             v7m_stack_read(cpu, &env->regs[2], frameptr + 0x8, mmu_idx) &&
7264             v7m_stack_read(cpu, &env->regs[3], frameptr + 0xc, mmu_idx) &&
7265             v7m_stack_read(cpu, &env->regs[12], frameptr + 0x10, mmu_idx) &&
7266             v7m_stack_read(cpu, &env->regs[14], frameptr + 0x14, mmu_idx) &&
7267             v7m_stack_read(cpu, &env->regs[15], frameptr + 0x18, mmu_idx) &&
7268             v7m_stack_read(cpu, &xpsr, frameptr + 0x1c, mmu_idx);
7269
7270         if (!pop_ok) {
7271             /* v7m_stack_read() pended a fault, so take it (as a tail
7272              * chained exception on the same stack frame)
7273              */
7274             qemu_log_mask(CPU_LOG_INT, "...derived exception on unstacking\n");
7275             v7m_exception_taken(cpu, excret, true, false);
7276             return;
7277         }
7278
7279         /* Returning from an exception with a PC with bit 0 set is defined
7280          * behaviour on v8M (bit 0 is ignored), but for v7M it was specified
7281          * to be UNPREDICTABLE. In practice actual v7M hardware seems to ignore
7282          * the lsbit, and there are several RTOSes out there which incorrectly
7283          * assume the r15 in the stack frame should be a Thumb-style "lsbit
7284          * indicates ARM/Thumb" value, so ignore the bit on v7M as well, but
7285          * complain about the badly behaved guest.
7286          */
7287         if (env->regs[15] & 1) {
7288             env->regs[15] &= ~1U;
7289             if (!arm_feature(env, ARM_FEATURE_V8)) {
7290                 qemu_log_mask(LOG_GUEST_ERROR,
7291                               "M profile return from interrupt with misaligned "
7292                               "PC is UNPREDICTABLE on v7M\n");
7293             }
7294         }
7295
7296         if (arm_feature(env, ARM_FEATURE_V8)) {
7297             /* For v8M we have to check whether the xPSR exception field
7298              * matches the EXCRET value for return to handler/thread
7299              * before we commit to changing the SP and xPSR.
7300              */
7301             bool will_be_handler = (xpsr & XPSR_EXCP) != 0;
7302             if (return_to_handler != will_be_handler) {
7303                 /* Take an INVPC UsageFault on the current stack.
7304                  * By this point we will have switched to the security state
7305                  * for the background state, so this UsageFault will target
7306                  * that state.
7307                  */
7308                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7309                                         env->v7m.secure);
7310                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7311                 qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7312                               "stackframe: failed exception return integrity "
7313                               "check\n");
7314                 v7m_exception_taken(cpu, excret, true, false);
7315                 return;
7316             }
7317         }
7318
7319         /* Commit to consuming the stack frame */
7320         frameptr += 0x20;
7321         /* Undo stack alignment (the SPREALIGN bit indicates that the original
7322          * pre-exception SP was not 8-aligned and we added a padding word to
7323          * align it, so we undo this by ORing in the bit that increases it
7324          * from the current 8-aligned value to the 8-unaligned value. (Adding 4
7325          * would work too but a logical OR is how the pseudocode specifies it.)
7326          */
7327         if (xpsr & XPSR_SPREALIGN) {
7328             frameptr |= 4;
7329         }
7330         *frame_sp_p = frameptr;
7331     }
7332     /* This xpsr_write() will invalidate frame_sp_p as it may switch stack */
7333     xpsr_write(env, xpsr, ~XPSR_SPREALIGN);
7334
7335     /* The restored xPSR exception field will be zero if we're
7336      * resuming in Thread mode. If that doesn't match what the
7337      * exception return excret specified then this is a UsageFault.
7338      * v7M requires we make this check here; v8M did it earlier.
7339      */
7340     if (return_to_handler != arm_v7m_is_handler_mode(env)) {
7341         /* Take an INVPC UsageFault by pushing the stack again;
7342          * we know we're v7M so this is never a Secure UsageFault.
7343          */
7344         bool ignore_stackfaults;
7345
7346         assert(!arm_feature(env, ARM_FEATURE_V8));
7347         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, false);
7348         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7349         ignore_stackfaults = v7m_push_stack(cpu);
7350         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on new stackframe: "
7351                       "failed exception return integrity check\n");
7352         v7m_exception_taken(cpu, excret, false, ignore_stackfaults);
7353         return;
7354     }
7355
7356     /* Otherwise, we have a successful exception exit. */
7357     arm_clear_exclusive(env);
7358     qemu_log_mask(CPU_LOG_INT, "...successful exception return\n");
7359 }
7360
7361 static bool do_v7m_function_return(ARMCPU *cpu)
7362 {
7363     /* v8M security extensions magic function return.
7364      * We may either:
7365      *  (1) throw an exception (longjump)
7366      *  (2) return true if we successfully handled the function return
7367      *  (3) return false if we failed a consistency check and have
7368      *      pended a UsageFault that needs to be taken now
7369      *
7370      * At this point the magic return value is split between env->regs[15]
7371      * and env->thumb. We don't bother to reconstitute it because we don't
7372      * need it (all values are handled the same way).
7373      */
7374     CPUARMState *env = &cpu->env;
7375     uint32_t newpc, newpsr, newpsr_exc;
7376
7377     qemu_log_mask(CPU_LOG_INT, "...really v7M secure function return\n");
7378
7379     {
7380         bool threadmode, spsel;
7381         TCGMemOpIdx oi;
7382         ARMMMUIdx mmu_idx;
7383         uint32_t *frame_sp_p;
7384         uint32_t frameptr;
7385
7386         /* Pull the return address and IPSR from the Secure stack */
7387         threadmode = !arm_v7m_is_handler_mode(env);
7388         spsel = env->v7m.control[M_REG_S] & R_V7M_CONTROL_SPSEL_MASK;
7389
7390         frame_sp_p = get_v7m_sp_ptr(env, true, threadmode, spsel);
7391         frameptr = *frame_sp_p;
7392
7393         /* These loads may throw an exception (for MPU faults). We want to
7394          * do them as secure, so work out what MMU index that is.
7395          */
7396         mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7397         oi = make_memop_idx(MO_LE, arm_to_core_mmu_idx(mmu_idx));
7398         newpc = helper_le_ldul_mmu(env, frameptr, oi, 0);
7399         newpsr = helper_le_ldul_mmu(env, frameptr + 4, oi, 0);
7400
7401         /* Consistency checks on new IPSR */
7402         newpsr_exc = newpsr & XPSR_EXCP;
7403         if (!((env->v7m.exception == 0 && newpsr_exc == 0) ||
7404               (env->v7m.exception == 1 && newpsr_exc != 0))) {
7405             /* Pend the fault and tell our caller to take it */
7406             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7407             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7408                                     env->v7m.secure);
7409             qemu_log_mask(CPU_LOG_INT,
7410                           "...taking INVPC UsageFault: "
7411                           "IPSR consistency check failed\n");
7412             return false;
7413         }
7414
7415         *frame_sp_p = frameptr + 8;
7416     }
7417
7418     /* This invalidates frame_sp_p */
7419     switch_v7m_security_state(env, true);
7420     env->v7m.exception = newpsr_exc;
7421     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
7422     if (newpsr & XPSR_SFPA) {
7423         env->v7m.control[M_REG_S] |= R_V7M_CONTROL_SFPA_MASK;
7424     }
7425     xpsr_write(env, 0, XPSR_IT);
7426     env->thumb = newpc & 1;
7427     env->regs[15] = newpc & ~1;
7428
7429     qemu_log_mask(CPU_LOG_INT, "...function return successful\n");
7430     return true;
7431 }
7432
7433 static void arm_log_exception(int idx)
7434 {
7435     if (qemu_loglevel_mask(CPU_LOG_INT)) {
7436         const char *exc = NULL;
7437         static const char * const excnames[] = {
7438             [EXCP_UDEF] = "Undefined Instruction",
7439             [EXCP_SWI] = "SVC",
7440             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
7441             [EXCP_DATA_ABORT] = "Data Abort",
7442             [EXCP_IRQ] = "IRQ",
7443             [EXCP_FIQ] = "FIQ",
7444             [EXCP_BKPT] = "Breakpoint",
7445             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
7446             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
7447             [EXCP_HVC] = "Hypervisor Call",
7448             [EXCP_HYP_TRAP] = "Hypervisor Trap",
7449             [EXCP_SMC] = "Secure Monitor Call",
7450             [EXCP_VIRQ] = "Virtual IRQ",
7451             [EXCP_VFIQ] = "Virtual FIQ",
7452             [EXCP_SEMIHOST] = "Semihosting call",
7453             [EXCP_NOCP] = "v7M NOCP UsageFault",
7454             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
7455         };
7456
7457         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
7458             exc = excnames[idx];
7459         }
7460         if (!exc) {
7461             exc = "unknown";
7462         }
7463         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
7464     }
7465 }
7466
7467 static bool v7m_read_half_insn(ARMCPU *cpu, ARMMMUIdx mmu_idx,
7468                                uint32_t addr, uint16_t *insn)
7469 {
7470     /* Load a 16-bit portion of a v7M instruction, returning true on success,
7471      * or false on failure (in which case we will have pended the appropriate
7472      * exception).
7473      * We need to do the instruction fetch's MPU and SAU checks
7474      * like this because there is no MMU index that would allow
7475      * doing the load with a single function call. Instead we must
7476      * first check that the security attributes permit the load
7477      * and that they don't mismatch on the two halves of the instruction,
7478      * and then we do the load as a secure load (ie using the security
7479      * attributes of the address, not the CPU, as architecturally required).
7480      */
7481     CPUState *cs = CPU(cpu);
7482     CPUARMState *env = &cpu->env;
7483     V8M_SAttributes sattrs = {};
7484     MemTxAttrs attrs = {};
7485     ARMMMUFaultInfo fi = {};
7486     MemTxResult txres;
7487     target_ulong page_size;
7488     hwaddr physaddr;
7489     int prot;
7490
7491     v8m_security_lookup(env, addr, MMU_INST_FETCH, mmu_idx, &sattrs);
7492     if (!sattrs.nsc || sattrs.ns) {
7493         /* This must be the second half of the insn, and it straddles a
7494          * region boundary with the second half not being S&NSC.
7495          */
7496         env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7497         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7498         qemu_log_mask(CPU_LOG_INT,
7499                       "...really SecureFault with SFSR.INVEP\n");
7500         return false;
7501     }
7502     if (get_phys_addr(env, addr, MMU_INST_FETCH, mmu_idx,
7503                       &physaddr, &attrs, &prot, &page_size, &fi, NULL)) {
7504         /* the MPU lookup failed */
7505         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
7506         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM, env->v7m.secure);
7507         qemu_log_mask(CPU_LOG_INT, "...really MemManage with CFSR.IACCVIOL\n");
7508         return false;
7509     }
7510     *insn = address_space_lduw_le(arm_addressspace(cs, attrs), physaddr,
7511                                  attrs, &txres);
7512     if (txres != MEMTX_OK) {
7513         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
7514         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
7515         qemu_log_mask(CPU_LOG_INT, "...really BusFault with CFSR.IBUSERR\n");
7516         return false;
7517     }
7518     return true;
7519 }
7520
7521 static bool v7m_handle_execute_nsc(ARMCPU *cpu)
7522 {
7523     /* Check whether this attempt to execute code in a Secure & NS-Callable
7524      * memory region is for an SG instruction; if so, then emulate the
7525      * effect of the SG instruction and return true. Otherwise pend
7526      * the correct kind of exception and return false.
7527      */
7528     CPUARMState *env = &cpu->env;
7529     ARMMMUIdx mmu_idx;
7530     uint16_t insn;
7531
7532     /* We should never get here unless get_phys_addr_pmsav8() caused
7533      * an exception for NS executing in S&NSC memory.
7534      */
7535     assert(!env->v7m.secure);
7536     assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
7537
7538     /* We want to do the MPU lookup as secure; work out what mmu_idx that is */
7539     mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7540
7541     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15], &insn)) {
7542         return false;
7543     }
7544
7545     if (!env->thumb) {
7546         goto gen_invep;
7547     }
7548
7549     if (insn != 0xe97f) {
7550         /* Not an SG instruction first half (we choose the IMPDEF
7551          * early-SG-check option).
7552          */
7553         goto gen_invep;
7554     }
7555
7556     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15] + 2, &insn)) {
7557         return false;
7558     }
7559
7560     if (insn != 0xe97f) {
7561         /* Not an SG instruction second half (yes, both halves of the SG
7562          * insn have the same hex value)
7563          */
7564         goto gen_invep;
7565     }
7566
7567     /* OK, we have confirmed that we really have an SG instruction.
7568      * We know we're NS in S memory so don't need to repeat those checks.
7569      */
7570     qemu_log_mask(CPU_LOG_INT, "...really an SG instruction at 0x%08" PRIx32
7571                   ", executing it\n", env->regs[15]);
7572     env->regs[14] &= ~1;
7573     switch_v7m_security_state(env, true);
7574     xpsr_write(env, 0, XPSR_IT);
7575     env->regs[15] += 4;
7576     return true;
7577
7578 gen_invep:
7579     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7580     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7581     qemu_log_mask(CPU_LOG_INT,
7582                   "...really SecureFault with SFSR.INVEP\n");
7583     return false;
7584 }
7585
7586 void arm_v7m_cpu_do_interrupt(CPUState *cs)
7587 {
7588     ARMCPU *cpu = ARM_CPU(cs);
7589     CPUARMState *env = &cpu->env;
7590     uint32_t lr;
7591     bool ignore_stackfaults;
7592
7593     arm_log_exception(cs->exception_index);
7594
7595     /* For exceptions we just mark as pending on the NVIC, and let that
7596        handle it.  */
7597     switch (cs->exception_index) {
7598     case EXCP_UDEF:
7599         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7600         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;
7601         break;
7602     case EXCP_NOCP:
7603         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7604         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;
7605         break;
7606     case EXCP_INVSTATE:
7607         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7608         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;
7609         break;
7610     case EXCP_SWI:
7611         /* The PC already points to the next instruction.  */
7612         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC, env->v7m.secure);
7613         break;
7614     case EXCP_PREFETCH_ABORT:
7615     case EXCP_DATA_ABORT:
7616         /* Note that for M profile we don't have a guest facing FSR, but
7617          * the env->exception.fsr will be populated by the code that
7618          * raises the fault, in the A profile short-descriptor format.
7619          */
7620         switch (env->exception.fsr & 0xf) {
7621         case M_FAKE_FSR_NSC_EXEC:
7622             /* Exception generated when we try to execute code at an address
7623              * which is marked as Secure & Non-Secure Callable and the CPU
7624              * is in the Non-Secure state. The only instruction which can
7625              * be executed like this is SG (and that only if both halves of
7626              * the SG instruction have the same security attributes.)
7627              * Everything else must generate an INVEP SecureFault, so we
7628              * emulate the SG instruction here.
7629              */
7630             if (v7m_handle_execute_nsc(cpu)) {
7631                 return;
7632             }
7633             break;
7634         case M_FAKE_FSR_SFAULT:
7635             /* Various flavours of SecureFault for attempts to execute or
7636              * access data in the wrong security state.
7637              */
7638             switch (cs->exception_index) {
7639             case EXCP_PREFETCH_ABORT:
7640                 if (env->v7m.secure) {
7641                     env->v7m.sfsr |= R_V7M_SFSR_INVTRAN_MASK;
7642                     qemu_log_mask(CPU_LOG_INT,
7643                                   "...really SecureFault with SFSR.INVTRAN\n");
7644                 } else {
7645                     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7646                     qemu_log_mask(CPU_LOG_INT,
7647                                   "...really SecureFault with SFSR.INVEP\n");
7648                 }
7649                 break;
7650             case EXCP_DATA_ABORT:
7651                 /* This must be an NS access to S memory */
7652                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
7653                 qemu_log_mask(CPU_LOG_INT,
7654                               "...really SecureFault with SFSR.AUVIOL\n");
7655                 break;
7656             }
7657             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7658             break;
7659         case 0x8: /* External Abort */
7660             switch (cs->exception_index) {
7661             case EXCP_PREFETCH_ABORT:
7662                 env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
7663                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");
7664                 break;
7665             case EXCP_DATA_ABORT:
7666                 env->v7m.cfsr[M_REG_NS] |=
7667                     (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);
7668                 env->v7m.bfar = env->exception.vaddress;
7669                 qemu_log_mask(CPU_LOG_INT,
7670                               "...with CFSR.PRECISERR and BFAR 0x%x\n",
7671                               env->v7m.bfar);
7672                 break;
7673             }
7674             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
7675             break;
7676         default:
7677             /* All other FSR values are either MPU faults or "can't happen
7678              * for M profile" cases.
7679              */
7680             switch (cs->exception_index) {
7681             case EXCP_PREFETCH_ABORT:
7682                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
7683                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");
7684                 break;
7685             case EXCP_DATA_ABORT:
7686                 env->v7m.cfsr[env->v7m.secure] |=
7687                     (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);
7688                 env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;
7689                 qemu_log_mask(CPU_LOG_INT,
7690                               "...with CFSR.DACCVIOL and MMFAR 0x%x\n",
7691                               env->v7m.mmfar[env->v7m.secure]);
7692                 break;
7693             }
7694             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM,
7695                                     env->v7m.secure);
7696             break;
7697         }
7698         break;
7699     case EXCP_BKPT:
7700         if (semihosting_enabled()) {
7701             int nr;
7702             nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;
7703             if (nr == 0xab) {
7704                 env->regs[15] += 2;
7705                 qemu_log_mask(CPU_LOG_INT,
7706                               "...handling as semihosting call 0x%x\n",
7707                               env->regs[0]);
7708                 env->regs[0] = do_arm_semihosting(env);
7709                 return;
7710             }
7711         }
7712         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG, false);
7713         break;
7714     case EXCP_IRQ:
7715         break;
7716     case EXCP_EXCEPTION_EXIT:
7717         if (env->regs[15] < EXC_RETURN_MIN_MAGIC) {
7718             /* Must be v8M security extension function return */
7719             assert(env->regs[15] >= FNC_RETURN_MIN_MAGIC);
7720             assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
7721             if (do_v7m_function_return(cpu)) {
7722                 return;
7723             }
7724         } else {
7725             do_v7m_exception_exit(cpu);
7726             return;
7727         }
7728         break;
7729     default:
7730         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
7731         return; /* Never happens.  Keep compiler happy.  */
7732     }
7733
7734     if (arm_feature(env, ARM_FEATURE_V8)) {
7735         lr = R_V7M_EXCRET_RES1_MASK |
7736             R_V7M_EXCRET_DCRS_MASK |
7737             R_V7M_EXCRET_FTYPE_MASK;
7738         /* The S bit indicates whether we should return to Secure
7739          * or NonSecure (ie our current state).
7740          * The ES bit indicates whether we're taking this exception
7741          * to Secure or NonSecure (ie our target state). We set it
7742          * later, in v7m_exception_taken().
7743          * The SPSEL bit is also set in v7m_exception_taken() for v8M.
7744          * This corresponds to the ARM ARM pseudocode for v8M setting
7745          * some LR bits in PushStack() and some in ExceptionTaken();
7746          * the distinction matters for the tailchain cases where we
7747          * can take an exception without pushing the stack.
7748          */
7749         if (env->v7m.secure) {
7750             lr |= R_V7M_EXCRET_S_MASK;
7751         }
7752     } else {
7753         lr = R_V7M_EXCRET_RES1_MASK |
7754             R_V7M_EXCRET_S_MASK |
7755             R_V7M_EXCRET_DCRS_MASK |
7756             R_V7M_EXCRET_FTYPE_MASK |
7757             R_V7M_EXCRET_ES_MASK;
7758         if (env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK) {
7759             lr |= R_V7M_EXCRET_SPSEL_MASK;
7760         }
7761     }
7762     if (!arm_v7m_is_handler_mode(env)) {
7763         lr |= R_V7M_EXCRET_MODE_MASK;
7764     }
7765
7766     ignore_stackfaults = v7m_push_stack(cpu);
7767     v7m_exception_taken(cpu, lr, false, ignore_stackfaults);
7768 }
7769
7770 /* Function used to synchronize QEMU's AArch64 register set with AArch32
7771  * register set.  This is necessary when switching between AArch32 and AArch64
7772  * execution state.
7773  */
7774 void aarch64_sync_32_to_64(CPUARMState *env)
7775 {
7776     int i;
7777     uint32_t mode = env->uncached_cpsr & CPSR_M;
7778
7779     /* We can blanket copy R[0:7] to X[0:7] */
7780     for (i = 0; i < 8; i++) {
7781         env->xregs[i] = env->regs[i];
7782     }
7783
7784     /* Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
7785      * Otherwise, they come from the banked user regs.
7786      */
7787     if (mode == ARM_CPU_MODE_FIQ) {
7788         for (i = 8; i < 13; i++) {
7789             env->xregs[i] = env->usr_regs[i - 8];
7790         }
7791     } else {
7792         for (i = 8; i < 13; i++) {
7793             env->xregs[i] = env->regs[i];
7794         }
7795     }
7796
7797     /* Registers x13-x23 are the various mode SP and FP registers. Registers
7798      * r13 and r14 are only copied if we are in that mode, otherwise we copy
7799      * from the mode banked register.
7800      */
7801     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7802         env->xregs[13] = env->regs[13];
7803         env->xregs[14] = env->regs[14];
7804     } else {
7805         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
7806         /* HYP is an exception in that it is copied from r14 */
7807         if (mode == ARM_CPU_MODE_HYP) {
7808             env->xregs[14] = env->regs[14];
7809         } else {
7810             env->xregs[14] = env->banked_r14[bank_number(ARM_CPU_MODE_USR)];
7811         }
7812     }
7813
7814     if (mode == ARM_CPU_MODE_HYP) {
7815         env->xregs[15] = env->regs[13];
7816     } else {
7817         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
7818     }
7819
7820     if (mode == ARM_CPU_MODE_IRQ) {
7821         env->xregs[16] = env->regs[14];
7822         env->xregs[17] = env->regs[13];
7823     } else {
7824         env->xregs[16] = env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)];
7825         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
7826     }
7827
7828     if (mode == ARM_CPU_MODE_SVC) {
7829         env->xregs[18] = env->regs[14];
7830         env->xregs[19] = env->regs[13];
7831     } else {
7832         env->xregs[18] = env->banked_r14[bank_number(ARM_CPU_MODE_SVC)];
7833         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
7834     }
7835
7836     if (mode == ARM_CPU_MODE_ABT) {
7837         env->xregs[20] = env->regs[14];
7838         env->xregs[21] = env->regs[13];
7839     } else {
7840         env->xregs[20] = env->banked_r14[bank_number(ARM_CPU_MODE_ABT)];
7841         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
7842     }
7843
7844     if (mode == ARM_CPU_MODE_UND) {
7845         env->xregs[22] = env->regs[14];
7846         env->xregs[23] = env->regs[13];
7847     } else {
7848         env->xregs[22] = env->banked_r14[bank_number(ARM_CPU_MODE_UND)];
7849         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
7850     }
7851
7852     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7853      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
7854      * FIQ bank for r8-r14.
7855      */
7856     if (mode == ARM_CPU_MODE_FIQ) {
7857         for (i = 24; i < 31; i++) {
7858             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
7859         }
7860     } else {
7861         for (i = 24; i < 29; i++) {
7862             env->xregs[i] = env->fiq_regs[i - 24];
7863         }
7864         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
7865         env->xregs[30] = env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)];
7866     }
7867
7868     env->pc = env->regs[15];
7869 }
7870
7871 /* Function used to synchronize QEMU's AArch32 register set with AArch64
7872  * register set.  This is necessary when switching between AArch32 and AArch64
7873  * execution state.
7874  */
7875 void aarch64_sync_64_to_32(CPUARMState *env)
7876 {
7877     int i;
7878     uint32_t mode = env->uncached_cpsr & CPSR_M;
7879
7880     /* We can blanket copy X[0:7] to R[0:7] */
7881     for (i = 0; i < 8; i++) {
7882         env->regs[i] = env->xregs[i];
7883     }
7884
7885     /* Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
7886      * Otherwise, we copy x8-x12 into the banked user regs.
7887      */
7888     if (mode == ARM_CPU_MODE_FIQ) {
7889         for (i = 8; i < 13; i++) {
7890             env->usr_regs[i - 8] = env->xregs[i];
7891         }
7892     } else {
7893         for (i = 8; i < 13; i++) {
7894             env->regs[i] = env->xregs[i];
7895         }
7896     }
7897
7898     /* Registers r13 & r14 depend on the current mode.
7899      * If we are in a given mode, we copy the corresponding x registers to r13
7900      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
7901      * for the mode.
7902      */
7903     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7904         env->regs[13] = env->xregs[13];
7905         env->regs[14] = env->xregs[14];
7906     } else {
7907         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
7908
7909         /* HYP is an exception in that it does not have its own banked r14 but
7910          * shares the USR r14
7911          */
7912         if (mode == ARM_CPU_MODE_HYP) {
7913             env->regs[14] = env->xregs[14];
7914         } else {
7915             env->banked_r14[bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
7916         }
7917     }
7918
7919     if (mode == ARM_CPU_MODE_HYP) {
7920         env->regs[13] = env->xregs[15];
7921     } else {
7922         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
7923     }
7924
7925     if (mode == ARM_CPU_MODE_IRQ) {
7926         env->regs[14] = env->xregs[16];
7927         env->regs[13] = env->xregs[17];
7928     } else {
7929         env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
7930         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
7931     }
7932
7933     if (mode == ARM_CPU_MODE_SVC) {
7934         env->regs[14] = env->xregs[18];
7935         env->regs[13] = env->xregs[19];
7936     } else {
7937         env->banked_r14[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
7938         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
7939     }
7940
7941     if (mode == ARM_CPU_MODE_ABT) {
7942         env->regs[14] = env->xregs[20];
7943         env->regs[13] = env->xregs[21];
7944     } else {
7945         env->banked_r14[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
7946         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
7947     }
7948
7949     if (mode == ARM_CPU_MODE_UND) {
7950         env->regs[14] = env->xregs[22];
7951         env->regs[13] = env->xregs[23];
7952     } else {
7953         env->banked_r14[bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
7954         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
7955     }
7956
7957     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7958      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
7959      * FIQ bank for r8-r14.
7960      */
7961     if (mode == ARM_CPU_MODE_FIQ) {
7962         for (i = 24; i < 31; i++) {
7963             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
7964         }
7965     } else {
7966         for (i = 24; i < 29; i++) {
7967             env->fiq_regs[i - 24] = env->xregs[i];
7968         }
7969         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
7970         env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
7971     }
7972
7973     env->regs[15] = env->pc;
7974 }
7975
7976 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
7977 {
7978     ARMCPU *cpu = ARM_CPU(cs);
7979     CPUARMState *env = &cpu->env;
7980     uint32_t addr;
7981     uint32_t mask;
7982     int new_mode;
7983     uint32_t offset;
7984     uint32_t moe;
7985
7986     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
7987     switch (env->exception.syndrome >> ARM_EL_EC_SHIFT) {
7988     case EC_BREAKPOINT:
7989     case EC_BREAKPOINT_SAME_EL:
7990         moe = 1;
7991         break;
7992     case EC_WATCHPOINT:
7993     case EC_WATCHPOINT_SAME_EL:
7994         moe = 10;
7995         break;
7996     case EC_AA32_BKPT:
7997         moe = 3;
7998         break;
7999     case EC_VECTORCATCH:
8000         moe = 5;
8001         break;
8002     default:
8003         moe = 0;
8004         break;
8005     }
8006
8007     if (moe) {
8008         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
8009     }
8010
8011     /* TODO: Vectored interrupt controller.  */
8012     switch (cs->exception_index) {
8013     case EXCP_UDEF:
8014         new_mode = ARM_CPU_MODE_UND;
8015         addr = 0x04;
8016         mask = CPSR_I;
8017         if (env->thumb)
8018             offset = 2;
8019         else
8020             offset = 4;
8021         break;
8022     case EXCP_SWI:
8023         new_mode = ARM_CPU_MODE_SVC;
8024         addr = 0x08;
8025         mask = CPSR_I;
8026         /* The PC already points to the next instruction.  */
8027         offset = 0;
8028         break;
8029     case EXCP_BKPT:
8030         /* Fall through to prefetch abort.  */
8031     case EXCP_PREFETCH_ABORT:
8032         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
8033         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
8034         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
8035                       env->exception.fsr, (uint32_t)env->exception.vaddress);
8036         new_mode = ARM_CPU_MODE_ABT;
8037         addr = 0x0c;
8038         mask = CPSR_A | CPSR_I;
8039         offset = 4;
8040         break;
8041     case EXCP_DATA_ABORT:
8042         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
8043         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
8044         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
8045                       env->exception.fsr,
8046                       (uint32_t)env->exception.vaddress);
8047         new_mode = ARM_CPU_MODE_ABT;
8048         addr = 0x10;
8049         mask = CPSR_A | CPSR_I;
8050         offset = 8;
8051         break;
8052     case EXCP_IRQ:
8053         new_mode = ARM_CPU_MODE_IRQ;
8054         addr = 0x18;
8055         /* Disable IRQ and imprecise data aborts.  */
8056         mask = CPSR_A | CPSR_I;
8057         offset = 4;
8058         if (env->cp15.scr_el3 & SCR_IRQ) {
8059             /* IRQ routed to monitor mode */
8060             new_mode = ARM_CPU_MODE_MON;
8061             mask |= CPSR_F;
8062         }
8063         break;
8064     case EXCP_FIQ:
8065         new_mode = ARM_CPU_MODE_FIQ;
8066         addr = 0x1c;
8067         /* Disable FIQ, IRQ and imprecise data aborts.  */
8068         mask = CPSR_A | CPSR_I | CPSR_F;
8069         if (env->cp15.scr_el3 & SCR_FIQ) {
8070             /* FIQ routed to monitor mode */
8071             new_mode = ARM_CPU_MODE_MON;
8072         }
8073         offset = 4;
8074         break;
8075     case EXCP_VIRQ:
8076         new_mode = ARM_CPU_MODE_IRQ;
8077         addr = 0x18;
8078         /* Disable IRQ and imprecise data aborts.  */
8079         mask = CPSR_A | CPSR_I;
8080         offset = 4;
8081         break;
8082     case EXCP_VFIQ:
8083         new_mode = ARM_CPU_MODE_FIQ;
8084         addr = 0x1c;
8085         /* Disable FIQ, IRQ and imprecise data aborts.  */
8086         mask = CPSR_A | CPSR_I | CPSR_F;
8087         offset = 4;
8088         break;
8089     case EXCP_SMC:
8090         new_mode = ARM_CPU_MODE_MON;
8091         addr = 0x08;
8092         mask = CPSR_A | CPSR_I | CPSR_F;
8093         offset = 0;
8094         break;
8095     default:
8096         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8097         return; /* Never happens.  Keep compiler happy.  */
8098     }
8099
8100     if (new_mode == ARM_CPU_MODE_MON) {
8101         addr += env->cp15.mvbar;
8102     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
8103         /* High vectors. When enabled, base address cannot be remapped. */
8104         addr += 0xffff0000;
8105     } else {
8106         /* ARM v7 architectures provide a vector base address register to remap
8107          * the interrupt vector table.
8108          * This register is only followed in non-monitor mode, and is banked.
8109          * Note: only bits 31:5 are valid.
8110          */
8111         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
8112     }
8113
8114     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
8115         env->cp15.scr_el3 &= ~SCR_NS;
8116     }
8117
8118     switch_mode (env, new_mode);
8119     /* For exceptions taken to AArch32 we must clear the SS bit in both
8120      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
8121      */
8122     env->uncached_cpsr &= ~PSTATE_SS;
8123     env->spsr = cpsr_read(env);
8124     /* Clear IT bits.  */
8125     env->condexec_bits = 0;
8126     /* Switch to the new mode, and to the correct instruction set.  */
8127     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
8128     /* Set new mode endianness */
8129     env->uncached_cpsr &= ~CPSR_E;
8130     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
8131         env->uncached_cpsr |= CPSR_E;
8132     }
8133     env->daif |= mask;
8134     /* this is a lie, as the was no c1_sys on V4T/V5, but who cares
8135      * and we should just guard the thumb mode on V4 */
8136     if (arm_feature(env, ARM_FEATURE_V4T)) {
8137         env->thumb = (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
8138     }
8139     env->regs[14] = env->regs[15] + offset;
8140     env->regs[15] = addr;
8141 }
8142
8143 /* Handle exception entry to a target EL which is using AArch64 */
8144 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
8145 {
8146     ARMCPU *cpu = ARM_CPU(cs);
8147     CPUARMState *env = &cpu->env;
8148     unsigned int new_el = env->exception.target_el;
8149     target_ulong addr = env->cp15.vbar_el[new_el];
8150     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
8151
8152     if (arm_current_el(env) < new_el) {
8153         /* Entry vector offset depends on whether the implemented EL
8154          * immediately lower than the target level is using AArch32 or AArch64
8155          */
8156         bool is_aa64;
8157
8158         switch (new_el) {
8159         case 3:
8160             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
8161             break;
8162         case 2:
8163             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
8164             break;
8165         case 1:
8166             is_aa64 = is_a64(env);
8167             break;
8168         default:
8169             g_assert_not_reached();
8170         }
8171
8172         if (is_aa64) {
8173             addr += 0x400;
8174         } else {
8175             addr += 0x600;
8176         }
8177     } else if (pstate_read(env) & PSTATE_SP) {
8178         addr += 0x200;
8179     }
8180
8181     switch (cs->exception_index) {
8182     case EXCP_PREFETCH_ABORT:
8183     case EXCP_DATA_ABORT:
8184         env->cp15.far_el[new_el] = env->exception.vaddress;
8185         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
8186                       env->cp15.far_el[new_el]);
8187         /* fall through */
8188     case EXCP_BKPT:
8189     case EXCP_UDEF:
8190     case EXCP_SWI:
8191     case EXCP_HVC:
8192     case EXCP_HYP_TRAP:
8193     case EXCP_SMC:
8194         env->cp15.esr_el[new_el] = env->exception.syndrome;
8195         break;
8196     case EXCP_IRQ:
8197     case EXCP_VIRQ:
8198         addr += 0x80;
8199         break;
8200     case EXCP_FIQ:
8201     case EXCP_VFIQ:
8202         addr += 0x100;
8203         break;
8204     case EXCP_SEMIHOST:
8205         qemu_log_mask(CPU_LOG_INT,
8206                       "...handling as semihosting call 0x%" PRIx64 "\n",
8207                       env->xregs[0]);
8208         env->xregs[0] = do_arm_semihosting(env);
8209         return;
8210     default:
8211         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8212     }
8213
8214     if (is_a64(env)) {
8215         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
8216         aarch64_save_sp(env, arm_current_el(env));
8217         env->elr_el[new_el] = env->pc;
8218     } else {
8219         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
8220         env->elr_el[new_el] = env->regs[15];
8221
8222         aarch64_sync_32_to_64(env);
8223
8224         env->condexec_bits = 0;
8225     }
8226     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
8227                   env->elr_el[new_el]);
8228
8229     pstate_write(env, PSTATE_DAIF | new_mode);
8230     env->aarch64 = 1;
8231     aarch64_restore_sp(env, new_el);
8232
8233     env->pc = addr;
8234
8235     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
8236                   new_el, env->pc, pstate_read(env));
8237 }
8238
8239 static inline bool check_for_semihosting(CPUState *cs)
8240 {
8241     /* Check whether this exception is a semihosting call; if so
8242      * then handle it and return true; otherwise return false.
8243      */
8244     ARMCPU *cpu = ARM_CPU(cs);
8245     CPUARMState *env = &cpu->env;
8246
8247     if (is_a64(env)) {
8248         if (cs->exception_index == EXCP_SEMIHOST) {
8249             /* This is always the 64-bit semihosting exception.
8250              * The "is this usermode" and "is semihosting enabled"
8251              * checks have been done at translate time.
8252              */
8253             qemu_log_mask(CPU_LOG_INT,
8254                           "...handling as semihosting call 0x%" PRIx64 "\n",
8255                           env->xregs[0]);
8256             env->xregs[0] = do_arm_semihosting(env);
8257             return true;
8258         }
8259         return false;
8260     } else {
8261         uint32_t imm;
8262
8263         /* Only intercept calls from privileged modes, to provide some
8264          * semblance of security.
8265          */
8266         if (cs->exception_index != EXCP_SEMIHOST &&
8267             (!semihosting_enabled() ||
8268              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
8269             return false;
8270         }
8271
8272         switch (cs->exception_index) {
8273         case EXCP_SEMIHOST:
8274             /* This is always a semihosting call; the "is this usermode"
8275              * and "is semihosting enabled" checks have been done at
8276              * translate time.
8277              */
8278             break;
8279         case EXCP_SWI:
8280             /* Check for semihosting interrupt.  */
8281             if (env->thumb) {
8282                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
8283                     & 0xff;
8284                 if (imm == 0xab) {
8285                     break;
8286                 }
8287             } else {
8288                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
8289                     & 0xffffff;
8290                 if (imm == 0x123456) {
8291                     break;
8292                 }
8293             }
8294             return false;
8295         case EXCP_BKPT:
8296             /* See if this is a semihosting syscall.  */
8297             if (env->thumb) {
8298                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
8299                     & 0xff;
8300                 if (imm == 0xab) {
8301                     env->regs[15] += 2;
8302                     break;
8303                 }
8304             }
8305             return false;
8306         default:
8307             return false;
8308         }
8309
8310         qemu_log_mask(CPU_LOG_INT,
8311                       "...handling as semihosting call 0x%x\n",
8312                       env->regs[0]);
8313         env->regs[0] = do_arm_semihosting(env);
8314         return true;
8315     }
8316 }
8317
8318 /* Handle a CPU exception for A and R profile CPUs.
8319  * Do any appropriate logging, handle PSCI calls, and then hand off
8320  * to the AArch64-entry or AArch32-entry function depending on the
8321  * target exception level's register width.
8322  */
8323 void arm_cpu_do_interrupt(CPUState *cs)
8324 {
8325     ARMCPU *cpu = ARM_CPU(cs);
8326     CPUARMState *env = &cpu->env;
8327     unsigned int new_el = env->exception.target_el;
8328
8329     assert(!arm_feature(env, ARM_FEATURE_M));
8330
8331     arm_log_exception(cs->exception_index);
8332     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
8333                   new_el);
8334     if (qemu_loglevel_mask(CPU_LOG_INT)
8335         && !excp_is_internal(cs->exception_index)) {
8336         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
8337                       env->exception.syndrome >> ARM_EL_EC_SHIFT,
8338                       env->exception.syndrome);
8339     }
8340
8341     if (arm_is_psci_call(cpu, cs->exception_index)) {
8342         arm_handle_psci_call(cpu);
8343         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
8344         return;
8345     }
8346
8347     /* Semihosting semantics depend on the register width of the
8348      * code that caused the exception, not the target exception level,
8349      * so must be handled here.
8350      */
8351     if (check_for_semihosting(cs)) {
8352         return;
8353     }
8354
8355     /* Hooks may change global state so BQL should be held, also the
8356      * BQL needs to be held for any modification of
8357      * cs->interrupt_request.
8358      */
8359     g_assert(qemu_mutex_iothread_locked());
8360
8361     arm_call_pre_el_change_hook(cpu);
8362
8363     assert(!excp_is_internal(cs->exception_index));
8364     if (arm_el_is_aa64(env, new_el)) {
8365         arm_cpu_do_interrupt_aarch64(cs);
8366     } else {
8367         arm_cpu_do_interrupt_aarch32(cs);
8368     }
8369
8370     arm_call_el_change_hook(cpu);
8371
8372     if (!kvm_enabled()) {
8373         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
8374     }
8375 }
8376
8377 /* Return the exception level which controls this address translation regime */
8378 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
8379 {
8380     switch (mmu_idx) {
8381     case ARMMMUIdx_S2NS:
8382     case ARMMMUIdx_S1E2:
8383         return 2;
8384     case ARMMMUIdx_S1E3:
8385         return 3;
8386     case ARMMMUIdx_S1SE0:
8387         return arm_el_is_aa64(env, 3) ? 1 : 3;
8388     case ARMMMUIdx_S1SE1:
8389     case ARMMMUIdx_S1NSE0:
8390     case ARMMMUIdx_S1NSE1:
8391     case ARMMMUIdx_MPrivNegPri:
8392     case ARMMMUIdx_MUserNegPri:
8393     case ARMMMUIdx_MPriv:
8394     case ARMMMUIdx_MUser:
8395     case ARMMMUIdx_MSPrivNegPri:
8396     case ARMMMUIdx_MSUserNegPri:
8397     case ARMMMUIdx_MSPriv:
8398     case ARMMMUIdx_MSUser:
8399         return 1;
8400     default:
8401         g_assert_not_reached();
8402     }
8403 }
8404
8405 /* Return the SCTLR value which controls this address translation regime */
8406 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
8407 {
8408     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
8409 }
8410
8411 /* Return true if the specified stage of address translation is disabled */
8412 static inline bool regime_translation_disabled(CPUARMState *env,
8413                                                ARMMMUIdx mmu_idx)
8414 {
8415     if (arm_feature(env, ARM_FEATURE_M)) {
8416         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
8417                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
8418         case R_V7M_MPU_CTRL_ENABLE_MASK:
8419             /* Enabled, but not for HardFault and NMI */
8420             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
8421         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
8422             /* Enabled for all cases */
8423             return false;
8424         case 0:
8425         default:
8426             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
8427              * we warned about that in armv7m_nvic.c when the guest set it.
8428              */
8429             return true;
8430         }
8431     }
8432
8433     if (mmu_idx == ARMMMUIdx_S2NS) {
8434         return (env->cp15.hcr_el2 & HCR_VM) == 0;
8435     }
8436
8437     if (env->cp15.hcr_el2 & HCR_TGE) {
8438         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
8439         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
8440             return true;
8441         }
8442     }
8443
8444     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
8445 }
8446
8447 static inline bool regime_translation_big_endian(CPUARMState *env,
8448                                                  ARMMMUIdx mmu_idx)
8449 {
8450     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
8451 }
8452
8453 /* Return the TCR controlling this translation regime */
8454 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
8455 {
8456     if (mmu_idx == ARMMMUIdx_S2NS) {
8457         return &env->cp15.vtcr_el2;
8458     }
8459     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
8460 }
8461
8462 /* Convert a possible stage1+2 MMU index into the appropriate
8463  * stage 1 MMU index
8464  */
8465 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
8466 {
8467     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
8468         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
8469     }
8470     return mmu_idx;
8471 }
8472
8473 /* Returns TBI0 value for current regime el */
8474 uint32_t arm_regime_tbi0(CPUARMState *env, ARMMMUIdx mmu_idx)
8475 {
8476     TCR *tcr;
8477     uint32_t el;
8478
8479     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8480      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8481      */
8482     mmu_idx = stage_1_mmu_idx(mmu_idx);
8483
8484     tcr = regime_tcr(env, mmu_idx);
8485     el = regime_el(env, mmu_idx);
8486
8487     if (el > 1) {
8488         return extract64(tcr->raw_tcr, 20, 1);
8489     } else {
8490         return extract64(tcr->raw_tcr, 37, 1);
8491     }
8492 }
8493
8494 /* Returns TBI1 value for current regime el */
8495 uint32_t arm_regime_tbi1(CPUARMState *env, ARMMMUIdx mmu_idx)
8496 {
8497     TCR *tcr;
8498     uint32_t el;
8499
8500     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8501      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8502      */
8503     mmu_idx = stage_1_mmu_idx(mmu_idx);
8504
8505     tcr = regime_tcr(env, mmu_idx);
8506     el = regime_el(env, mmu_idx);
8507
8508     if (el > 1) {
8509         return 0;
8510     } else {
8511         return extract64(tcr->raw_tcr, 38, 1);
8512     }
8513 }
8514
8515 /* Return the TTBR associated with this translation regime */
8516 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
8517                                    int ttbrn)
8518 {
8519     if (mmu_idx == ARMMMUIdx_S2NS) {
8520         return env->cp15.vttbr_el2;
8521     }
8522     if (ttbrn == 0) {
8523         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
8524     } else {
8525         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
8526     }
8527 }
8528
8529 /* Return true if the translation regime is using LPAE format page tables */
8530 static inline bool regime_using_lpae_format(CPUARMState *env,
8531                                             ARMMMUIdx mmu_idx)
8532 {
8533     int el = regime_el(env, mmu_idx);
8534     if (el == 2 || arm_el_is_aa64(env, el)) {
8535         return true;
8536     }
8537     if (arm_feature(env, ARM_FEATURE_LPAE)
8538         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
8539         return true;
8540     }
8541     return false;
8542 }
8543
8544 /* Returns true if the stage 1 translation regime is using LPAE format page
8545  * tables. Used when raising alignment exceptions, whose FSR changes depending
8546  * on whether the long or short descriptor format is in use. */
8547 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
8548 {
8549     mmu_idx = stage_1_mmu_idx(mmu_idx);
8550
8551     return regime_using_lpae_format(env, mmu_idx);
8552 }
8553
8554 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
8555 {
8556     switch (mmu_idx) {
8557     case ARMMMUIdx_S1SE0:
8558     case ARMMMUIdx_S1NSE0:
8559     case ARMMMUIdx_MUser:
8560     case ARMMMUIdx_MSUser:
8561     case ARMMMUIdx_MUserNegPri:
8562     case ARMMMUIdx_MSUserNegPri:
8563         return true;
8564     default:
8565         return false;
8566     case ARMMMUIdx_S12NSE0:
8567     case ARMMMUIdx_S12NSE1:
8568         g_assert_not_reached();
8569     }
8570 }
8571
8572 /* Translate section/page access permissions to page
8573  * R/W protection flags
8574  *
8575  * @env:         CPUARMState
8576  * @mmu_idx:     MMU index indicating required translation regime
8577  * @ap:          The 3-bit access permissions (AP[2:0])
8578  * @domain_prot: The 2-bit domain access permissions
8579  */
8580 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
8581                                 int ap, int domain_prot)
8582 {
8583     bool is_user = regime_is_user(env, mmu_idx);
8584
8585     if (domain_prot == 3) {
8586         return PAGE_READ | PAGE_WRITE;
8587     }
8588
8589     switch (ap) {
8590     case 0:
8591         if (arm_feature(env, ARM_FEATURE_V7)) {
8592             return 0;
8593         }
8594         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
8595         case SCTLR_S:
8596             return is_user ? 0 : PAGE_READ;
8597         case SCTLR_R:
8598             return PAGE_READ;
8599         default:
8600             return 0;
8601         }
8602     case 1:
8603         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8604     case 2:
8605         if (is_user) {
8606             return PAGE_READ;
8607         } else {
8608             return PAGE_READ | PAGE_WRITE;
8609         }
8610     case 3:
8611         return PAGE_READ | PAGE_WRITE;
8612     case 4: /* Reserved.  */
8613         return 0;
8614     case 5:
8615         return is_user ? 0 : PAGE_READ;
8616     case 6:
8617         return PAGE_READ;
8618     case 7:
8619         if (!arm_feature(env, ARM_FEATURE_V6K)) {
8620             return 0;
8621         }
8622         return PAGE_READ;
8623     default:
8624         g_assert_not_reached();
8625     }
8626 }
8627
8628 /* Translate section/page access permissions to page
8629  * R/W protection flags.
8630  *
8631  * @ap:      The 2-bit simple AP (AP[2:1])
8632  * @is_user: TRUE if accessing from PL0
8633  */
8634 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
8635 {
8636     switch (ap) {
8637     case 0:
8638         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8639     case 1:
8640         return PAGE_READ | PAGE_WRITE;
8641     case 2:
8642         return is_user ? 0 : PAGE_READ;
8643     case 3:
8644         return PAGE_READ;
8645     default:
8646         g_assert_not_reached();
8647     }
8648 }
8649
8650 static inline int
8651 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
8652 {
8653     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
8654 }
8655
8656 /* Translate S2 section/page access permissions to protection flags
8657  *
8658  * @env:     CPUARMState
8659  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
8660  * @xn:      XN (execute-never) bit
8661  */
8662 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
8663 {
8664     int prot = 0;
8665
8666     if (s2ap & 1) {
8667         prot |= PAGE_READ;
8668     }
8669     if (s2ap & 2) {
8670         prot |= PAGE_WRITE;
8671     }
8672     if (!xn) {
8673         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
8674             prot |= PAGE_EXEC;
8675         }
8676     }
8677     return prot;
8678 }
8679
8680 /* Translate section/page access permissions to protection flags
8681  *
8682  * @env:     CPUARMState
8683  * @mmu_idx: MMU index indicating required translation regime
8684  * @is_aa64: TRUE if AArch64
8685  * @ap:      The 2-bit simple AP (AP[2:1])
8686  * @ns:      NS (non-secure) bit
8687  * @xn:      XN (execute-never) bit
8688  * @pxn:     PXN (privileged execute-never) bit
8689  */
8690 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
8691                       int ap, int ns, int xn, int pxn)
8692 {
8693     bool is_user = regime_is_user(env, mmu_idx);
8694     int prot_rw, user_rw;
8695     bool have_wxn;
8696     int wxn = 0;
8697
8698     assert(mmu_idx != ARMMMUIdx_S2NS);
8699
8700     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
8701     if (is_user) {
8702         prot_rw = user_rw;
8703     } else {
8704         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
8705     }
8706
8707     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
8708         return prot_rw;
8709     }
8710
8711     /* TODO have_wxn should be replaced with
8712      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
8713      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
8714      * compatible processors have EL2, which is required for [U]WXN.
8715      */
8716     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
8717
8718     if (have_wxn) {
8719         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
8720     }
8721
8722     if (is_aa64) {
8723         switch (regime_el(env, mmu_idx)) {
8724         case 1:
8725             if (!is_user) {
8726                 xn = pxn || (user_rw & PAGE_WRITE);
8727             }
8728             break;
8729         case 2:
8730         case 3:
8731             break;
8732         }
8733     } else if (arm_feature(env, ARM_FEATURE_V7)) {
8734         switch (regime_el(env, mmu_idx)) {
8735         case 1:
8736         case 3:
8737             if (is_user) {
8738                 xn = xn || !(user_rw & PAGE_READ);
8739             } else {
8740                 int uwxn = 0;
8741                 if (have_wxn) {
8742                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
8743                 }
8744                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
8745                      (uwxn && (user_rw & PAGE_WRITE));
8746             }
8747             break;
8748         case 2:
8749             break;
8750         }
8751     } else {
8752         xn = wxn = 0;
8753     }
8754
8755     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
8756         return prot_rw;
8757     }
8758     return prot_rw | PAGE_EXEC;
8759 }
8760
8761 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
8762                                      uint32_t *table, uint32_t address)
8763 {
8764     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
8765     TCR *tcr = regime_tcr(env, mmu_idx);
8766
8767     if (address & tcr->mask) {
8768         if (tcr->raw_tcr & TTBCR_PD1) {
8769             /* Translation table walk disabled for TTBR1 */
8770             return false;
8771         }
8772         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
8773     } else {
8774         if (tcr->raw_tcr & TTBCR_PD0) {
8775             /* Translation table walk disabled for TTBR0 */
8776             return false;
8777         }
8778         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
8779     }
8780     *table |= (address >> 18) & 0x3ffc;
8781     return true;
8782 }
8783
8784 /* Translate a S1 pagetable walk through S2 if needed.  */
8785 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
8786                                hwaddr addr, MemTxAttrs txattrs,
8787                                ARMMMUFaultInfo *fi)
8788 {
8789     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
8790         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
8791         target_ulong s2size;
8792         hwaddr s2pa;
8793         int s2prot;
8794         int ret;
8795
8796         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
8797                                  &txattrs, &s2prot, &s2size, fi, NULL);
8798         if (ret) {
8799             assert(fi->type != ARMFault_None);
8800             fi->s2addr = addr;
8801             fi->stage2 = true;
8802             fi->s1ptw = true;
8803             return ~0;
8804         }
8805         addr = s2pa;
8806     }
8807     return addr;
8808 }
8809
8810 /* All loads done in the course of a page table walk go through here. */
8811 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8812                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8813 {
8814     ARMCPU *cpu = ARM_CPU(cs);
8815     CPUARMState *env = &cpu->env;
8816     MemTxAttrs attrs = {};
8817     MemTxResult result = MEMTX_OK;
8818     AddressSpace *as;
8819     uint32_t data;
8820
8821     attrs.secure = is_secure;
8822     as = arm_addressspace(cs, attrs);
8823     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8824     if (fi->s1ptw) {
8825         return 0;
8826     }
8827     if (regime_translation_big_endian(env, mmu_idx)) {
8828         data = address_space_ldl_be(as, addr, attrs, &result);
8829     } else {
8830         data = address_space_ldl_le(as, addr, attrs, &result);
8831     }
8832     if (result == MEMTX_OK) {
8833         return data;
8834     }
8835     fi->type = ARMFault_SyncExternalOnWalk;
8836     fi->ea = arm_extabort_type(result);
8837     return 0;
8838 }
8839
8840 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8841                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8842 {
8843     ARMCPU *cpu = ARM_CPU(cs);
8844     CPUARMState *env = &cpu->env;
8845     MemTxAttrs attrs = {};
8846     MemTxResult result = MEMTX_OK;
8847     AddressSpace *as;
8848     uint64_t data;
8849
8850     attrs.secure = is_secure;
8851     as = arm_addressspace(cs, attrs);
8852     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8853     if (fi->s1ptw) {
8854         return 0;
8855     }
8856     if (regime_translation_big_endian(env, mmu_idx)) {
8857         data = address_space_ldq_be(as, addr, attrs, &result);
8858     } else {
8859         data = address_space_ldq_le(as, addr, attrs, &result);
8860     }
8861     if (result == MEMTX_OK) {
8862         return data;
8863     }
8864     fi->type = ARMFault_SyncExternalOnWalk;
8865     fi->ea = arm_extabort_type(result);
8866     return 0;
8867 }
8868
8869 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
8870                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8871                              hwaddr *phys_ptr, int *prot,
8872                              target_ulong *page_size,
8873                              ARMMMUFaultInfo *fi)
8874 {
8875     CPUState *cs = CPU(arm_env_get_cpu(env));
8876     int level = 1;
8877     uint32_t table;
8878     uint32_t desc;
8879     int type;
8880     int ap;
8881     int domain = 0;
8882     int domain_prot;
8883     hwaddr phys_addr;
8884     uint32_t dacr;
8885
8886     /* Pagetable walk.  */
8887     /* Lookup l1 descriptor.  */
8888     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8889         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8890         fi->type = ARMFault_Translation;
8891         goto do_fault;
8892     }
8893     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8894                        mmu_idx, fi);
8895     if (fi->type != ARMFault_None) {
8896         goto do_fault;
8897     }
8898     type = (desc & 3);
8899     domain = (desc >> 5) & 0x0f;
8900     if (regime_el(env, mmu_idx) == 1) {
8901         dacr = env->cp15.dacr_ns;
8902     } else {
8903         dacr = env->cp15.dacr_s;
8904     }
8905     domain_prot = (dacr >> (domain * 2)) & 3;
8906     if (type == 0) {
8907         /* Section translation fault.  */
8908         fi->type = ARMFault_Translation;
8909         goto do_fault;
8910     }
8911     if (type != 2) {
8912         level = 2;
8913     }
8914     if (domain_prot == 0 || domain_prot == 2) {
8915         fi->type = ARMFault_Domain;
8916         goto do_fault;
8917     }
8918     if (type == 2) {
8919         /* 1Mb section.  */
8920         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
8921         ap = (desc >> 10) & 3;
8922         *page_size = 1024 * 1024;
8923     } else {
8924         /* Lookup l2 entry.  */
8925         if (type == 1) {
8926             /* Coarse pagetable.  */
8927             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
8928         } else {
8929             /* Fine pagetable.  */
8930             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
8931         }
8932         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8933                            mmu_idx, fi);
8934         if (fi->type != ARMFault_None) {
8935             goto do_fault;
8936         }
8937         switch (desc & 3) {
8938         case 0: /* Page translation fault.  */
8939             fi->type = ARMFault_Translation;
8940             goto do_fault;
8941         case 1: /* 64k page.  */
8942             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
8943             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
8944             *page_size = 0x10000;
8945             break;
8946         case 2: /* 4k page.  */
8947             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8948             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
8949             *page_size = 0x1000;
8950             break;
8951         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
8952             if (type == 1) {
8953                 /* ARMv6/XScale extended small page format */
8954                 if (arm_feature(env, ARM_FEATURE_XSCALE)
8955                     || arm_feature(env, ARM_FEATURE_V6)) {
8956                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8957                     *page_size = 0x1000;
8958                 } else {
8959                     /* UNPREDICTABLE in ARMv5; we choose to take a
8960                      * page translation fault.
8961                      */
8962                     fi->type = ARMFault_Translation;
8963                     goto do_fault;
8964                 }
8965             } else {
8966                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
8967                 *page_size = 0x400;
8968             }
8969             ap = (desc >> 4) & 3;
8970             break;
8971         default:
8972             /* Never happens, but compiler isn't smart enough to tell.  */
8973             abort();
8974         }
8975     }
8976     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
8977     *prot |= *prot ? PAGE_EXEC : 0;
8978     if (!(*prot & (1 << access_type))) {
8979         /* Access permission fault.  */
8980         fi->type = ARMFault_Permission;
8981         goto do_fault;
8982     }
8983     *phys_ptr = phys_addr;
8984     return false;
8985 do_fault:
8986     fi->domain = domain;
8987     fi->level = level;
8988     return true;
8989 }
8990
8991 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
8992                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8993                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
8994                              target_ulong *page_size, ARMMMUFaultInfo *fi)
8995 {
8996     CPUState *cs = CPU(arm_env_get_cpu(env));
8997     int level = 1;
8998     uint32_t table;
8999     uint32_t desc;
9000     uint32_t xn;
9001     uint32_t pxn = 0;
9002     int type;
9003     int ap;
9004     int domain = 0;
9005     int domain_prot;
9006     hwaddr phys_addr;
9007     uint32_t dacr;
9008     bool ns;
9009
9010     /* Pagetable walk.  */
9011     /* Lookup l1 descriptor.  */
9012     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
9013         /* Section translation fault if page walk is disabled by PD0 or PD1 */
9014         fi->type = ARMFault_Translation;
9015         goto do_fault;
9016     }
9017     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9018                        mmu_idx, fi);
9019     if (fi->type != ARMFault_None) {
9020         goto do_fault;
9021     }
9022     type = (desc & 3);
9023     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
9024         /* Section translation fault, or attempt to use the encoding
9025          * which is Reserved on implementations without PXN.
9026          */
9027         fi->type = ARMFault_Translation;
9028         goto do_fault;
9029     }
9030     if ((type == 1) || !(desc & (1 << 18))) {
9031         /* Page or Section.  */
9032         domain = (desc >> 5) & 0x0f;
9033     }
9034     if (regime_el(env, mmu_idx) == 1) {
9035         dacr = env->cp15.dacr_ns;
9036     } else {
9037         dacr = env->cp15.dacr_s;
9038     }
9039     if (type == 1) {
9040         level = 2;
9041     }
9042     domain_prot = (dacr >> (domain * 2)) & 3;
9043     if (domain_prot == 0 || domain_prot == 2) {
9044         /* Section or Page domain fault */
9045         fi->type = ARMFault_Domain;
9046         goto do_fault;
9047     }
9048     if (type != 1) {
9049         if (desc & (1 << 18)) {
9050             /* Supersection.  */
9051             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
9052             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
9053             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
9054             *page_size = 0x1000000;
9055         } else {
9056             /* Section.  */
9057             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
9058             *page_size = 0x100000;
9059         }
9060         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
9061         xn = desc & (1 << 4);
9062         pxn = desc & 1;
9063         ns = extract32(desc, 19, 1);
9064     } else {
9065         if (arm_feature(env, ARM_FEATURE_PXN)) {
9066             pxn = (desc >> 2) & 1;
9067         }
9068         ns = extract32(desc, 3, 1);
9069         /* Lookup l2 entry.  */
9070         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
9071         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9072                            mmu_idx, fi);
9073         if (fi->type != ARMFault_None) {
9074             goto do_fault;
9075         }
9076         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
9077         switch (desc & 3) {
9078         case 0: /* Page translation fault.  */
9079             fi->type = ARMFault_Translation;
9080             goto do_fault;
9081         case 1: /* 64k page.  */
9082             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
9083             xn = desc & (1 << 15);
9084             *page_size = 0x10000;
9085             break;
9086         case 2: case 3: /* 4k page.  */
9087             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9088             xn = desc & 1;
9089             *page_size = 0x1000;
9090             break;
9091         default:
9092             /* Never happens, but compiler isn't smart enough to tell.  */
9093             abort();
9094         }
9095     }
9096     if (domain_prot == 3) {
9097         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9098     } else {
9099         if (pxn && !regime_is_user(env, mmu_idx)) {
9100             xn = 1;
9101         }
9102         if (xn && access_type == MMU_INST_FETCH) {
9103             fi->type = ARMFault_Permission;
9104             goto do_fault;
9105         }
9106
9107         if (arm_feature(env, ARM_FEATURE_V6K) &&
9108                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
9109             /* The simplified model uses AP[0] as an access control bit.  */
9110             if ((ap & 1) == 0) {
9111                 /* Access flag fault.  */
9112                 fi->type = ARMFault_AccessFlag;
9113                 goto do_fault;
9114             }
9115             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
9116         } else {
9117             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9118         }
9119         if (*prot && !xn) {
9120             *prot |= PAGE_EXEC;
9121         }
9122         if (!(*prot & (1 << access_type))) {
9123             /* Access permission fault.  */
9124             fi->type = ARMFault_Permission;
9125             goto do_fault;
9126         }
9127     }
9128     if (ns) {
9129         /* The NS bit will (as required by the architecture) have no effect if
9130          * the CPU doesn't support TZ or this is a non-secure translation
9131          * regime, because the attribute will already be non-secure.
9132          */
9133         attrs->secure = false;
9134     }
9135     *phys_ptr = phys_addr;
9136     return false;
9137 do_fault:
9138     fi->domain = domain;
9139     fi->level = level;
9140     return true;
9141 }
9142
9143 /*
9144  * check_s2_mmu_setup
9145  * @cpu:        ARMCPU
9146  * @is_aa64:    True if the translation regime is in AArch64 state
9147  * @startlevel: Suggested starting level
9148  * @inputsize:  Bitsize of IPAs
9149  * @stride:     Page-table stride (See the ARM ARM)
9150  *
9151  * Returns true if the suggested S2 translation parameters are OK and
9152  * false otherwise.
9153  */
9154 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
9155                                int inputsize, int stride)
9156 {
9157     const int grainsize = stride + 3;
9158     int startsizecheck;
9159
9160     /* Negative levels are never allowed.  */
9161     if (level < 0) {
9162         return false;
9163     }
9164
9165     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
9166     if (startsizecheck < 1 || startsizecheck > stride + 4) {
9167         return false;
9168     }
9169
9170     if (is_aa64) {
9171         CPUARMState *env = &cpu->env;
9172         unsigned int pamax = arm_pamax(cpu);
9173
9174         switch (stride) {
9175         case 13: /* 64KB Pages.  */
9176             if (level == 0 || (level == 1 && pamax <= 42)) {
9177                 return false;
9178             }
9179             break;
9180         case 11: /* 16KB Pages.  */
9181             if (level == 0 || (level == 1 && pamax <= 40)) {
9182                 return false;
9183             }
9184             break;
9185         case 9: /* 4KB Pages.  */
9186             if (level == 0 && pamax <= 42) {
9187                 return false;
9188             }
9189             break;
9190         default:
9191             g_assert_not_reached();
9192         }
9193
9194         /* Inputsize checks.  */
9195         if (inputsize > pamax &&
9196             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
9197             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
9198             return false;
9199         }
9200     } else {
9201         /* AArch32 only supports 4KB pages. Assert on that.  */
9202         assert(stride == 9);
9203
9204         if (level == 0) {
9205             return false;
9206         }
9207     }
9208     return true;
9209 }
9210
9211 /* Translate from the 4-bit stage 2 representation of
9212  * memory attributes (without cache-allocation hints) to
9213  * the 8-bit representation of the stage 1 MAIR registers
9214  * (which includes allocation hints).
9215  *
9216  * ref: shared/translation/attrs/S2AttrDecode()
9217  *      .../S2ConvertAttrsHints()
9218  */
9219 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
9220 {
9221     uint8_t hiattr = extract32(s2attrs, 2, 2);
9222     uint8_t loattr = extract32(s2attrs, 0, 2);
9223     uint8_t hihint = 0, lohint = 0;
9224
9225     if (hiattr != 0) { /* normal memory */
9226         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
9227             hiattr = loattr = 1; /* non-cacheable */
9228         } else {
9229             if (hiattr != 1) { /* Write-through or write-back */
9230                 hihint = 3; /* RW allocate */
9231             }
9232             if (loattr != 1) { /* Write-through or write-back */
9233                 lohint = 3; /* RW allocate */
9234             }
9235         }
9236     }
9237
9238     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
9239 }
9240
9241 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
9242                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
9243                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
9244                                target_ulong *page_size_ptr,
9245                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
9246 {
9247     ARMCPU *cpu = arm_env_get_cpu(env);
9248     CPUState *cs = CPU(cpu);
9249     /* Read an LPAE long-descriptor translation table. */
9250     ARMFaultType fault_type = ARMFault_Translation;
9251     uint32_t level;
9252     uint32_t epd = 0;
9253     int32_t t0sz, t1sz;
9254     uint32_t tg;
9255     uint64_t ttbr;
9256     int ttbr_select;
9257     hwaddr descaddr, indexmask, indexmask_grainsize;
9258     uint32_t tableattrs;
9259     target_ulong page_size;
9260     uint32_t attrs;
9261     int32_t stride = 9;
9262     int32_t addrsize;
9263     int inputsize;
9264     int32_t tbi = 0;
9265     TCR *tcr = regime_tcr(env, mmu_idx);
9266     int ap, ns, xn, pxn;
9267     uint32_t el = regime_el(env, mmu_idx);
9268     bool ttbr1_valid = true;
9269     uint64_t descaddrmask;
9270     bool aarch64 = arm_el_is_aa64(env, el);
9271
9272     /* TODO:
9273      * This code does not handle the different format TCR for VTCR_EL2.
9274      * This code also does not support shareability levels.
9275      * Attribute and permission bit handling should also be checked when adding
9276      * support for those page table walks.
9277      */
9278     if (aarch64) {
9279         level = 0;
9280         addrsize = 64;
9281         if (el > 1) {
9282             if (mmu_idx != ARMMMUIdx_S2NS) {
9283                 tbi = extract64(tcr->raw_tcr, 20, 1);
9284             }
9285         } else {
9286             if (extract64(address, 55, 1)) {
9287                 tbi = extract64(tcr->raw_tcr, 38, 1);
9288             } else {
9289                 tbi = extract64(tcr->raw_tcr, 37, 1);
9290             }
9291         }
9292         tbi *= 8;
9293
9294         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
9295          * invalid.
9296          */
9297         if (el > 1) {
9298             ttbr1_valid = false;
9299         }
9300     } else {
9301         level = 1;
9302         addrsize = 32;
9303         /* There is no TTBR1 for EL2 */
9304         if (el == 2) {
9305             ttbr1_valid = false;
9306         }
9307     }
9308
9309     /* Determine whether this address is in the region controlled by
9310      * TTBR0 or TTBR1 (or if it is in neither region and should fault).
9311      * This is a Non-secure PL0/1 stage 1 translation, so controlled by
9312      * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:
9313      */
9314     if (aarch64) {
9315         /* AArch64 translation.  */
9316         t0sz = extract32(tcr->raw_tcr, 0, 6);
9317         t0sz = MIN(t0sz, 39);
9318         t0sz = MAX(t0sz, 16);
9319     } else if (mmu_idx != ARMMMUIdx_S2NS) {
9320         /* AArch32 stage 1 translation.  */
9321         t0sz = extract32(tcr->raw_tcr, 0, 3);
9322     } else {
9323         /* AArch32 stage 2 translation.  */
9324         bool sext = extract32(tcr->raw_tcr, 4, 1);
9325         bool sign = extract32(tcr->raw_tcr, 3, 1);
9326         /* Address size is 40-bit for a stage 2 translation,
9327          * and t0sz can be negative (from -8 to 7),
9328          * so we need to adjust it to use the TTBR selecting logic below.
9329          */
9330         addrsize = 40;
9331         t0sz = sextract32(tcr->raw_tcr, 0, 4) + 8;
9332
9333         /* If the sign-extend bit is not the same as t0sz[3], the result
9334          * is unpredictable. Flag this as a guest error.  */
9335         if (sign != sext) {
9336             qemu_log_mask(LOG_GUEST_ERROR,
9337                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
9338         }
9339     }
9340     t1sz = extract32(tcr->raw_tcr, 16, 6);
9341     if (aarch64) {
9342         t1sz = MIN(t1sz, 39);
9343         t1sz = MAX(t1sz, 16);
9344     }
9345     if (t0sz && !extract64(address, addrsize - t0sz, t0sz - tbi)) {
9346         /* there is a ttbr0 region and we are in it (high bits all zero) */
9347         ttbr_select = 0;
9348     } else if (ttbr1_valid && t1sz &&
9349                !extract64(~address, addrsize - t1sz, t1sz - tbi)) {
9350         /* there is a ttbr1 region and we are in it (high bits all one) */
9351         ttbr_select = 1;
9352     } else if (!t0sz) {
9353         /* ttbr0 region is "everything not in the ttbr1 region" */
9354         ttbr_select = 0;
9355     } else if (!t1sz && ttbr1_valid) {
9356         /* ttbr1 region is "everything not in the ttbr0 region" */
9357         ttbr_select = 1;
9358     } else {
9359         /* in the gap between the two regions, this is a Translation fault */
9360         fault_type = ARMFault_Translation;
9361         goto do_fault;
9362     }
9363
9364     /* Note that QEMU ignores shareability and cacheability attributes,
9365      * so we don't need to do anything with the SH, ORGN, IRGN fields
9366      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
9367      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
9368      * implement any ASID-like capability so we can ignore it (instead
9369      * we will always flush the TLB any time the ASID is changed).
9370      */
9371     if (ttbr_select == 0) {
9372         ttbr = regime_ttbr(env, mmu_idx, 0);
9373         if (el < 2) {
9374             epd = extract32(tcr->raw_tcr, 7, 1);
9375         }
9376         inputsize = addrsize - t0sz;
9377
9378         tg = extract32(tcr->raw_tcr, 14, 2);
9379         if (tg == 1) { /* 64KB pages */
9380             stride = 13;
9381         }
9382         if (tg == 2) { /* 16KB pages */
9383             stride = 11;
9384         }
9385     } else {
9386         /* We should only be here if TTBR1 is valid */
9387         assert(ttbr1_valid);
9388
9389         ttbr = regime_ttbr(env, mmu_idx, 1);
9390         epd = extract32(tcr->raw_tcr, 23, 1);
9391         inputsize = addrsize - t1sz;
9392
9393         tg = extract32(tcr->raw_tcr, 30, 2);
9394         if (tg == 3)  { /* 64KB pages */
9395             stride = 13;
9396         }
9397         if (tg == 1) { /* 16KB pages */
9398             stride = 11;
9399         }
9400     }
9401
9402     /* Here we should have set up all the parameters for the translation:
9403      * inputsize, ttbr, epd, stride, tbi
9404      */
9405
9406     if (epd) {
9407         /* Translation table walk disabled => Translation fault on TLB miss
9408          * Note: This is always 0 on 64-bit EL2 and EL3.
9409          */
9410         goto do_fault;
9411     }
9412
9413     if (mmu_idx != ARMMMUIdx_S2NS) {
9414         /* The starting level depends on the virtual address size (which can
9415          * be up to 48 bits) and the translation granule size. It indicates
9416          * the number of strides (stride bits at a time) needed to
9417          * consume the bits of the input address. In the pseudocode this is:
9418          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
9419          * where their 'inputsize' is our 'inputsize', 'grainsize' is
9420          * our 'stride + 3' and 'stride' is our 'stride'.
9421          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
9422          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
9423          * = 4 - (inputsize - 4) / stride;
9424          */
9425         level = 4 - (inputsize - 4) / stride;
9426     } else {
9427         /* For stage 2 translations the starting level is specified by the
9428          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
9429          */
9430         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
9431         uint32_t startlevel;
9432         bool ok;
9433
9434         if (!aarch64 || stride == 9) {
9435             /* AArch32 or 4KB pages */
9436             startlevel = 2 - sl0;
9437         } else {
9438             /* 16KB or 64KB pages */
9439             startlevel = 3 - sl0;
9440         }
9441
9442         /* Check that the starting level is valid. */
9443         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
9444                                 inputsize, stride);
9445         if (!ok) {
9446             fault_type = ARMFault_Translation;
9447             goto do_fault;
9448         }
9449         level = startlevel;
9450     }
9451
9452     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
9453     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
9454
9455     /* Now we can extract the actual base address from the TTBR */
9456     descaddr = extract64(ttbr, 0, 48);
9457     descaddr &= ~indexmask;
9458
9459     /* The address field in the descriptor goes up to bit 39 for ARMv7
9460      * but up to bit 47 for ARMv8, but we use the descaddrmask
9461      * up to bit 39 for AArch32, because we don't need other bits in that case
9462      * to construct next descriptor address (anyway they should be all zeroes).
9463      */
9464     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
9465                    ~indexmask_grainsize;
9466
9467     /* Secure accesses start with the page table in secure memory and
9468      * can be downgraded to non-secure at any step. Non-secure accesses
9469      * remain non-secure. We implement this by just ORing in the NSTable/NS
9470      * bits at each step.
9471      */
9472     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
9473     for (;;) {
9474         uint64_t descriptor;
9475         bool nstable;
9476
9477         descaddr |= (address >> (stride * (4 - level))) & indexmask;
9478         descaddr &= ~7ULL;
9479         nstable = extract32(tableattrs, 4, 1);
9480         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
9481         if (fi->type != ARMFault_None) {
9482             goto do_fault;
9483         }
9484
9485         if (!(descriptor & 1) ||
9486             (!(descriptor & 2) && (level == 3))) {
9487             /* Invalid, or the Reserved level 3 encoding */
9488             goto do_fault;
9489         }
9490         descaddr = descriptor & descaddrmask;
9491
9492         if ((descriptor & 2) && (level < 3)) {
9493             /* Table entry. The top five bits are attributes which  may
9494              * propagate down through lower levels of the table (and
9495              * which are all arranged so that 0 means "no effect", so
9496              * we can gather them up by ORing in the bits at each level).
9497              */
9498             tableattrs |= extract64(descriptor, 59, 5);
9499             level++;
9500             indexmask = indexmask_grainsize;
9501             continue;
9502         }
9503         /* Block entry at level 1 or 2, or page entry at level 3.
9504          * These are basically the same thing, although the number
9505          * of bits we pull in from the vaddr varies.
9506          */
9507         page_size = (1ULL << ((stride * (4 - level)) + 3));
9508         descaddr |= (address & (page_size - 1));
9509         /* Extract attributes from the descriptor */
9510         attrs = extract64(descriptor, 2, 10)
9511             | (extract64(descriptor, 52, 12) << 10);
9512
9513         if (mmu_idx == ARMMMUIdx_S2NS) {
9514             /* Stage 2 table descriptors do not include any attribute fields */
9515             break;
9516         }
9517         /* Merge in attributes from table descriptors */
9518         attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */
9519         attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */
9520         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
9521          * means "force PL1 access only", which means forcing AP[1] to 0.
9522          */
9523         if (extract32(tableattrs, 2, 1)) {
9524             attrs &= ~(1 << 4);
9525         }
9526         attrs |= nstable << 3; /* NS */
9527         break;
9528     }
9529     /* Here descaddr is the final physical address, and attributes
9530      * are all in attrs.
9531      */
9532     fault_type = ARMFault_AccessFlag;
9533     if ((attrs & (1 << 8)) == 0) {
9534         /* Access flag */
9535         goto do_fault;
9536     }
9537
9538     ap = extract32(attrs, 4, 2);
9539     xn = extract32(attrs, 12, 1);
9540
9541     if (mmu_idx == ARMMMUIdx_S2NS) {
9542         ns = true;
9543         *prot = get_S2prot(env, ap, xn);
9544     } else {
9545         ns = extract32(attrs, 3, 1);
9546         pxn = extract32(attrs, 11, 1);
9547         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
9548     }
9549
9550     fault_type = ARMFault_Permission;
9551     if (!(*prot & (1 << access_type))) {
9552         goto do_fault;
9553     }
9554
9555     if (ns) {
9556         /* The NS bit will (as required by the architecture) have no effect if
9557          * the CPU doesn't support TZ or this is a non-secure translation
9558          * regime, because the attribute will already be non-secure.
9559          */
9560         txattrs->secure = false;
9561     }
9562
9563     if (cacheattrs != NULL) {
9564         if (mmu_idx == ARMMMUIdx_S2NS) {
9565             cacheattrs->attrs = convert_stage2_attrs(env,
9566                                                      extract32(attrs, 0, 4));
9567         } else {
9568             /* Index into MAIR registers for cache attributes */
9569             uint8_t attrindx = extract32(attrs, 0, 3);
9570             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
9571             assert(attrindx <= 7);
9572             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
9573         }
9574         cacheattrs->shareability = extract32(attrs, 6, 2);
9575     }
9576
9577     *phys_ptr = descaddr;
9578     *page_size_ptr = page_size;
9579     return false;
9580
9581 do_fault:
9582     fi->type = fault_type;
9583     fi->level = level;
9584     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
9585     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
9586     return true;
9587 }
9588
9589 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
9590                                                 ARMMMUIdx mmu_idx,
9591                                                 int32_t address, int *prot)
9592 {
9593     if (!arm_feature(env, ARM_FEATURE_M)) {
9594         *prot = PAGE_READ | PAGE_WRITE;
9595         switch (address) {
9596         case 0xF0000000 ... 0xFFFFFFFF:
9597             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
9598                 /* hivecs execing is ok */
9599                 *prot |= PAGE_EXEC;
9600             }
9601             break;
9602         case 0x00000000 ... 0x7FFFFFFF:
9603             *prot |= PAGE_EXEC;
9604             break;
9605         }
9606     } else {
9607         /* Default system address map for M profile cores.
9608          * The architecture specifies which regions are execute-never;
9609          * at the MPU level no other checks are defined.
9610          */
9611         switch (address) {
9612         case 0x00000000 ... 0x1fffffff: /* ROM */
9613         case 0x20000000 ... 0x3fffffff: /* SRAM */
9614         case 0x60000000 ... 0x7fffffff: /* RAM */
9615         case 0x80000000 ... 0x9fffffff: /* RAM */
9616             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9617             break;
9618         case 0x40000000 ... 0x5fffffff: /* Peripheral */
9619         case 0xa0000000 ... 0xbfffffff: /* Device */
9620         case 0xc0000000 ... 0xdfffffff: /* Device */
9621         case 0xe0000000 ... 0xffffffff: /* System */
9622             *prot = PAGE_READ | PAGE_WRITE;
9623             break;
9624         default:
9625             g_assert_not_reached();
9626         }
9627     }
9628 }
9629
9630 static bool pmsav7_use_background_region(ARMCPU *cpu,
9631                                          ARMMMUIdx mmu_idx, bool is_user)
9632 {
9633     /* Return true if we should use the default memory map as a
9634      * "background" region if there are no hits against any MPU regions.
9635      */
9636     CPUARMState *env = &cpu->env;
9637
9638     if (is_user) {
9639         return false;
9640     }
9641
9642     if (arm_feature(env, ARM_FEATURE_M)) {
9643         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
9644             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
9645     } else {
9646         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
9647     }
9648 }
9649
9650 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
9651 {
9652     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
9653     return arm_feature(env, ARM_FEATURE_M) &&
9654         extract32(address, 20, 12) == 0xe00;
9655 }
9656
9657 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
9658 {
9659     /* True if address is in the M profile system region
9660      * 0xe0000000 - 0xffffffff
9661      */
9662     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
9663 }
9664
9665 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
9666                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9667                                  hwaddr *phys_ptr, int *prot,
9668                                  target_ulong *page_size,
9669                                  ARMMMUFaultInfo *fi)
9670 {
9671     ARMCPU *cpu = arm_env_get_cpu(env);
9672     int n;
9673     bool is_user = regime_is_user(env, mmu_idx);
9674
9675     *phys_ptr = address;
9676     *page_size = TARGET_PAGE_SIZE;
9677     *prot = 0;
9678
9679     if (regime_translation_disabled(env, mmu_idx) ||
9680         m_is_ppb_region(env, address)) {
9681         /* MPU disabled or M profile PPB access: use default memory map.
9682          * The other case which uses the default memory map in the
9683          * v7M ARM ARM pseudocode is exception vector reads from the vector
9684          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
9685          * which always does a direct read using address_space_ldl(), rather
9686          * than going via this function, so we don't need to check that here.
9687          */
9688         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9689     } else { /* MPU enabled */
9690         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9691             /* region search */
9692             uint32_t base = env->pmsav7.drbar[n];
9693             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
9694             uint32_t rmask;
9695             bool srdis = false;
9696
9697             if (!(env->pmsav7.drsr[n] & 0x1)) {
9698                 continue;
9699             }
9700
9701             if (!rsize) {
9702                 qemu_log_mask(LOG_GUEST_ERROR,
9703                               "DRSR[%d]: Rsize field cannot be 0\n", n);
9704                 continue;
9705             }
9706             rsize++;
9707             rmask = (1ull << rsize) - 1;
9708
9709             if (base & rmask) {
9710                 qemu_log_mask(LOG_GUEST_ERROR,
9711                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
9712                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
9713                               n, base, rmask);
9714                 continue;
9715             }
9716
9717             if (address < base || address > base + rmask) {
9718                 /*
9719                  * Address not in this region. We must check whether the
9720                  * region covers addresses in the same page as our address.
9721                  * In that case we must not report a size that covers the
9722                  * whole page for a subsequent hit against a different MPU
9723                  * region or the background region, because it would result in
9724                  * incorrect TLB hits for subsequent accesses to addresses that
9725                  * are in this MPU region.
9726                  */
9727                 if (ranges_overlap(base, rmask,
9728                                    address & TARGET_PAGE_MASK,
9729                                    TARGET_PAGE_SIZE)) {
9730                     *page_size = 1;
9731                 }
9732                 continue;
9733             }
9734
9735             /* Region matched */
9736
9737             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
9738                 int i, snd;
9739                 uint32_t srdis_mask;
9740
9741                 rsize -= 3; /* sub region size (power of 2) */
9742                 snd = ((address - base) >> rsize) & 0x7;
9743                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
9744
9745                 srdis_mask = srdis ? 0x3 : 0x0;
9746                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
9747                     /* This will check in groups of 2, 4 and then 8, whether
9748                      * the subregion bits are consistent. rsize is incremented
9749                      * back up to give the region size, considering consistent
9750                      * adjacent subregions as one region. Stop testing if rsize
9751                      * is already big enough for an entire QEMU page.
9752                      */
9753                     int snd_rounded = snd & ~(i - 1);
9754                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
9755                                                      snd_rounded + 8, i);
9756                     if (srdis_mask ^ srdis_multi) {
9757                         break;
9758                     }
9759                     srdis_mask = (srdis_mask << i) | srdis_mask;
9760                     rsize++;
9761                 }
9762             }
9763             if (srdis) {
9764                 continue;
9765             }
9766             if (rsize < TARGET_PAGE_BITS) {
9767                 *page_size = 1 << rsize;
9768             }
9769             break;
9770         }
9771
9772         if (n == -1) { /* no hits */
9773             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9774                 /* background fault */
9775                 fi->type = ARMFault_Background;
9776                 return true;
9777             }
9778             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9779         } else { /* a MPU hit! */
9780             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
9781             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
9782
9783             if (m_is_system_region(env, address)) {
9784                 /* System space is always execute never */
9785                 xn = 1;
9786             }
9787
9788             if (is_user) { /* User mode AP bit decoding */
9789                 switch (ap) {
9790                 case 0:
9791                 case 1:
9792                 case 5:
9793                     break; /* no access */
9794                 case 3:
9795                     *prot |= PAGE_WRITE;
9796                     /* fall through */
9797                 case 2:
9798                 case 6:
9799                     *prot |= PAGE_READ | PAGE_EXEC;
9800                     break;
9801                 case 7:
9802                     /* for v7M, same as 6; for R profile a reserved value */
9803                     if (arm_feature(env, ARM_FEATURE_M)) {
9804                         *prot |= PAGE_READ | PAGE_EXEC;
9805                         break;
9806                     }
9807                     /* fall through */
9808                 default:
9809                     qemu_log_mask(LOG_GUEST_ERROR,
9810                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9811                                   PRIx32 "\n", n, ap);
9812                 }
9813             } else { /* Priv. mode AP bits decoding */
9814                 switch (ap) {
9815                 case 0:
9816                     break; /* no access */
9817                 case 1:
9818                 case 2:
9819                 case 3:
9820                     *prot |= PAGE_WRITE;
9821                     /* fall through */
9822                 case 5:
9823                 case 6:
9824                     *prot |= PAGE_READ | PAGE_EXEC;
9825                     break;
9826                 case 7:
9827                     /* for v7M, same as 6; for R profile a reserved value */
9828                     if (arm_feature(env, ARM_FEATURE_M)) {
9829                         *prot |= PAGE_READ | PAGE_EXEC;
9830                         break;
9831                     }
9832                     /* fall through */
9833                 default:
9834                     qemu_log_mask(LOG_GUEST_ERROR,
9835                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9836                                   PRIx32 "\n", n, ap);
9837                 }
9838             }
9839
9840             /* execute never */
9841             if (xn) {
9842                 *prot &= ~PAGE_EXEC;
9843             }
9844         }
9845     }
9846
9847     fi->type = ARMFault_Permission;
9848     fi->level = 1;
9849     return !(*prot & (1 << access_type));
9850 }
9851
9852 static bool v8m_is_sau_exempt(CPUARMState *env,
9853                               uint32_t address, MMUAccessType access_type)
9854 {
9855     /* The architecture specifies that certain address ranges are
9856      * exempt from v8M SAU/IDAU checks.
9857      */
9858     return
9859         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
9860         (address >= 0xe0000000 && address <= 0xe0002fff) ||
9861         (address >= 0xe000e000 && address <= 0xe000efff) ||
9862         (address >= 0xe002e000 && address <= 0xe002efff) ||
9863         (address >= 0xe0040000 && address <= 0xe0041fff) ||
9864         (address >= 0xe00ff000 && address <= 0xe00fffff);
9865 }
9866
9867 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
9868                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
9869                                 V8M_SAttributes *sattrs)
9870 {
9871     /* Look up the security attributes for this address. Compare the
9872      * pseudocode SecurityCheck() function.
9873      * We assume the caller has zero-initialized *sattrs.
9874      */
9875     ARMCPU *cpu = arm_env_get_cpu(env);
9876     int r;
9877     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
9878     int idau_region = IREGION_NOTVALID;
9879     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
9880     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
9881
9882     if (cpu->idau) {
9883         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
9884         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
9885
9886         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
9887                    &idau_nsc);
9888     }
9889
9890     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
9891         /* 0xf0000000..0xffffffff is always S for insn fetches */
9892         return;
9893     }
9894
9895     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
9896         sattrs->ns = !regime_is_secure(env, mmu_idx);
9897         return;
9898     }
9899
9900     if (idau_region != IREGION_NOTVALID) {
9901         sattrs->irvalid = true;
9902         sattrs->iregion = idau_region;
9903     }
9904
9905     switch (env->sau.ctrl & 3) {
9906     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
9907         break;
9908     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
9909         sattrs->ns = true;
9910         break;
9911     default: /* SAU.ENABLE == 1 */
9912         for (r = 0; r < cpu->sau_sregion; r++) {
9913             if (env->sau.rlar[r] & 1) {
9914                 uint32_t base = env->sau.rbar[r] & ~0x1f;
9915                 uint32_t limit = env->sau.rlar[r] | 0x1f;
9916
9917                 if (base <= address && limit >= address) {
9918                     if (base > addr_page_base || limit < addr_page_limit) {
9919                         sattrs->subpage = true;
9920                     }
9921                     if (sattrs->srvalid) {
9922                         /* If we hit in more than one region then we must report
9923                          * as Secure, not NS-Callable, with no valid region
9924                          * number info.
9925                          */
9926                         sattrs->ns = false;
9927                         sattrs->nsc = false;
9928                         sattrs->sregion = 0;
9929                         sattrs->srvalid = false;
9930                         break;
9931                     } else {
9932                         if (env->sau.rlar[r] & 2) {
9933                             sattrs->nsc = true;
9934                         } else {
9935                             sattrs->ns = true;
9936                         }
9937                         sattrs->srvalid = true;
9938                         sattrs->sregion = r;
9939                     }
9940                 } else {
9941                     /*
9942                      * Address not in this region. We must check whether the
9943                      * region covers addresses in the same page as our address.
9944                      * In that case we must not report a size that covers the
9945                      * whole page for a subsequent hit against a different MPU
9946                      * region or the background region, because it would result
9947                      * in incorrect TLB hits for subsequent accesses to
9948                      * addresses that are in this MPU region.
9949                      */
9950                     if (limit >= base &&
9951                         ranges_overlap(base, limit - base + 1,
9952                                        addr_page_base,
9953                                        TARGET_PAGE_SIZE)) {
9954                         sattrs->subpage = true;
9955                     }
9956                 }
9957             }
9958         }
9959
9960         /* The IDAU will override the SAU lookup results if it specifies
9961          * higher security than the SAU does.
9962          */
9963         if (!idau_ns) {
9964             if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
9965                 sattrs->ns = false;
9966                 sattrs->nsc = idau_nsc;
9967             }
9968         }
9969         break;
9970     }
9971 }
9972
9973 static bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
9974                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
9975                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
9976                               int *prot, bool *is_subpage,
9977                               ARMMMUFaultInfo *fi, uint32_t *mregion)
9978 {
9979     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
9980      * that a full phys-to-virt translation does).
9981      * mregion is (if not NULL) set to the region number which matched,
9982      * or -1 if no region number is returned (MPU off, address did not
9983      * hit a region, address hit in multiple regions).
9984      * We set is_subpage to true if the region hit doesn't cover the
9985      * entire TARGET_PAGE the address is within.
9986      */
9987     ARMCPU *cpu = arm_env_get_cpu(env);
9988     bool is_user = regime_is_user(env, mmu_idx);
9989     uint32_t secure = regime_is_secure(env, mmu_idx);
9990     int n;
9991     int matchregion = -1;
9992     bool hit = false;
9993     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
9994     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
9995
9996     *is_subpage = false;
9997     *phys_ptr = address;
9998     *prot = 0;
9999     if (mregion) {
10000         *mregion = -1;
10001     }
10002
10003     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
10004      * was an exception vector read from the vector table (which is always
10005      * done using the default system address map), because those accesses
10006      * are done in arm_v7m_load_vector(), which always does a direct
10007      * read using address_space_ldl(), rather than going via this function.
10008      */
10009     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
10010         hit = true;
10011     } else if (m_is_ppb_region(env, address)) {
10012         hit = true;
10013     } else if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
10014         hit = true;
10015     } else {
10016         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
10017             /* region search */
10018             /* Note that the base address is bits [31:5] from the register
10019              * with bits [4:0] all zeroes, but the limit address is bits
10020              * [31:5] from the register with bits [4:0] all ones.
10021              */
10022             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
10023             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
10024
10025             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
10026                 /* Region disabled */
10027                 continue;
10028             }
10029
10030             if (address < base || address > limit) {
10031                 /*
10032                  * Address not in this region. We must check whether the
10033                  * region covers addresses in the same page as our address.
10034                  * In that case we must not report a size that covers the
10035                  * whole page for a subsequent hit against a different MPU
10036                  * region or the background region, because it would result in
10037                  * incorrect TLB hits for subsequent accesses to addresses that
10038                  * are in this MPU region.
10039                  */
10040                 if (limit >= base &&
10041                     ranges_overlap(base, limit - base + 1,
10042                                    addr_page_base,
10043                                    TARGET_PAGE_SIZE)) {
10044                     *is_subpage = true;
10045                 }
10046                 continue;
10047             }
10048
10049             if (base > addr_page_base || limit < addr_page_limit) {
10050                 *is_subpage = true;
10051             }
10052
10053             if (hit) {
10054                 /* Multiple regions match -- always a failure (unlike
10055                  * PMSAv7 where highest-numbered-region wins)
10056                  */
10057                 fi->type = ARMFault_Permission;
10058                 fi->level = 1;
10059                 return true;
10060             }
10061
10062             matchregion = n;
10063             hit = true;
10064         }
10065     }
10066
10067     if (!hit) {
10068         /* background fault */
10069         fi->type = ARMFault_Background;
10070         return true;
10071     }
10072
10073     if (matchregion == -1) {
10074         /* hit using the background region */
10075         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
10076     } else {
10077         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
10078         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
10079
10080         if (m_is_system_region(env, address)) {
10081             /* System space is always execute never */
10082             xn = 1;
10083         }
10084
10085         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
10086         if (*prot && !xn) {
10087             *prot |= PAGE_EXEC;
10088         }
10089         /* We don't need to look the attribute up in the MAIR0/MAIR1
10090          * registers because that only tells us about cacheability.
10091          */
10092         if (mregion) {
10093             *mregion = matchregion;
10094         }
10095     }
10096
10097     fi->type = ARMFault_Permission;
10098     fi->level = 1;
10099     return !(*prot & (1 << access_type));
10100 }
10101
10102
10103 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
10104                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10105                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
10106                                  int *prot, target_ulong *page_size,
10107                                  ARMMMUFaultInfo *fi)
10108 {
10109     uint32_t secure = regime_is_secure(env, mmu_idx);
10110     V8M_SAttributes sattrs = {};
10111     bool ret;
10112     bool mpu_is_subpage;
10113
10114     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10115         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
10116         if (access_type == MMU_INST_FETCH) {
10117             /* Instruction fetches always use the MMU bank and the
10118              * transaction attribute determined by the fetch address,
10119              * regardless of CPU state. This is painful for QEMU
10120              * to handle, because it would mean we need to encode
10121              * into the mmu_idx not just the (user, negpri) information
10122              * for the current security state but also that for the
10123              * other security state, which would balloon the number
10124              * of mmu_idx values needed alarmingly.
10125              * Fortunately we can avoid this because it's not actually
10126              * possible to arbitrarily execute code from memory with
10127              * the wrong security attribute: it will always generate
10128              * an exception of some kind or another, apart from the
10129              * special case of an NS CPU executing an SG instruction
10130              * in S&NSC memory. So we always just fail the translation
10131              * here and sort things out in the exception handler
10132              * (including possibly emulating an SG instruction).
10133              */
10134             if (sattrs.ns != !secure) {
10135                 if (sattrs.nsc) {
10136                     fi->type = ARMFault_QEMU_NSCExec;
10137                 } else {
10138                     fi->type = ARMFault_QEMU_SFault;
10139                 }
10140                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10141                 *phys_ptr = address;
10142                 *prot = 0;
10143                 return true;
10144             }
10145         } else {
10146             /* For data accesses we always use the MMU bank indicated
10147              * by the current CPU state, but the security attributes
10148              * might downgrade a secure access to nonsecure.
10149              */
10150             if (sattrs.ns) {
10151                 txattrs->secure = false;
10152             } else if (!secure) {
10153                 /* NS access to S memory must fault.
10154                  * Architecturally we should first check whether the
10155                  * MPU information for this address indicates that we
10156                  * are doing an unaligned access to Device memory, which
10157                  * should generate a UsageFault instead. QEMU does not
10158                  * currently check for that kind of unaligned access though.
10159                  * If we added it we would need to do so as a special case
10160                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
10161                  */
10162                 fi->type = ARMFault_QEMU_SFault;
10163                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10164                 *phys_ptr = address;
10165                 *prot = 0;
10166                 return true;
10167             }
10168         }
10169     }
10170
10171     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
10172                             txattrs, prot, &mpu_is_subpage, fi, NULL);
10173     /*
10174      * TODO: this is a temporary hack to ignore the fact that the SAU region
10175      * is smaller than a page if this is an executable region. We never
10176      * supported small MPU regions, but we did (accidentally) allow small
10177      * SAU regions, and if we now made small SAU regions not be executable
10178      * then this would break previously working guest code. We can't
10179      * remove this until/unless we implement support for execution from
10180      * small regions.
10181      */
10182     if (*prot & PAGE_EXEC) {
10183         sattrs.subpage = false;
10184     }
10185     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
10186     return ret;
10187 }
10188
10189 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
10190                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10191                                  hwaddr *phys_ptr, int *prot,
10192                                  ARMMMUFaultInfo *fi)
10193 {
10194     int n;
10195     uint32_t mask;
10196     uint32_t base;
10197     bool is_user = regime_is_user(env, mmu_idx);
10198
10199     if (regime_translation_disabled(env, mmu_idx)) {
10200         /* MPU disabled.  */
10201         *phys_ptr = address;
10202         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10203         return false;
10204     }
10205
10206     *phys_ptr = address;
10207     for (n = 7; n >= 0; n--) {
10208         base = env->cp15.c6_region[n];
10209         if ((base & 1) == 0) {
10210             continue;
10211         }
10212         mask = 1 << ((base >> 1) & 0x1f);
10213         /* Keep this shift separate from the above to avoid an
10214            (undefined) << 32.  */
10215         mask = (mask << 1) - 1;
10216         if (((base ^ address) & ~mask) == 0) {
10217             break;
10218         }
10219     }
10220     if (n < 0) {
10221         fi->type = ARMFault_Background;
10222         return true;
10223     }
10224
10225     if (access_type == MMU_INST_FETCH) {
10226         mask = env->cp15.pmsav5_insn_ap;
10227     } else {
10228         mask = env->cp15.pmsav5_data_ap;
10229     }
10230     mask = (mask >> (n * 4)) & 0xf;
10231     switch (mask) {
10232     case 0:
10233         fi->type = ARMFault_Permission;
10234         fi->level = 1;
10235         return true;
10236     case 1:
10237         if (is_user) {
10238             fi->type = ARMFault_Permission;
10239             fi->level = 1;
10240             return true;
10241         }
10242         *prot = PAGE_READ | PAGE_WRITE;
10243         break;
10244     case 2:
10245         *prot = PAGE_READ;
10246         if (!is_user) {
10247             *prot |= PAGE_WRITE;
10248         }
10249         break;
10250     case 3:
10251         *prot = PAGE_READ | PAGE_WRITE;
10252         break;
10253     case 5:
10254         if (is_user) {
10255             fi->type = ARMFault_Permission;
10256             fi->level = 1;
10257             return true;
10258         }
10259         *prot = PAGE_READ;
10260         break;
10261     case 6:
10262         *prot = PAGE_READ;
10263         break;
10264     default:
10265         /* Bad permission.  */
10266         fi->type = ARMFault_Permission;
10267         fi->level = 1;
10268         return true;
10269     }
10270     *prot |= PAGE_EXEC;
10271     return false;
10272 }
10273
10274 /* Combine either inner or outer cacheability attributes for normal
10275  * memory, according to table D4-42 and pseudocode procedure
10276  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
10277  *
10278  * NB: only stage 1 includes allocation hints (RW bits), leading to
10279  * some asymmetry.
10280  */
10281 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
10282 {
10283     if (s1 == 4 || s2 == 4) {
10284         /* non-cacheable has precedence */
10285         return 4;
10286     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
10287         /* stage 1 write-through takes precedence */
10288         return s1;
10289     } else if (extract32(s2, 2, 2) == 2) {
10290         /* stage 2 write-through takes precedence, but the allocation hint
10291          * is still taken from stage 1
10292          */
10293         return (2 << 2) | extract32(s1, 0, 2);
10294     } else { /* write-back */
10295         return s1;
10296     }
10297 }
10298
10299 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
10300  * and CombineS1S2Desc()
10301  *
10302  * @s1:      Attributes from stage 1 walk
10303  * @s2:      Attributes from stage 2 walk
10304  */
10305 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
10306 {
10307     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
10308     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
10309     ARMCacheAttrs ret;
10310
10311     /* Combine shareability attributes (table D4-43) */
10312     if (s1.shareability == 2 || s2.shareability == 2) {
10313         /* if either are outer-shareable, the result is outer-shareable */
10314         ret.shareability = 2;
10315     } else if (s1.shareability == 3 || s2.shareability == 3) {
10316         /* if either are inner-shareable, the result is inner-shareable */
10317         ret.shareability = 3;
10318     } else {
10319         /* both non-shareable */
10320         ret.shareability = 0;
10321     }
10322
10323     /* Combine memory type and cacheability attributes */
10324     if (s1hi == 0 || s2hi == 0) {
10325         /* Device has precedence over normal */
10326         if (s1lo == 0 || s2lo == 0) {
10327             /* nGnRnE has precedence over anything */
10328             ret.attrs = 0;
10329         } else if (s1lo == 4 || s2lo == 4) {
10330             /* non-Reordering has precedence over Reordering */
10331             ret.attrs = 4;  /* nGnRE */
10332         } else if (s1lo == 8 || s2lo == 8) {
10333             /* non-Gathering has precedence over Gathering */
10334             ret.attrs = 8;  /* nGRE */
10335         } else {
10336             ret.attrs = 0xc; /* GRE */
10337         }
10338
10339         /* Any location for which the resultant memory type is any
10340          * type of Device memory is always treated as Outer Shareable.
10341          */
10342         ret.shareability = 2;
10343     } else { /* Normal memory */
10344         /* Outer/inner cacheability combine independently */
10345         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
10346                   | combine_cacheattr_nibble(s1lo, s2lo);
10347
10348         if (ret.attrs == 0x44) {
10349             /* Any location for which the resultant memory type is Normal
10350              * Inner Non-cacheable, Outer Non-cacheable is always treated
10351              * as Outer Shareable.
10352              */
10353             ret.shareability = 2;
10354         }
10355     }
10356
10357     return ret;
10358 }
10359
10360
10361 /* get_phys_addr - get the physical address for this virtual address
10362  *
10363  * Find the physical address corresponding to the given virtual address,
10364  * by doing a translation table walk on MMU based systems or using the
10365  * MPU state on MPU based systems.
10366  *
10367  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
10368  * prot and page_size may not be filled in, and the populated fsr value provides
10369  * information on why the translation aborted, in the format of a
10370  * DFSR/IFSR fault register, with the following caveats:
10371  *  * we honour the short vs long DFSR format differences.
10372  *  * the WnR bit is never set (the caller must do this).
10373  *  * for PSMAv5 based systems we don't bother to return a full FSR format
10374  *    value.
10375  *
10376  * @env: CPUARMState
10377  * @address: virtual address to get physical address for
10378  * @access_type: 0 for read, 1 for write, 2 for execute
10379  * @mmu_idx: MMU index indicating required translation regime
10380  * @phys_ptr: set to the physical address corresponding to the virtual address
10381  * @attrs: set to the memory transaction attributes to use
10382  * @prot: set to the permissions for the page containing phys_ptr
10383  * @page_size: set to the size of the page containing phys_ptr
10384  * @fi: set to fault info if the translation fails
10385  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
10386  */
10387 static bool get_phys_addr(CPUARMState *env, target_ulong address,
10388                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
10389                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10390                           target_ulong *page_size,
10391                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10392 {
10393     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10394         /* Call ourselves recursively to do the stage 1 and then stage 2
10395          * translations.
10396          */
10397         if (arm_feature(env, ARM_FEATURE_EL2)) {
10398             hwaddr ipa;
10399             int s2_prot;
10400             int ret;
10401             ARMCacheAttrs cacheattrs2 = {};
10402
10403             ret = get_phys_addr(env, address, access_type,
10404                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
10405                                 prot, page_size, fi, cacheattrs);
10406
10407             /* If S1 fails or S2 is disabled, return early.  */
10408             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10409                 *phys_ptr = ipa;
10410                 return ret;
10411             }
10412
10413             /* S1 is done. Now do S2 translation.  */
10414             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
10415                                      phys_ptr, attrs, &s2_prot,
10416                                      page_size, fi,
10417                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
10418             fi->s2addr = ipa;
10419             /* Combine the S1 and S2 perms.  */
10420             *prot &= s2_prot;
10421
10422             /* Combine the S1 and S2 cache attributes, if needed */
10423             if (!ret && cacheattrs != NULL) {
10424                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
10425             }
10426
10427             return ret;
10428         } else {
10429             /*
10430              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
10431              */
10432             mmu_idx = stage_1_mmu_idx(mmu_idx);
10433         }
10434     }
10435
10436     /* The page table entries may downgrade secure to non-secure, but
10437      * cannot upgrade an non-secure translation regime's attributes
10438      * to secure.
10439      */
10440     attrs->secure = regime_is_secure(env, mmu_idx);
10441     attrs->user = regime_is_user(env, mmu_idx);
10442
10443     /* Fast Context Switch Extension. This doesn't exist at all in v8.
10444      * In v7 and earlier it affects all stage 1 translations.
10445      */
10446     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
10447         && !arm_feature(env, ARM_FEATURE_V8)) {
10448         if (regime_el(env, mmu_idx) == 3) {
10449             address += env->cp15.fcseidr_s;
10450         } else {
10451             address += env->cp15.fcseidr_ns;
10452         }
10453     }
10454
10455     if (arm_feature(env, ARM_FEATURE_PMSA)) {
10456         bool ret;
10457         *page_size = TARGET_PAGE_SIZE;
10458
10459         if (arm_feature(env, ARM_FEATURE_V8)) {
10460             /* PMSAv8 */
10461             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
10462                                        phys_ptr, attrs, prot, page_size, fi);
10463         } else if (arm_feature(env, ARM_FEATURE_V7)) {
10464             /* PMSAv7 */
10465             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
10466                                        phys_ptr, prot, page_size, fi);
10467         } else {
10468             /* Pre-v7 MPU */
10469             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
10470                                        phys_ptr, prot, fi);
10471         }
10472         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
10473                       " mmu_idx %u -> %s (prot %c%c%c)\n",
10474                       access_type == MMU_DATA_LOAD ? "reading" :
10475                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
10476                       (uint32_t)address, mmu_idx,
10477                       ret ? "Miss" : "Hit",
10478                       *prot & PAGE_READ ? 'r' : '-',
10479                       *prot & PAGE_WRITE ? 'w' : '-',
10480                       *prot & PAGE_EXEC ? 'x' : '-');
10481
10482         return ret;
10483     }
10484
10485     /* Definitely a real MMU, not an MPU */
10486
10487     if (regime_translation_disabled(env, mmu_idx)) {
10488         /* MMU disabled. */
10489         *phys_ptr = address;
10490         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10491         *page_size = TARGET_PAGE_SIZE;
10492         return 0;
10493     }
10494
10495     if (regime_using_lpae_format(env, mmu_idx)) {
10496         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
10497                                   phys_ptr, attrs, prot, page_size,
10498                                   fi, cacheattrs);
10499     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
10500         return get_phys_addr_v6(env, address, access_type, mmu_idx,
10501                                 phys_ptr, attrs, prot, page_size, fi);
10502     } else {
10503         return get_phys_addr_v5(env, address, access_type, mmu_idx,
10504                                     phys_ptr, prot, page_size, fi);
10505     }
10506 }
10507
10508 /* Walk the page table and (if the mapping exists) add the page
10509  * to the TLB. Return false on success, or true on failure. Populate
10510  * fsr with ARM DFSR/IFSR fault register format value on failure.
10511  */
10512 bool arm_tlb_fill(CPUState *cs, vaddr address,
10513                   MMUAccessType access_type, int mmu_idx,
10514                   ARMMMUFaultInfo *fi)
10515 {
10516     ARMCPU *cpu = ARM_CPU(cs);
10517     CPUARMState *env = &cpu->env;
10518     hwaddr phys_addr;
10519     target_ulong page_size;
10520     int prot;
10521     int ret;
10522     MemTxAttrs attrs = {};
10523
10524     ret = get_phys_addr(env, address, access_type,
10525                         core_to_arm_mmu_idx(env, mmu_idx), &phys_addr,
10526                         &attrs, &prot, &page_size, fi, NULL);
10527     if (!ret) {
10528         /*
10529          * Map a single [sub]page. Regions smaller than our declared
10530          * target page size are handled specially, so for those we
10531          * pass in the exact addresses.
10532          */
10533         if (page_size >= TARGET_PAGE_SIZE) {
10534             phys_addr &= TARGET_PAGE_MASK;
10535             address &= TARGET_PAGE_MASK;
10536         }
10537         tlb_set_page_with_attrs(cs, address, phys_addr, attrs,
10538                                 prot, mmu_idx, page_size);
10539         return 0;
10540     }
10541
10542     return ret;
10543 }
10544
10545 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
10546                                          MemTxAttrs *attrs)
10547 {
10548     ARMCPU *cpu = ARM_CPU(cs);
10549     CPUARMState *env = &cpu->env;
10550     hwaddr phys_addr;
10551     target_ulong page_size;
10552     int prot;
10553     bool ret;
10554     ARMMMUFaultInfo fi = {};
10555     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
10556
10557     *attrs = (MemTxAttrs) {};
10558
10559     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
10560                         attrs, &prot, &page_size, &fi, NULL);
10561
10562     if (ret) {
10563         return -1;
10564     }
10565     return phys_addr;
10566 }
10567
10568 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
10569 {
10570     uint32_t mask;
10571     unsigned el = arm_current_el(env);
10572
10573     /* First handle registers which unprivileged can read */
10574
10575     switch (reg) {
10576     case 0 ... 7: /* xPSR sub-fields */
10577         mask = 0;
10578         if ((reg & 1) && el) {
10579             mask |= XPSR_EXCP; /* IPSR (unpriv. reads as zero) */
10580         }
10581         if (!(reg & 4)) {
10582             mask |= XPSR_NZCV | XPSR_Q; /* APSR */
10583         }
10584         /* EPSR reads as zero */
10585         return xpsr_read(env) & mask;
10586         break;
10587     case 20: /* CONTROL */
10588         return env->v7m.control[env->v7m.secure];
10589     case 0x94: /* CONTROL_NS */
10590         /* We have to handle this here because unprivileged Secure code
10591          * can read the NS CONTROL register.
10592          */
10593         if (!env->v7m.secure) {
10594             return 0;
10595         }
10596         return env->v7m.control[M_REG_NS];
10597     }
10598
10599     if (el == 0) {
10600         return 0; /* unprivileged reads others as zero */
10601     }
10602
10603     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10604         switch (reg) {
10605         case 0x88: /* MSP_NS */
10606             if (!env->v7m.secure) {
10607                 return 0;
10608             }
10609             return env->v7m.other_ss_msp;
10610         case 0x89: /* PSP_NS */
10611             if (!env->v7m.secure) {
10612                 return 0;
10613             }
10614             return env->v7m.other_ss_psp;
10615         case 0x8a: /* MSPLIM_NS */
10616             if (!env->v7m.secure) {
10617                 return 0;
10618             }
10619             return env->v7m.msplim[M_REG_NS];
10620         case 0x8b: /* PSPLIM_NS */
10621             if (!env->v7m.secure) {
10622                 return 0;
10623             }
10624             return env->v7m.psplim[M_REG_NS];
10625         case 0x90: /* PRIMASK_NS */
10626             if (!env->v7m.secure) {
10627                 return 0;
10628             }
10629             return env->v7m.primask[M_REG_NS];
10630         case 0x91: /* BASEPRI_NS */
10631             if (!env->v7m.secure) {
10632                 return 0;
10633             }
10634             return env->v7m.basepri[M_REG_NS];
10635         case 0x93: /* FAULTMASK_NS */
10636             if (!env->v7m.secure) {
10637                 return 0;
10638             }
10639             return env->v7m.faultmask[M_REG_NS];
10640         case 0x98: /* SP_NS */
10641         {
10642             /* This gives the non-secure SP selected based on whether we're
10643              * currently in handler mode or not, using the NS CONTROL.SPSEL.
10644              */
10645             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
10646
10647             if (!env->v7m.secure) {
10648                 return 0;
10649             }
10650             if (!arm_v7m_is_handler_mode(env) && spsel) {
10651                 return env->v7m.other_ss_psp;
10652             } else {
10653                 return env->v7m.other_ss_msp;
10654             }
10655         }
10656         default:
10657             break;
10658         }
10659     }
10660
10661     switch (reg) {
10662     case 8: /* MSP */
10663         return v7m_using_psp(env) ? env->v7m.other_sp : env->regs[13];
10664     case 9: /* PSP */
10665         return v7m_using_psp(env) ? env->regs[13] : env->v7m.other_sp;
10666     case 10: /* MSPLIM */
10667         if (!arm_feature(env, ARM_FEATURE_V8)) {
10668             goto bad_reg;
10669         }
10670         return env->v7m.msplim[env->v7m.secure];
10671     case 11: /* PSPLIM */
10672         if (!arm_feature(env, ARM_FEATURE_V8)) {
10673             goto bad_reg;
10674         }
10675         return env->v7m.psplim[env->v7m.secure];
10676     case 16: /* PRIMASK */
10677         return env->v7m.primask[env->v7m.secure];
10678     case 17: /* BASEPRI */
10679     case 18: /* BASEPRI_MAX */
10680         return env->v7m.basepri[env->v7m.secure];
10681     case 19: /* FAULTMASK */
10682         return env->v7m.faultmask[env->v7m.secure];
10683     default:
10684     bad_reg:
10685         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"
10686                                        " register %d\n", reg);
10687         return 0;
10688     }
10689 }
10690
10691 void HELPER(v7m_msr)(CPUARMState *env, uint32_t maskreg, uint32_t val)
10692 {
10693     /* We're passed bits [11..0] of the instruction; extract
10694      * SYSm and the mask bits.
10695      * Invalid combinations of SYSm and mask are UNPREDICTABLE;
10696      * we choose to treat them as if the mask bits were valid.
10697      * NB that the pseudocode 'mask' variable is bits [11..10],
10698      * whereas ours is [11..8].
10699      */
10700     uint32_t mask = extract32(maskreg, 8, 4);
10701     uint32_t reg = extract32(maskreg, 0, 8);
10702
10703     if (arm_current_el(env) == 0 && reg > 7) {
10704         /* only xPSR sub-fields may be written by unprivileged */
10705         return;
10706     }
10707
10708     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10709         switch (reg) {
10710         case 0x88: /* MSP_NS */
10711             if (!env->v7m.secure) {
10712                 return;
10713             }
10714             env->v7m.other_ss_msp = val;
10715             return;
10716         case 0x89: /* PSP_NS */
10717             if (!env->v7m.secure) {
10718                 return;
10719             }
10720             env->v7m.other_ss_psp = val;
10721             return;
10722         case 0x8a: /* MSPLIM_NS */
10723             if (!env->v7m.secure) {
10724                 return;
10725             }
10726             env->v7m.msplim[M_REG_NS] = val & ~7;
10727             return;
10728         case 0x8b: /* PSPLIM_NS */
10729             if (!env->v7m.secure) {
10730                 return;
10731             }
10732             env->v7m.psplim[M_REG_NS] = val & ~7;
10733             return;
10734         case 0x90: /* PRIMASK_NS */
10735             if (!env->v7m.secure) {
10736                 return;
10737             }
10738             env->v7m.primask[M_REG_NS] = val & 1;
10739             return;
10740         case 0x91: /* BASEPRI_NS */
10741             if (!env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_MAIN)) {
10742                 return;
10743             }
10744             env->v7m.basepri[M_REG_NS] = val & 0xff;
10745             return;
10746         case 0x93: /* FAULTMASK_NS */
10747             if (!env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_MAIN)) {
10748                 return;
10749             }
10750             env->v7m.faultmask[M_REG_NS] = val & 1;
10751             return;
10752         case 0x94: /* CONTROL_NS */
10753             if (!env->v7m.secure) {
10754                 return;
10755             }
10756             write_v7m_control_spsel_for_secstate(env,
10757                                                  val & R_V7M_CONTROL_SPSEL_MASK,
10758                                                  M_REG_NS);
10759             if (arm_feature(env, ARM_FEATURE_M_MAIN)) {
10760                 env->v7m.control[M_REG_NS] &= ~R_V7M_CONTROL_NPRIV_MASK;
10761                 env->v7m.control[M_REG_NS] |= val & R_V7M_CONTROL_NPRIV_MASK;
10762             }
10763             return;
10764         case 0x98: /* SP_NS */
10765         {
10766             /* This gives the non-secure SP selected based on whether we're
10767              * currently in handler mode or not, using the NS CONTROL.SPSEL.
10768              */
10769             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
10770
10771             if (!env->v7m.secure) {
10772                 return;
10773             }
10774             if (!arm_v7m_is_handler_mode(env) && spsel) {
10775                 env->v7m.other_ss_psp = val;
10776             } else {
10777                 env->v7m.other_ss_msp = val;
10778             }
10779             return;
10780         }
10781         default:
10782             break;
10783         }
10784     }
10785
10786     switch (reg) {
10787     case 0 ... 7: /* xPSR sub-fields */
10788         /* only APSR is actually writable */
10789         if (!(reg & 4)) {
10790             uint32_t apsrmask = 0;
10791
10792             if (mask & 8) {
10793                 apsrmask |= XPSR_NZCV | XPSR_Q;
10794             }
10795             if ((mask & 4) && arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
10796                 apsrmask |= XPSR_GE;
10797             }
10798             xpsr_write(env, val, apsrmask);
10799         }
10800         break;
10801     case 8: /* MSP */
10802         if (v7m_using_psp(env)) {
10803             env->v7m.other_sp = val;
10804         } else {
10805             env->regs[13] = val;
10806         }
10807         break;
10808     case 9: /* PSP */
10809         if (v7m_using_psp(env)) {
10810             env->regs[13] = val;
10811         } else {
10812             env->v7m.other_sp = val;
10813         }
10814         break;
10815     case 10: /* MSPLIM */
10816         if (!arm_feature(env, ARM_FEATURE_V8)) {
10817             goto bad_reg;
10818         }
10819         env->v7m.msplim[env->v7m.secure] = val & ~7;
10820         break;
10821     case 11: /* PSPLIM */
10822         if (!arm_feature(env, ARM_FEATURE_V8)) {
10823             goto bad_reg;
10824         }
10825         env->v7m.psplim[env->v7m.secure] = val & ~7;
10826         break;
10827     case 16: /* PRIMASK */
10828         env->v7m.primask[env->v7m.secure] = val & 1;
10829         break;
10830     case 17: /* BASEPRI */
10831         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
10832             goto bad_reg;
10833         }
10834         env->v7m.basepri[env->v7m.secure] = val & 0xff;
10835         break;
10836     case 18: /* BASEPRI_MAX */
10837         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
10838             goto bad_reg;
10839         }
10840         val &= 0xff;
10841         if (val != 0 && (val < env->v7m.basepri[env->v7m.secure]
10842                          || env->v7m.basepri[env->v7m.secure] == 0)) {
10843             env->v7m.basepri[env->v7m.secure] = val;
10844         }
10845         break;
10846     case 19: /* FAULTMASK */
10847         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
10848             goto bad_reg;
10849         }
10850         env->v7m.faultmask[env->v7m.secure] = val & 1;
10851         break;
10852     case 20: /* CONTROL */
10853         /* Writing to the SPSEL bit only has an effect if we are in
10854          * thread mode; other bits can be updated by any privileged code.
10855          * write_v7m_control_spsel() deals with updating the SPSEL bit in
10856          * env->v7m.control, so we only need update the others.
10857          * For v7M, we must just ignore explicit writes to SPSEL in handler
10858          * mode; for v8M the write is permitted but will have no effect.
10859          */
10860         if (arm_feature(env, ARM_FEATURE_V8) ||
10861             !arm_v7m_is_handler_mode(env)) {
10862             write_v7m_control_spsel(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);
10863         }
10864         if (arm_feature(env, ARM_FEATURE_M_MAIN)) {
10865             env->v7m.control[env->v7m.secure] &= ~R_V7M_CONTROL_NPRIV_MASK;
10866             env->v7m.control[env->v7m.secure] |= val & R_V7M_CONTROL_NPRIV_MASK;
10867         }
10868         break;
10869     default:
10870     bad_reg:
10871         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"
10872                                        " register %d\n", reg);
10873         return;
10874     }
10875 }
10876
10877 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
10878 {
10879     /* Implement the TT instruction. op is bits [7:6] of the insn. */
10880     bool forceunpriv = op & 1;
10881     bool alt = op & 2;
10882     V8M_SAttributes sattrs = {};
10883     uint32_t tt_resp;
10884     bool r, rw, nsr, nsrw, mrvalid;
10885     int prot;
10886     ARMMMUFaultInfo fi = {};
10887     MemTxAttrs attrs = {};
10888     hwaddr phys_addr;
10889     ARMMMUIdx mmu_idx;
10890     uint32_t mregion;
10891     bool targetpriv;
10892     bool targetsec = env->v7m.secure;
10893     bool is_subpage;
10894
10895     /* Work out what the security state and privilege level we're
10896      * interested in is...
10897      */
10898     if (alt) {
10899         targetsec = !targetsec;
10900     }
10901
10902     if (forceunpriv) {
10903         targetpriv = false;
10904     } else {
10905         targetpriv = arm_v7m_is_handler_mode(env) ||
10906             !(env->v7m.control[targetsec] & R_V7M_CONTROL_NPRIV_MASK);
10907     }
10908
10909     /* ...and then figure out which MMU index this is */
10910     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targetsec, targetpriv);
10911
10912     /* We know that the MPU and SAU don't care about the access type
10913      * for our purposes beyond that we don't want to claim to be
10914      * an insn fetch, so we arbitrarily call this a read.
10915      */
10916
10917     /* MPU region info only available for privileged or if
10918      * inspecting the other MPU state.
10919      */
10920     if (arm_current_el(env) != 0 || alt) {
10921         /* We can ignore the return value as prot is always set */
10922         pmsav8_mpu_lookup(env, addr, MMU_DATA_LOAD, mmu_idx,
10923                           &phys_addr, &attrs, &prot, &is_subpage,
10924                           &fi, &mregion);
10925         if (mregion == -1) {
10926             mrvalid = false;
10927             mregion = 0;
10928         } else {
10929             mrvalid = true;
10930         }
10931         r = prot & PAGE_READ;
10932         rw = prot & PAGE_WRITE;
10933     } else {
10934         r = false;
10935         rw = false;
10936         mrvalid = false;
10937         mregion = 0;
10938     }
10939
10940     if (env->v7m.secure) {
10941         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
10942         nsr = sattrs.ns && r;
10943         nsrw = sattrs.ns && rw;
10944     } else {
10945         sattrs.ns = true;
10946         nsr = false;
10947         nsrw = false;
10948     }
10949
10950     tt_resp = (sattrs.iregion << 24) |
10951         (sattrs.irvalid << 23) |
10952         ((!sattrs.ns) << 22) |
10953         (nsrw << 21) |
10954         (nsr << 20) |
10955         (rw << 19) |
10956         (r << 18) |
10957         (sattrs.srvalid << 17) |
10958         (mrvalid << 16) |
10959         (sattrs.sregion << 8) |
10960         mregion;
10961
10962     return tt_resp;
10963 }
10964
10965 #endif
10966
10967 void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)
10968 {
10969     /* Implement DC ZVA, which zeroes a fixed-length block of memory.
10970      * Note that we do not implement the (architecturally mandated)
10971      * alignment fault for attempts to use this on Device memory
10972      * (which matches the usual QEMU behaviour of not implementing either
10973      * alignment faults or any memory attribute handling).
10974      */
10975
10976     ARMCPU *cpu = arm_env_get_cpu(env);
10977     uint64_t blocklen = 4 << cpu->dcz_blocksize;
10978     uint64_t vaddr = vaddr_in & ~(blocklen - 1);
10979
10980 #ifndef CONFIG_USER_ONLY
10981     {
10982         /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than
10983          * the block size so we might have to do more than one TLB lookup.
10984          * We know that in fact for any v8 CPU the page size is at least 4K
10985          * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only
10986          * 1K as an artefact of legacy v5 subpage support being present in the
10987          * same QEMU executable.
10988          */
10989         int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);
10990         void *hostaddr[maxidx];
10991         int try, i;
10992         unsigned mmu_idx = cpu_mmu_index(env, false);
10993         TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);
10994
10995         for (try = 0; try < 2; try++) {
10996
10997             for (i = 0; i < maxidx; i++) {
10998                 hostaddr[i] = tlb_vaddr_to_host(env,
10999                                                 vaddr + TARGET_PAGE_SIZE * i,
11000                                                 1, mmu_idx);
11001                 if (!hostaddr[i]) {
11002                     break;
11003                 }
11004             }
11005             if (i == maxidx) {
11006                 /* If it's all in the TLB it's fair game for just writing to;
11007                  * we know we don't need to update dirty status, etc.
11008                  */
11009                 for (i = 0; i < maxidx - 1; i++) {
11010                     memset(hostaddr[i], 0, TARGET_PAGE_SIZE);
11011                 }
11012                 memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));
11013                 return;
11014             }
11015             /* OK, try a store and see if we can populate the tlb. This
11016              * might cause an exception if the memory isn't writable,
11017              * in which case we will longjmp out of here. We must for
11018              * this purpose use the actual register value passed to us
11019              * so that we get the fault address right.
11020              */
11021             helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETPC());
11022             /* Now we can populate the other TLB entries, if any */
11023             for (i = 0; i < maxidx; i++) {
11024                 uint64_t va = vaddr + TARGET_PAGE_SIZE * i;
11025                 if (va != (vaddr_in & TARGET_PAGE_MASK)) {
11026                     helper_ret_stb_mmu(env, va, 0, oi, GETPC());
11027                 }
11028             }
11029         }
11030
11031         /* Slow path (probably attempt to do this to an I/O device or
11032          * similar, or clearing of a block of code we have translations
11033          * cached for). Just do a series of byte writes as the architecture
11034          * demands. It's not worth trying to use a cpu_physical_memory_map(),
11035          * memset(), unmap() sequence here because:
11036          *  + we'd need to account for the blocksize being larger than a page
11037          *  + the direct-RAM access case is almost always going to be dealt
11038          *    with in the fastpath code above, so there's no speed benefit
11039          *  + we would have to deal with the map returning NULL because the
11040          *    bounce buffer was in use
11041          */
11042         for (i = 0; i < blocklen; i++) {
11043             helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETPC());
11044         }
11045     }
11046 #else
11047     memset(g2h(vaddr), 0, blocklen);
11048 #endif
11049 }
11050
11051 /* Note that signed overflow is undefined in C.  The following routines are
11052    careful to use unsigned types where modulo arithmetic is required.
11053    Failure to do so _will_ break on newer gcc.  */
11054
11055 /* Signed saturating arithmetic.  */
11056
11057 /* Perform 16-bit signed saturating addition.  */
11058 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
11059 {
11060     uint16_t res;
11061
11062     res = a + b;
11063     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
11064         if (a & 0x8000)
11065             res = 0x8000;
11066         else
11067             res = 0x7fff;
11068     }
11069     return res;
11070 }
11071
11072 /* Perform 8-bit signed saturating addition.  */
11073 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
11074 {
11075     uint8_t res;
11076
11077     res = a + b;
11078     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
11079         if (a & 0x80)
11080             res = 0x80;
11081         else
11082             res = 0x7f;
11083     }
11084     return res;
11085 }
11086
11087 /* Perform 16-bit signed saturating subtraction.  */
11088 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
11089 {
11090     uint16_t res;
11091
11092     res = a - b;
11093     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
11094         if (a & 0x8000)
11095             res = 0x8000;
11096         else
11097             res = 0x7fff;
11098     }
11099     return res;
11100 }
11101
11102 /* Perform 8-bit signed saturating subtraction.  */
11103 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
11104 {
11105     uint8_t res;
11106
11107     res = a - b;
11108     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
11109         if (a & 0x80)
11110             res = 0x80;
11111         else
11112             res = 0x7f;
11113     }
11114     return res;
11115 }
11116
11117 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
11118 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
11119 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
11120 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
11121 #define PFX q
11122
11123 #include "op_addsub.h"
11124
11125 /* Unsigned saturating arithmetic.  */
11126 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
11127 {
11128     uint16_t res;
11129     res = a + b;
11130     if (res < a)
11131         res = 0xffff;
11132     return res;
11133 }
11134
11135 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
11136 {
11137     if (a > b)
11138         return a - b;
11139     else
11140         return 0;
11141 }
11142
11143 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
11144 {
11145     uint8_t res;
11146     res = a + b;
11147     if (res < a)
11148         res = 0xff;
11149     return res;
11150 }
11151
11152 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
11153 {
11154     if (a > b)
11155         return a - b;
11156     else
11157         return 0;
11158 }
11159
11160 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
11161 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
11162 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
11163 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
11164 #define PFX uq
11165
11166 #include "op_addsub.h"
11167
11168 /* Signed modulo arithmetic.  */
11169 #define SARITH16(a, b, n, op) do { \
11170     int32_t sum; \
11171     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
11172     RESULT(sum, n, 16); \
11173     if (sum >= 0) \
11174         ge |= 3 << (n * 2); \
11175     } while(0)
11176
11177 #define SARITH8(a, b, n, op) do { \
11178     int32_t sum; \
11179     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
11180     RESULT(sum, n, 8); \
11181     if (sum >= 0) \
11182         ge |= 1 << n; \
11183     } while(0)
11184
11185
11186 #define ADD16(a, b, n) SARITH16(a, b, n, +)
11187 #define SUB16(a, b, n) SARITH16(a, b, n, -)
11188 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
11189 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
11190 #define PFX s
11191 #define ARITH_GE
11192
11193 #include "op_addsub.h"
11194
11195 /* Unsigned modulo arithmetic.  */
11196 #define ADD16(a, b, n) do { \
11197     uint32_t sum; \
11198     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
11199     RESULT(sum, n, 16); \
11200     if ((sum >> 16) == 1) \
11201         ge |= 3 << (n * 2); \
11202     } while(0)
11203
11204 #define ADD8(a, b, n) do { \
11205     uint32_t sum; \
11206     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
11207     RESULT(sum, n, 8); \
11208     if ((sum >> 8) == 1) \
11209         ge |= 1 << n; \
11210     } while(0)
11211
11212 #define SUB16(a, b, n) do { \
11213     uint32_t sum; \
11214     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
11215     RESULT(sum, n, 16); \
11216     if ((sum >> 16) == 0) \
11217         ge |= 3 << (n * 2); \
11218     } while(0)
11219
11220 #define SUB8(a, b, n) do { \
11221     uint32_t sum; \
11222     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
11223     RESULT(sum, n, 8); \
11224     if ((sum >> 8) == 0) \
11225         ge |= 1 << n; \
11226     } while(0)
11227
11228 #define PFX u
11229 #define ARITH_GE
11230
11231 #include "op_addsub.h"
11232
11233 /* Halved signed arithmetic.  */
11234 #define ADD16(a, b, n) \
11235   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
11236 #define SUB16(a, b, n) \
11237   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
11238 #define ADD8(a, b, n) \
11239   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
11240 #define SUB8(a, b, n) \
11241   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
11242 #define PFX sh
11243
11244 #include "op_addsub.h"
11245
11246 /* Halved unsigned arithmetic.  */
11247 #define ADD16(a, b, n) \
11248   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11249 #define SUB16(a, b, n) \
11250   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11251 #define ADD8(a, b, n) \
11252   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11253 #define SUB8(a, b, n) \
11254   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11255 #define PFX uh
11256
11257 #include "op_addsub.h"
11258
11259 static inline uint8_t do_usad(uint8_t a, uint8_t b)
11260 {
11261     if (a > b)
11262         return a - b;
11263     else
11264         return b - a;
11265 }
11266
11267 /* Unsigned sum of absolute byte differences.  */
11268 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
11269 {
11270     uint32_t sum;
11271     sum = do_usad(a, b);
11272     sum += do_usad(a >> 8, b >> 8);
11273     sum += do_usad(a >> 16, b >>16);
11274     sum += do_usad(a >> 24, b >> 24);
11275     return sum;
11276 }
11277
11278 /* For ARMv6 SEL instruction.  */
11279 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
11280 {
11281     uint32_t mask;
11282
11283     mask = 0;
11284     if (flags & 1)
11285         mask |= 0xff;
11286     if (flags & 2)
11287         mask |= 0xff00;
11288     if (flags & 4)
11289         mask |= 0xff0000;
11290     if (flags & 8)
11291         mask |= 0xff000000;
11292     return (a & mask) | (b & ~mask);
11293 }
11294
11295 /* VFP support.  We follow the convention used for VFP instructions:
11296    Single precision routines have a "s" suffix, double precision a
11297    "d" suffix.  */
11298
11299 /* Convert host exception flags to vfp form.  */
11300 static inline int vfp_exceptbits_from_host(int host_bits)
11301 {
11302     int target_bits = 0;
11303
11304     if (host_bits & float_flag_invalid)
11305         target_bits |= 1;
11306     if (host_bits & float_flag_divbyzero)
11307         target_bits |= 2;
11308     if (host_bits & float_flag_overflow)
11309         target_bits |= 4;
11310     if (host_bits & (float_flag_underflow | float_flag_output_denormal))
11311         target_bits |= 8;
11312     if (host_bits & float_flag_inexact)
11313         target_bits |= 0x10;
11314     if (host_bits & float_flag_input_denormal)
11315         target_bits |= 0x80;
11316     return target_bits;
11317 }
11318
11319 uint32_t HELPER(vfp_get_fpscr)(CPUARMState *env)
11320 {
11321     int i;
11322     uint32_t fpscr;
11323
11324     fpscr = (env->vfp.xregs[ARM_VFP_FPSCR] & 0xffc8ffff)
11325             | (env->vfp.vec_len << 16)
11326             | (env->vfp.vec_stride << 20);
11327
11328     i = get_float_exception_flags(&env->vfp.fp_status);
11329     i |= get_float_exception_flags(&env->vfp.standard_fp_status);
11330     /* FZ16 does not generate an input denormal exception.  */
11331     i |= (get_float_exception_flags(&env->vfp.fp_status_f16)
11332           & ~float_flag_input_denormal);
11333
11334     fpscr |= vfp_exceptbits_from_host(i);
11335     return fpscr;
11336 }
11337
11338 uint32_t vfp_get_fpscr(CPUARMState *env)
11339 {
11340     return HELPER(vfp_get_fpscr)(env);
11341 }
11342
11343 /* Convert vfp exception flags to target form.  */
11344 static inline int vfp_exceptbits_to_host(int target_bits)
11345 {
11346     int host_bits = 0;
11347
11348     if (target_bits & 1)
11349         host_bits |= float_flag_invalid;
11350     if (target_bits & 2)
11351         host_bits |= float_flag_divbyzero;
11352     if (target_bits & 4)
11353         host_bits |= float_flag_overflow;
11354     if (target_bits & 8)
11355         host_bits |= float_flag_underflow;
11356     if (target_bits & 0x10)
11357         host_bits |= float_flag_inexact;
11358     if (target_bits & 0x80)
11359         host_bits |= float_flag_input_denormal;
11360     return host_bits;
11361 }
11362
11363 void HELPER(vfp_set_fpscr)(CPUARMState *env, uint32_t val)
11364 {
11365     int i;
11366     uint32_t changed;
11367
11368     /* When ARMv8.2-FP16 is not supported, FZ16 is RES0.  */
11369     if (!arm_feature(env, ARM_FEATURE_V8_FP16)) {
11370         val &= ~FPCR_FZ16;
11371     }
11372
11373     changed = env->vfp.xregs[ARM_VFP_FPSCR];
11374     env->vfp.xregs[ARM_VFP_FPSCR] = (val & 0xffc8ffff);
11375     env->vfp.vec_len = (val >> 16) & 7;
11376     env->vfp.vec_stride = (val >> 20) & 3;
11377
11378     changed ^= val;
11379     if (changed & (3 << 22)) {
11380         i = (val >> 22) & 3;
11381         switch (i) {
11382         case FPROUNDING_TIEEVEN:
11383             i = float_round_nearest_even;
11384             break;
11385         case FPROUNDING_POSINF:
11386             i = float_round_up;
11387             break;
11388         case FPROUNDING_NEGINF:
11389             i = float_round_down;
11390             break;
11391         case FPROUNDING_ZERO:
11392             i = float_round_to_zero;
11393             break;
11394         }
11395         set_float_rounding_mode(i, &env->vfp.fp_status);
11396         set_float_rounding_mode(i, &env->vfp.fp_status_f16);
11397     }
11398     if (changed & FPCR_FZ16) {
11399         bool ftz_enabled = val & FPCR_FZ16;
11400         set_flush_to_zero(ftz_enabled, &env->vfp.fp_status_f16);
11401         set_flush_inputs_to_zero(ftz_enabled, &env->vfp.fp_status_f16);
11402     }
11403     if (changed & FPCR_FZ) {
11404         bool ftz_enabled = val & FPCR_FZ;
11405         set_flush_to_zero(ftz_enabled, &env->vfp.fp_status);
11406         set_flush_inputs_to_zero(ftz_enabled, &env->vfp.fp_status);
11407     }
11408     if (changed & FPCR_DN) {
11409         bool dnan_enabled = val & FPCR_DN;
11410         set_default_nan_mode(dnan_enabled, &env->vfp.fp_status);
11411         set_default_nan_mode(dnan_enabled, &env->vfp.fp_status_f16);
11412     }
11413
11414     /* The exception flags are ORed together when we read fpscr so we
11415      * only need to preserve the current state in one of our
11416      * float_status values.
11417      */
11418     i = vfp_exceptbits_to_host(val);
11419     set_float_exception_flags(i, &env->vfp.fp_status);
11420     set_float_exception_flags(0, &env->vfp.fp_status_f16);
11421     set_float_exception_flags(0, &env->vfp.standard_fp_status);
11422 }
11423
11424 void vfp_set_fpscr(CPUARMState *env, uint32_t val)
11425 {
11426     HELPER(vfp_set_fpscr)(env, val);
11427 }
11428
11429 #define VFP_HELPER(name, p) HELPER(glue(glue(vfp_,name),p))
11430
11431 #define VFP_BINOP(name) \
11432 float32 VFP_HELPER(name, s)(float32 a, float32 b, void *fpstp) \
11433 { \
11434     float_status *fpst = fpstp; \
11435     return float32_ ## name(a, b, fpst); \
11436 } \
11437 float64 VFP_HELPER(name, d)(float64 a, float64 b, void *fpstp) \
11438 { \
11439     float_status *fpst = fpstp; \
11440     return float64_ ## name(a, b, fpst); \
11441 }
11442 VFP_BINOP(add)
11443 VFP_BINOP(sub)
11444 VFP_BINOP(mul)
11445 VFP_BINOP(div)
11446 VFP_BINOP(min)
11447 VFP_BINOP(max)
11448 VFP_BINOP(minnum)
11449 VFP_BINOP(maxnum)
11450 #undef VFP_BINOP
11451
11452 float32 VFP_HELPER(neg, s)(float32 a)
11453 {
11454     return float32_chs(a);
11455 }
11456
11457 float64 VFP_HELPER(neg, d)(float64 a)
11458 {
11459     return float64_chs(a);
11460 }
11461
11462 float32 VFP_HELPER(abs, s)(float32 a)
11463 {
11464     return float32_abs(a);
11465 }
11466
11467 float64 VFP_HELPER(abs, d)(float64 a)
11468 {
11469     return float64_abs(a);
11470 }
11471
11472 float32 VFP_HELPER(sqrt, s)(float32 a, CPUARMState *env)
11473 {
11474     return float32_sqrt(a, &env->vfp.fp_status);
11475 }
11476
11477 float64 VFP_HELPER(sqrt, d)(float64 a, CPUARMState *env)
11478 {
11479     return float64_sqrt(a, &env->vfp.fp_status);
11480 }
11481
11482 /* XXX: check quiet/signaling case */
11483 #define DO_VFP_cmp(p, type) \
11484 void VFP_HELPER(cmp, p)(type a, type b, CPUARMState *env)  \
11485 { \
11486     uint32_t flags; \
11487     switch(type ## _compare_quiet(a, b, &env->vfp.fp_status)) { \
11488     case 0: flags = 0x6; break; \
11489     case -1: flags = 0x8; break; \
11490     case 1: flags = 0x2; break; \
11491     default: case 2: flags = 0x3; break; \
11492     } \
11493     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
11494         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
11495 } \
11496 void VFP_HELPER(cmpe, p)(type a, type b, CPUARMState *env) \
11497 { \
11498     uint32_t flags; \
11499     switch(type ## _compare(a, b, &env->vfp.fp_status)) { \
11500     case 0: flags = 0x6; break; \
11501     case -1: flags = 0x8; break; \
11502     case 1: flags = 0x2; break; \
11503     default: case 2: flags = 0x3; break; \
11504     } \
11505     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
11506         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
11507 }
11508 DO_VFP_cmp(s, float32)
11509 DO_VFP_cmp(d, float64)
11510 #undef DO_VFP_cmp
11511
11512 /* Integer to float and float to integer conversions */
11513
11514 #define CONV_ITOF(name, ftype, fsz, sign)                           \
11515 ftype HELPER(name)(uint32_t x, void *fpstp)                         \
11516 {                                                                   \
11517     float_status *fpst = fpstp;                                     \
11518     return sign##int32_to_##float##fsz((sign##int32_t)x, fpst);     \
11519 }
11520
11521 #define CONV_FTOI(name, ftype, fsz, sign, round)                \
11522 sign##int32_t HELPER(name)(ftype x, void *fpstp)                \
11523 {                                                               \
11524     float_status *fpst = fpstp;                                 \
11525     if (float##fsz##_is_any_nan(x)) {                           \
11526         float_raise(float_flag_invalid, fpst);                  \
11527         return 0;                                               \
11528     }                                                           \
11529     return float##fsz##_to_##sign##int32##round(x, fpst);       \
11530 }
11531
11532 #define FLOAT_CONVS(name, p, ftype, fsz, sign)            \
11533     CONV_ITOF(vfp_##name##to##p, ftype, fsz, sign)        \
11534     CONV_FTOI(vfp_to##name##p, ftype, fsz, sign, )        \
11535     CONV_FTOI(vfp_to##name##z##p, ftype, fsz, sign, _round_to_zero)
11536
11537 FLOAT_CONVS(si, h, uint32_t, 16, )
11538 FLOAT_CONVS(si, s, float32, 32, )
11539 FLOAT_CONVS(si, d, float64, 64, )
11540 FLOAT_CONVS(ui, h, uint32_t, 16, u)
11541 FLOAT_CONVS(ui, s, float32, 32, u)
11542 FLOAT_CONVS(ui, d, float64, 64, u)
11543
11544 #undef CONV_ITOF
11545 #undef CONV_FTOI
11546 #undef FLOAT_CONVS
11547
11548 /* floating point conversion */
11549 float64 VFP_HELPER(fcvtd, s)(float32 x, CPUARMState *env)
11550 {
11551     return float32_to_float64(x, &env->vfp.fp_status);
11552 }
11553
11554 float32 VFP_HELPER(fcvts, d)(float64 x, CPUARMState *env)
11555 {
11556     return float64_to_float32(x, &env->vfp.fp_status);
11557 }
11558
11559 /* VFP3 fixed point conversion.  */
11560 #define VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype) \
11561 float##fsz HELPER(vfp_##name##to##p)(uint##isz##_t  x, uint32_t shift, \
11562                                      void *fpstp) \
11563 { \
11564     float_status *fpst = fpstp; \
11565     float##fsz tmp; \
11566     tmp = itype##_to_##float##fsz(x, fpst); \
11567     return float##fsz##_scalbn(tmp, -(int)shift, fpst); \
11568 }
11569
11570 /* Notice that we want only input-denormal exception flags from the
11571  * scalbn operation: the other possible flags (overflow+inexact if
11572  * we overflow to infinity, output-denormal) aren't correct for the
11573  * complete scale-and-convert operation.
11574  */
11575 #define VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, round) \
11576 uint##isz##_t HELPER(vfp_to##name##p##round)(float##fsz x, \
11577                                              uint32_t shift, \
11578                                              void *fpstp) \
11579 { \
11580     float_status *fpst = fpstp; \
11581     int old_exc_flags = get_float_exception_flags(fpst); \
11582     float##fsz tmp; \
11583     if (float##fsz##_is_any_nan(x)) { \
11584         float_raise(float_flag_invalid, fpst); \
11585         return 0; \
11586     } \
11587     tmp = float##fsz##_scalbn(x, shift, fpst); \
11588     old_exc_flags |= get_float_exception_flags(fpst) \
11589         & float_flag_input_denormal; \
11590     set_float_exception_flags(old_exc_flags, fpst); \
11591     return float##fsz##_to_##itype##round(tmp, fpst); \
11592 }
11593
11594 #define VFP_CONV_FIX(name, p, fsz, isz, itype)                   \
11595 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
11596 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, _round_to_zero) \
11597 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
11598
11599 #define VFP_CONV_FIX_A64(name, p, fsz, isz, itype)               \
11600 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
11601 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
11602
11603 VFP_CONV_FIX(sh, d, 64, 64, int16)
11604 VFP_CONV_FIX(sl, d, 64, 64, int32)
11605 VFP_CONV_FIX_A64(sq, d, 64, 64, int64)
11606 VFP_CONV_FIX(uh, d, 64, 64, uint16)
11607 VFP_CONV_FIX(ul, d, 64, 64, uint32)
11608 VFP_CONV_FIX_A64(uq, d, 64, 64, uint64)
11609 VFP_CONV_FIX(sh, s, 32, 32, int16)
11610 VFP_CONV_FIX(sl, s, 32, 32, int32)
11611 VFP_CONV_FIX_A64(sq, s, 32, 64, int64)
11612 VFP_CONV_FIX(uh, s, 32, 32, uint16)
11613 VFP_CONV_FIX(ul, s, 32, 32, uint32)
11614 VFP_CONV_FIX_A64(uq, s, 32, 64, uint64)
11615
11616 #undef VFP_CONV_FIX
11617 #undef VFP_CONV_FIX_FLOAT
11618 #undef VFP_CONV_FLOAT_FIX_ROUND
11619 #undef VFP_CONV_FIX_A64
11620
11621 /* Conversion to/from f16 can overflow to infinity before/after scaling.
11622  * Therefore we convert to f64, scale, and then convert f64 to f16; or
11623  * vice versa for conversion to integer.
11624  *
11625  * For 16- and 32-bit integers, the conversion to f64 never rounds.
11626  * For 64-bit integers, any integer that would cause rounding will also
11627  * overflow to f16 infinity, so there is no double rounding problem.
11628  */
11629
11630 static float16 do_postscale_fp16(float64 f, int shift, float_status *fpst)
11631 {
11632     return float64_to_float16(float64_scalbn(f, -shift, fpst), true, fpst);
11633 }
11634
11635 uint32_t HELPER(vfp_sltoh)(uint32_t x, uint32_t shift, void *fpst)
11636 {
11637     return do_postscale_fp16(int32_to_float64(x, fpst), shift, fpst);
11638 }
11639
11640 uint32_t HELPER(vfp_ultoh)(uint32_t x, uint32_t shift, void *fpst)
11641 {
11642     return do_postscale_fp16(uint32_to_float64(x, fpst), shift, fpst);
11643 }
11644
11645 uint32_t HELPER(vfp_sqtoh)(uint64_t x, uint32_t shift, void *fpst)
11646 {
11647     return do_postscale_fp16(int64_to_float64(x, fpst), shift, fpst);
11648 }
11649
11650 uint32_t HELPER(vfp_uqtoh)(uint64_t x, uint32_t shift, void *fpst)
11651 {
11652     return do_postscale_fp16(uint64_to_float64(x, fpst), shift, fpst);
11653 }
11654
11655 static float64 do_prescale_fp16(float16 f, int shift, float_status *fpst)
11656 {
11657     if (unlikely(float16_is_any_nan(f))) {
11658         float_raise(float_flag_invalid, fpst);
11659         return 0;
11660     } else {
11661         int old_exc_flags = get_float_exception_flags(fpst);
11662         float64 ret;
11663
11664         ret = float16_to_float64(f, true, fpst);
11665         ret = float64_scalbn(ret, shift, fpst);
11666         old_exc_flags |= get_float_exception_flags(fpst)
11667             & float_flag_input_denormal;
11668         set_float_exception_flags(old_exc_flags, fpst);
11669
11670         return ret;
11671     }
11672 }
11673
11674 uint32_t HELPER(vfp_toshh)(uint32_t x, uint32_t shift, void *fpst)
11675 {
11676     return float64_to_int16(do_prescale_fp16(x, shift, fpst), fpst);
11677 }
11678
11679 uint32_t HELPER(vfp_touhh)(uint32_t x, uint32_t shift, void *fpst)
11680 {
11681     return float64_to_uint16(do_prescale_fp16(x, shift, fpst), fpst);
11682 }
11683
11684 uint32_t HELPER(vfp_toslh)(uint32_t x, uint32_t shift, void *fpst)
11685 {
11686     return float64_to_int32(do_prescale_fp16(x, shift, fpst), fpst);
11687 }
11688
11689 uint32_t HELPER(vfp_toulh)(uint32_t x, uint32_t shift, void *fpst)
11690 {
11691     return float64_to_uint32(do_prescale_fp16(x, shift, fpst), fpst);
11692 }
11693
11694 uint64_t HELPER(vfp_tosqh)(uint32_t x, uint32_t shift, void *fpst)
11695 {
11696     return float64_to_int64(do_prescale_fp16(x, shift, fpst), fpst);
11697 }
11698
11699 uint64_t HELPER(vfp_touqh)(uint32_t x, uint32_t shift, void *fpst)
11700 {
11701     return float64_to_uint64(do_prescale_fp16(x, shift, fpst), fpst);
11702 }
11703
11704 /* Set the current fp rounding mode and return the old one.
11705  * The argument is a softfloat float_round_ value.
11706  */
11707 uint32_t HELPER(set_rmode)(uint32_t rmode, void *fpstp)
11708 {
11709     float_status *fp_status = fpstp;
11710
11711     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
11712     set_float_rounding_mode(rmode, fp_status);
11713
11714     return prev_rmode;
11715 }
11716
11717 /* Set the current fp rounding mode in the standard fp status and return
11718  * the old one. This is for NEON instructions that need to change the
11719  * rounding mode but wish to use the standard FPSCR values for everything
11720  * else. Always set the rounding mode back to the correct value after
11721  * modifying it.
11722  * The argument is a softfloat float_round_ value.
11723  */
11724 uint32_t HELPER(set_neon_rmode)(uint32_t rmode, CPUARMState *env)
11725 {
11726     float_status *fp_status = &env->vfp.standard_fp_status;
11727
11728     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
11729     set_float_rounding_mode(rmode, fp_status);
11730
11731     return prev_rmode;
11732 }
11733
11734 /* Half precision conversions.  */
11735 float32 HELPER(vfp_fcvt_f16_to_f32)(uint32_t a, void *fpstp, uint32_t ahp_mode)
11736 {
11737     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
11738      * it would affect flushing input denormals.
11739      */
11740     float_status *fpst = fpstp;
11741     flag save = get_flush_inputs_to_zero(fpst);
11742     set_flush_inputs_to_zero(false, fpst);
11743     float32 r = float16_to_float32(a, !ahp_mode, fpst);
11744     set_flush_inputs_to_zero(save, fpst);
11745     return r;
11746 }
11747
11748 uint32_t HELPER(vfp_fcvt_f32_to_f16)(float32 a, void *fpstp, uint32_t ahp_mode)
11749 {
11750     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
11751      * it would affect flushing output denormals.
11752      */
11753     float_status *fpst = fpstp;
11754     flag save = get_flush_to_zero(fpst);
11755     set_flush_to_zero(false, fpst);
11756     float16 r = float32_to_float16(a, !ahp_mode, fpst);
11757     set_flush_to_zero(save, fpst);
11758     return r;
11759 }
11760
11761 float64 HELPER(vfp_fcvt_f16_to_f64)(uint32_t a, void *fpstp, uint32_t ahp_mode)
11762 {
11763     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
11764      * it would affect flushing input denormals.
11765      */
11766     float_status *fpst = fpstp;
11767     flag save = get_flush_inputs_to_zero(fpst);
11768     set_flush_inputs_to_zero(false, fpst);
11769     float64 r = float16_to_float64(a, !ahp_mode, fpst);
11770     set_flush_inputs_to_zero(save, fpst);
11771     return r;
11772 }
11773
11774 uint32_t HELPER(vfp_fcvt_f64_to_f16)(float64 a, void *fpstp, uint32_t ahp_mode)
11775 {
11776     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
11777      * it would affect flushing output denormals.
11778      */
11779     float_status *fpst = fpstp;
11780     flag save = get_flush_to_zero(fpst);
11781     set_flush_to_zero(false, fpst);
11782     float16 r = float64_to_float16(a, !ahp_mode, fpst);
11783     set_flush_to_zero(save, fpst);
11784     return r;
11785 }
11786
11787 #define float32_two make_float32(0x40000000)
11788 #define float32_three make_float32(0x40400000)
11789 #define float32_one_point_five make_float32(0x3fc00000)
11790
11791 float32 HELPER(recps_f32)(float32 a, float32 b, CPUARMState *env)
11792 {
11793     float_status *s = &env->vfp.standard_fp_status;
11794     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
11795         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
11796         if (!(float32_is_zero(a) || float32_is_zero(b))) {
11797             float_raise(float_flag_input_denormal, s);
11798         }
11799         return float32_two;
11800     }
11801     return float32_sub(float32_two, float32_mul(a, b, s), s);
11802 }
11803
11804 float32 HELPER(rsqrts_f32)(float32 a, float32 b, CPUARMState *env)
11805 {
11806     float_status *s = &env->vfp.standard_fp_status;
11807     float32 product;
11808     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
11809         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
11810         if (!(float32_is_zero(a) || float32_is_zero(b))) {
11811             float_raise(float_flag_input_denormal, s);
11812         }
11813         return float32_one_point_five;
11814     }
11815     product = float32_mul(a, b, s);
11816     return float32_div(float32_sub(float32_three, product, s), float32_two, s);
11817 }
11818
11819 /* NEON helpers.  */
11820
11821 /* Constants 256 and 512 are used in some helpers; we avoid relying on
11822  * int->float conversions at run-time.  */
11823 #define float64_256 make_float64(0x4070000000000000LL)
11824 #define float64_512 make_float64(0x4080000000000000LL)
11825 #define float16_maxnorm make_float16(0x7bff)
11826 #define float32_maxnorm make_float32(0x7f7fffff)
11827 #define float64_maxnorm make_float64(0x7fefffffffffffffLL)
11828
11829 /* Reciprocal functions
11830  *
11831  * The algorithm that must be used to calculate the estimate
11832  * is specified by the ARM ARM, see FPRecipEstimate()/RecipEstimate
11833  */
11834
11835 /* See RecipEstimate()
11836  *
11837  * input is a 9 bit fixed point number
11838  * input range 256 .. 511 for a number from 0.5 <= x < 1.0.
11839  * result range 256 .. 511 for a number from 1.0 to 511/256.
11840  */
11841
11842 static int recip_estimate(int input)
11843 {
11844     int a, b, r;
11845     assert(256 <= input && input < 512);
11846     a = (input * 2) + 1;
11847     b = (1 << 19) / a;
11848     r = (b + 1) >> 1;
11849     assert(256 <= r && r < 512);
11850     return r;
11851 }
11852
11853 /*
11854  * Common wrapper to call recip_estimate
11855  *
11856  * The parameters are exponent and 64 bit fraction (without implicit
11857  * bit) where the binary point is nominally at bit 52. Returns a
11858  * float64 which can then be rounded to the appropriate size by the
11859  * callee.
11860  */
11861
11862 static uint64_t call_recip_estimate(int *exp, int exp_off, uint64_t frac)
11863 {
11864     uint32_t scaled, estimate;
11865     uint64_t result_frac;
11866     int result_exp;
11867
11868     /* Handle sub-normals */
11869     if (*exp == 0) {
11870         if (extract64(frac, 51, 1) == 0) {
11871             *exp = -1;
11872             frac <<= 2;
11873         } else {
11874             frac <<= 1;
11875         }
11876     }
11877
11878     /* scaled = UInt('1':fraction<51:44>) */
11879     scaled = deposit32(1 << 8, 0, 8, extract64(frac, 44, 8));
11880     estimate = recip_estimate(scaled);
11881
11882     result_exp = exp_off - *exp;
11883     result_frac = deposit64(0, 44, 8, estimate);
11884     if (result_exp == 0) {
11885         result_frac = deposit64(result_frac >> 1, 51, 1, 1);
11886     } else if (result_exp == -1) {
11887         result_frac = deposit64(result_frac >> 2, 50, 2, 1);
11888         result_exp = 0;
11889     }
11890
11891     *exp = result_exp;
11892
11893     return result_frac;
11894 }
11895
11896 static bool round_to_inf(float_status *fpst, bool sign_bit)
11897 {
11898     switch (fpst->float_rounding_mode) {
11899     case float_round_nearest_even: /* Round to Nearest */
11900         return true;
11901     case float_round_up: /* Round to +Inf */
11902         return !sign_bit;
11903     case float_round_down: /* Round to -Inf */
11904         return sign_bit;
11905     case float_round_to_zero: /* Round to Zero */
11906         return false;
11907     }
11908
11909     g_assert_not_reached();
11910 }
11911
11912 uint32_t HELPER(recpe_f16)(uint32_t input, void *fpstp)
11913 {
11914     float_status *fpst = fpstp;
11915     float16 f16 = float16_squash_input_denormal(input, fpst);
11916     uint32_t f16_val = float16_val(f16);
11917     uint32_t f16_sign = float16_is_neg(f16);
11918     int f16_exp = extract32(f16_val, 10, 5);
11919     uint32_t f16_frac = extract32(f16_val, 0, 10);
11920     uint64_t f64_frac;
11921
11922     if (float16_is_any_nan(f16)) {
11923         float16 nan = f16;
11924         if (float16_is_signaling_nan(f16, fpst)) {
11925             float_raise(float_flag_invalid, fpst);
11926             nan = float16_silence_nan(f16, fpst);
11927         }
11928         if (fpst->default_nan_mode) {
11929             nan =  float16_default_nan(fpst);
11930         }
11931         return nan;
11932     } else if (float16_is_infinity(f16)) {
11933         return float16_set_sign(float16_zero, float16_is_neg(f16));
11934     } else if (float16_is_zero(f16)) {
11935         float_raise(float_flag_divbyzero, fpst);
11936         return float16_set_sign(float16_infinity, float16_is_neg(f16));
11937     } else if (float16_abs(f16) < (1 << 8)) {
11938         /* Abs(value) < 2.0^-16 */
11939         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11940         if (round_to_inf(fpst, f16_sign)) {
11941             return float16_set_sign(float16_infinity, f16_sign);
11942         } else {
11943             return float16_set_sign(float16_maxnorm, f16_sign);
11944         }
11945     } else if (f16_exp >= 29 && fpst->flush_to_zero) {
11946         float_raise(float_flag_underflow, fpst);
11947         return float16_set_sign(float16_zero, float16_is_neg(f16));
11948     }
11949
11950     f64_frac = call_recip_estimate(&f16_exp, 29,
11951                                    ((uint64_t) f16_frac) << (52 - 10));
11952
11953     /* result = sign : result_exp<4:0> : fraction<51:42> */
11954     f16_val = deposit32(0, 15, 1, f16_sign);
11955     f16_val = deposit32(f16_val, 10, 5, f16_exp);
11956     f16_val = deposit32(f16_val, 0, 10, extract64(f64_frac, 52 - 10, 10));
11957     return make_float16(f16_val);
11958 }
11959
11960 float32 HELPER(recpe_f32)(float32 input, void *fpstp)
11961 {
11962     float_status *fpst = fpstp;
11963     float32 f32 = float32_squash_input_denormal(input, fpst);
11964     uint32_t f32_val = float32_val(f32);
11965     bool f32_sign = float32_is_neg(f32);
11966     int f32_exp = extract32(f32_val, 23, 8);
11967     uint32_t f32_frac = extract32(f32_val, 0, 23);
11968     uint64_t f64_frac;
11969
11970     if (float32_is_any_nan(f32)) {
11971         float32 nan = f32;
11972         if (float32_is_signaling_nan(f32, fpst)) {
11973             float_raise(float_flag_invalid, fpst);
11974             nan = float32_silence_nan(f32, fpst);
11975         }
11976         if (fpst->default_nan_mode) {
11977             nan =  float32_default_nan(fpst);
11978         }
11979         return nan;
11980     } else if (float32_is_infinity(f32)) {
11981         return float32_set_sign(float32_zero, float32_is_neg(f32));
11982     } else if (float32_is_zero(f32)) {
11983         float_raise(float_flag_divbyzero, fpst);
11984         return float32_set_sign(float32_infinity, float32_is_neg(f32));
11985     } else if (float32_abs(f32) < (1ULL << 21)) {
11986         /* Abs(value) < 2.0^-128 */
11987         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11988         if (round_to_inf(fpst, f32_sign)) {
11989             return float32_set_sign(float32_infinity, f32_sign);
11990         } else {
11991             return float32_set_sign(float32_maxnorm, f32_sign);
11992         }
11993     } else if (f32_exp >= 253 && fpst->flush_to_zero) {
11994         float_raise(float_flag_underflow, fpst);
11995         return float32_set_sign(float32_zero, float32_is_neg(f32));
11996     }
11997
11998     f64_frac = call_recip_estimate(&f32_exp, 253,
11999                                    ((uint64_t) f32_frac) << (52 - 23));
12000
12001     /* result = sign : result_exp<7:0> : fraction<51:29> */
12002     f32_val = deposit32(0, 31, 1, f32_sign);
12003     f32_val = deposit32(f32_val, 23, 8, f32_exp);
12004     f32_val = deposit32(f32_val, 0, 23, extract64(f64_frac, 52 - 23, 23));
12005     return make_float32(f32_val);
12006 }
12007
12008 float64 HELPER(recpe_f64)(float64 input, void *fpstp)
12009 {
12010     float_status *fpst = fpstp;
12011     float64 f64 = float64_squash_input_denormal(input, fpst);
12012     uint64_t f64_val = float64_val(f64);
12013     bool f64_sign = float64_is_neg(f64);
12014     int f64_exp = extract64(f64_val, 52, 11);
12015     uint64_t f64_frac = extract64(f64_val, 0, 52);
12016
12017     /* Deal with any special cases */
12018     if (float64_is_any_nan(f64)) {
12019         float64 nan = f64;
12020         if (float64_is_signaling_nan(f64, fpst)) {
12021             float_raise(float_flag_invalid, fpst);
12022             nan = float64_silence_nan(f64, fpst);
12023         }
12024         if (fpst->default_nan_mode) {
12025             nan =  float64_default_nan(fpst);
12026         }
12027         return nan;
12028     } else if (float64_is_infinity(f64)) {
12029         return float64_set_sign(float64_zero, float64_is_neg(f64));
12030     } else if (float64_is_zero(f64)) {
12031         float_raise(float_flag_divbyzero, fpst);
12032         return float64_set_sign(float64_infinity, float64_is_neg(f64));
12033     } else if ((f64_val & ~(1ULL << 63)) < (1ULL << 50)) {
12034         /* Abs(value) < 2.0^-1024 */
12035         float_raise(float_flag_overflow | float_flag_inexact, fpst);
12036         if (round_to_inf(fpst, f64_sign)) {
12037             return float64_set_sign(float64_infinity, f64_sign);
12038         } else {
12039             return float64_set_sign(float64_maxnorm, f64_sign);
12040         }
12041     } else if (f64_exp >= 2045 && fpst->flush_to_zero) {
12042         float_raise(float_flag_underflow, fpst);
12043         return float64_set_sign(float64_zero, float64_is_neg(f64));
12044     }
12045
12046     f64_frac = call_recip_estimate(&f64_exp, 2045, f64_frac);
12047
12048     /* result = sign : result_exp<10:0> : fraction<51:0>; */
12049     f64_val = deposit64(0, 63, 1, f64_sign);
12050     f64_val = deposit64(f64_val, 52, 11, f64_exp);
12051     f64_val = deposit64(f64_val, 0, 52, f64_frac);
12052     return make_float64(f64_val);
12053 }
12054
12055 /* The algorithm that must be used to calculate the estimate
12056  * is specified by the ARM ARM.
12057  */
12058
12059 static int do_recip_sqrt_estimate(int a)
12060 {
12061     int b, estimate;
12062
12063     assert(128 <= a && a < 512);
12064     if (a < 256) {
12065         a = a * 2 + 1;
12066     } else {
12067         a = (a >> 1) << 1;
12068         a = (a + 1) * 2;
12069     }
12070     b = 512;
12071     while (a * (b + 1) * (b + 1) < (1 << 28)) {
12072         b += 1;
12073     }
12074     estimate = (b + 1) / 2;
12075     assert(256 <= estimate && estimate < 512);
12076
12077     return estimate;
12078 }
12079
12080
12081 static uint64_t recip_sqrt_estimate(int *exp , int exp_off, uint64_t frac)
12082 {
12083     int estimate;
12084     uint32_t scaled;
12085
12086     if (*exp == 0) {
12087         while (extract64(frac, 51, 1) == 0) {
12088             frac = frac << 1;
12089             *exp -= 1;
12090         }
12091         frac = extract64(frac, 0, 51) << 1;
12092     }
12093
12094     if (*exp & 1) {
12095         /* scaled = UInt('01':fraction<51:45>) */
12096         scaled = deposit32(1 << 7, 0, 7, extract64(frac, 45, 7));
12097     } else {
12098         /* scaled = UInt('1':fraction<51:44>) */
12099         scaled = deposit32(1 << 8, 0, 8, extract64(frac, 44, 8));
12100     }
12101     estimate = do_recip_sqrt_estimate(scaled);
12102
12103     *exp = (exp_off - *exp) / 2;
12104     return extract64(estimate, 0, 8) << 44;
12105 }
12106
12107 uint32_t HELPER(rsqrte_f16)(uint32_t input, void *fpstp)
12108 {
12109     float_status *s = fpstp;
12110     float16 f16 = float16_squash_input_denormal(input, s);
12111     uint16_t val = float16_val(f16);
12112     bool f16_sign = float16_is_neg(f16);
12113     int f16_exp = extract32(val, 10, 5);
12114     uint16_t f16_frac = extract32(val, 0, 10);
12115     uint64_t f64_frac;
12116
12117     if (float16_is_any_nan(f16)) {
12118         float16 nan = f16;
12119         if (float16_is_signaling_nan(f16, s)) {
12120             float_raise(float_flag_invalid, s);
12121             nan = float16_silence_nan(f16, s);
12122         }
12123         if (s->default_nan_mode) {
12124             nan =  float16_default_nan(s);
12125         }
12126         return nan;
12127     } else if (float16_is_zero(f16)) {
12128         float_raise(float_flag_divbyzero, s);
12129         return float16_set_sign(float16_infinity, f16_sign);
12130     } else if (f16_sign) {
12131         float_raise(float_flag_invalid, s);
12132         return float16_default_nan(s);
12133     } else if (float16_is_infinity(f16)) {
12134         return float16_zero;
12135     }
12136
12137     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
12138      * preserving the parity of the exponent.  */
12139
12140     f64_frac = ((uint64_t) f16_frac) << (52 - 10);
12141
12142     f64_frac = recip_sqrt_estimate(&f16_exp, 44, f64_frac);
12143
12144     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(2) */
12145     val = deposit32(0, 15, 1, f16_sign);
12146     val = deposit32(val, 10, 5, f16_exp);
12147     val = deposit32(val, 2, 8, extract64(f64_frac, 52 - 8, 8));
12148     return make_float16(val);
12149 }
12150
12151 float32 HELPER(rsqrte_f32)(float32 input, void *fpstp)
12152 {
12153     float_status *s = fpstp;
12154     float32 f32 = float32_squash_input_denormal(input, s);
12155     uint32_t val = float32_val(f32);
12156     uint32_t f32_sign = float32_is_neg(f32);
12157     int f32_exp = extract32(val, 23, 8);
12158     uint32_t f32_frac = extract32(val, 0, 23);
12159     uint64_t f64_frac;
12160
12161     if (float32_is_any_nan(f32)) {
12162         float32 nan = f32;
12163         if (float32_is_signaling_nan(f32, s)) {
12164             float_raise(float_flag_invalid, s);
12165             nan = float32_silence_nan(f32, s);
12166         }
12167         if (s->default_nan_mode) {
12168             nan =  float32_default_nan(s);
12169         }
12170         return nan;
12171     } else if (float32_is_zero(f32)) {
12172         float_raise(float_flag_divbyzero, s);
12173         return float32_set_sign(float32_infinity, float32_is_neg(f32));
12174     } else if (float32_is_neg(f32)) {
12175         float_raise(float_flag_invalid, s);
12176         return float32_default_nan(s);
12177     } else if (float32_is_infinity(f32)) {
12178         return float32_zero;
12179     }
12180
12181     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
12182      * preserving the parity of the exponent.  */
12183
12184     f64_frac = ((uint64_t) f32_frac) << 29;
12185
12186     f64_frac = recip_sqrt_estimate(&f32_exp, 380, f64_frac);
12187
12188     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(15) */
12189     val = deposit32(0, 31, 1, f32_sign);
12190     val = deposit32(val, 23, 8, f32_exp);
12191     val = deposit32(val, 15, 8, extract64(f64_frac, 52 - 8, 8));
12192     return make_float32(val);
12193 }
12194
12195 float64 HELPER(rsqrte_f64)(float64 input, void *fpstp)
12196 {
12197     float_status *s = fpstp;
12198     float64 f64 = float64_squash_input_denormal(input, s);
12199     uint64_t val = float64_val(f64);
12200     bool f64_sign = float64_is_neg(f64);
12201     int f64_exp = extract64(val, 52, 11);
12202     uint64_t f64_frac = extract64(val, 0, 52);
12203
12204     if (float64_is_any_nan(f64)) {
12205         float64 nan = f64;
12206         if (float64_is_signaling_nan(f64, s)) {
12207             float_raise(float_flag_invalid, s);
12208             nan = float64_silence_nan(f64, s);
12209         }
12210         if (s->default_nan_mode) {
12211             nan =  float64_default_nan(s);
12212         }
12213         return nan;
12214     } else if (float64_is_zero(f64)) {
12215         float_raise(float_flag_divbyzero, s);
12216         return float64_set_sign(float64_infinity, float64_is_neg(f64));
12217     } else if (float64_is_neg(f64)) {
12218         float_raise(float_flag_invalid, s);
12219         return float64_default_nan(s);
12220     } else if (float64_is_infinity(f64)) {
12221         return float64_zero;
12222     }
12223
12224     f64_frac = recip_sqrt_estimate(&f64_exp, 3068, f64_frac);
12225
12226     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(44) */
12227     val = deposit64(0, 61, 1, f64_sign);
12228     val = deposit64(val, 52, 11, f64_exp);
12229     val = deposit64(val, 44, 8, extract64(f64_frac, 52 - 8, 8));
12230     return make_float64(val);
12231 }
12232
12233 uint32_t HELPER(recpe_u32)(uint32_t a, void *fpstp)
12234 {
12235     /* float_status *s = fpstp; */
12236     int input, estimate;
12237
12238     if ((a & 0x80000000) == 0) {
12239         return 0xffffffff;
12240     }
12241
12242     input = extract32(a, 23, 9);
12243     estimate = recip_estimate(input);
12244
12245     return deposit32(0, (32 - 9), 9, estimate);
12246 }
12247
12248 uint32_t HELPER(rsqrte_u32)(uint32_t a, void *fpstp)
12249 {
12250     int estimate;
12251
12252     if ((a & 0xc0000000) == 0) {
12253         return 0xffffffff;
12254     }
12255
12256     estimate = do_recip_sqrt_estimate(extract32(a, 23, 9));
12257
12258     return deposit32(0, 23, 9, estimate);
12259 }
12260
12261 /* VFPv4 fused multiply-accumulate */
12262 float32 VFP_HELPER(muladd, s)(float32 a, float32 b, float32 c, void *fpstp)
12263 {
12264     float_status *fpst = fpstp;
12265     return float32_muladd(a, b, c, 0, fpst);
12266 }
12267
12268 float64 VFP_HELPER(muladd, d)(float64 a, float64 b, float64 c, void *fpstp)
12269 {
12270     float_status *fpst = fpstp;
12271     return float64_muladd(a, b, c, 0, fpst);
12272 }
12273
12274 /* ARMv8 round to integral */
12275 float32 HELPER(rints_exact)(float32 x, void *fp_status)
12276 {
12277     return float32_round_to_int(x, fp_status);
12278 }
12279
12280 float64 HELPER(rintd_exact)(float64 x, void *fp_status)
12281 {
12282     return float64_round_to_int(x, fp_status);
12283 }
12284
12285 float32 HELPER(rints)(float32 x, void *fp_status)
12286 {
12287     int old_flags = get_float_exception_flags(fp_status), new_flags;
12288     float32 ret;
12289
12290     ret = float32_round_to_int(x, fp_status);
12291
12292     /* Suppress any inexact exceptions the conversion produced */
12293     if (!(old_flags & float_flag_inexact)) {
12294         new_flags = get_float_exception_flags(fp_status);
12295         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
12296     }
12297
12298     return ret;
12299 }
12300
12301 float64 HELPER(rintd)(float64 x, void *fp_status)
12302 {
12303     int old_flags = get_float_exception_flags(fp_status), new_flags;
12304     float64 ret;
12305
12306     ret = float64_round_to_int(x, fp_status);
12307
12308     new_flags = get_float_exception_flags(fp_status);
12309
12310     /* Suppress any inexact exceptions the conversion produced */
12311     if (!(old_flags & float_flag_inexact)) {
12312         new_flags = get_float_exception_flags(fp_status);
12313         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
12314     }
12315
12316     return ret;
12317 }
12318
12319 /* Convert ARM rounding mode to softfloat */
12320 int arm_rmode_to_sf(int rmode)
12321 {
12322     switch (rmode) {
12323     case FPROUNDING_TIEAWAY:
12324         rmode = float_round_ties_away;
12325         break;
12326     case FPROUNDING_ODD:
12327         /* FIXME: add support for TIEAWAY and ODD */
12328         qemu_log_mask(LOG_UNIMP, "arm: unimplemented rounding mode: %d\n",
12329                       rmode);
12330     case FPROUNDING_TIEEVEN:
12331     default:
12332         rmode = float_round_nearest_even;
12333         break;
12334     case FPROUNDING_POSINF:
12335         rmode = float_round_up;
12336         break;
12337     case FPROUNDING_NEGINF:
12338         rmode = float_round_down;
12339         break;
12340     case FPROUNDING_ZERO:
12341         rmode = float_round_to_zero;
12342         break;
12343     }
12344     return rmode;
12345 }
12346
12347 /* CRC helpers.
12348  * The upper bytes of val (above the number specified by 'bytes') must have
12349  * been zeroed out by the caller.
12350  */
12351 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12352 {
12353     uint8_t buf[4];
12354
12355     stl_le_p(buf, val);
12356
12357     /* zlib crc32 converts the accumulator and output to one's complement.  */
12358     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12359 }
12360
12361 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12362 {
12363     uint8_t buf[4];
12364
12365     stl_le_p(buf, val);
12366
12367     /* Linux crc32c converts the output to one's complement.  */
12368     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12369 }
12370
12371 /* Return the exception level to which FP-disabled exceptions should
12372  * be taken, or 0 if FP is enabled.
12373  */
12374 static inline int fp_exception_el(CPUARMState *env)
12375 {
12376 #ifndef CONFIG_USER_ONLY
12377     int fpen;
12378     int cur_el = arm_current_el(env);
12379
12380     /* CPACR and the CPTR registers don't exist before v6, so FP is
12381      * always accessible
12382      */
12383     if (!arm_feature(env, ARM_FEATURE_V6)) {
12384         return 0;
12385     }
12386
12387     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12388      * 0, 2 : trap EL0 and EL1/PL1 accesses
12389      * 1    : trap only EL0 accesses
12390      * 3    : trap no accesses
12391      */
12392     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12393     switch (fpen) {
12394     case 0:
12395     case 2:
12396         if (cur_el == 0 || cur_el == 1) {
12397             /* Trap to PL1, which might be EL1 or EL3 */
12398             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12399                 return 3;
12400             }
12401             return 1;
12402         }
12403         if (cur_el == 3 && !is_a64(env)) {
12404             /* Secure PL1 running at EL3 */
12405             return 3;
12406         }
12407         break;
12408     case 1:
12409         if (cur_el == 0) {
12410             return 1;
12411         }
12412         break;
12413     case 3:
12414         break;
12415     }
12416
12417     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12418      * check because zero bits in the registers mean "don't trap".
12419      */
12420
12421     /* CPTR_EL2 : present in v7VE or v8 */
12422     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12423         && !arm_is_secure_below_el3(env)) {
12424         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12425         return 2;
12426     }
12427
12428     /* CPTR_EL3 : present in v8 */
12429     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12430         /* Trap all FP ops to EL3 */
12431         return 3;
12432     }
12433 #endif
12434     return 0;
12435 }
12436
12437 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
12438                           target_ulong *cs_base, uint32_t *pflags)
12439 {
12440     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
12441     int fp_el = fp_exception_el(env);
12442     uint32_t flags;
12443
12444     if (is_a64(env)) {
12445         int sve_el = sve_exception_el(env);
12446         uint32_t zcr_len;
12447
12448         *pc = env->pc;
12449         flags = ARM_TBFLAG_AARCH64_STATE_MASK;
12450         /* Get control bits for tagged addresses */
12451         flags |= (arm_regime_tbi0(env, mmu_idx) << ARM_TBFLAG_TBI0_SHIFT);
12452         flags |= (arm_regime_tbi1(env, mmu_idx) << ARM_TBFLAG_TBI1_SHIFT);
12453         flags |= sve_el << ARM_TBFLAG_SVEEXC_EL_SHIFT;
12454
12455         /* If SVE is disabled, but FP is enabled,
12456            then the effective len is 0.  */
12457         if (sve_el != 0 && fp_el == 0) {
12458             zcr_len = 0;
12459         } else {
12460             int current_el = arm_current_el(env);
12461             ARMCPU *cpu = arm_env_get_cpu(env);
12462
12463             zcr_len = cpu->sve_max_vq - 1;
12464             if (current_el <= 1) {
12465                 zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
12466             }
12467             if (current_el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
12468                 zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
12469             }
12470             if (current_el < 3 && arm_feature(env, ARM_FEATURE_EL3)) {
12471                 zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
12472             }
12473         }
12474         flags |= zcr_len << ARM_TBFLAG_ZCR_LEN_SHIFT;
12475     } else {
12476         *pc = env->regs[15];
12477         flags = (env->thumb << ARM_TBFLAG_THUMB_SHIFT)
12478             | (env->vfp.vec_len << ARM_TBFLAG_VECLEN_SHIFT)
12479             | (env->vfp.vec_stride << ARM_TBFLAG_VECSTRIDE_SHIFT)
12480             | (env->condexec_bits << ARM_TBFLAG_CONDEXEC_SHIFT)
12481             | (arm_sctlr_b(env) << ARM_TBFLAG_SCTLR_B_SHIFT);
12482         if (!(access_secure_reg(env))) {
12483             flags |= ARM_TBFLAG_NS_MASK;
12484         }
12485         if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)
12486             || arm_el_is_aa64(env, 1)) {
12487             flags |= ARM_TBFLAG_VFPEN_MASK;
12488         }
12489         flags |= (extract32(env->cp15.c15_cpar, 0, 2)
12490                   << ARM_TBFLAG_XSCALE_CPAR_SHIFT);
12491     }
12492
12493     flags |= (arm_to_core_mmu_idx(mmu_idx) << ARM_TBFLAG_MMUIDX_SHIFT);
12494
12495     /* The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
12496      * states defined in the ARM ARM for software singlestep:
12497      *  SS_ACTIVE   PSTATE.SS   State
12498      *     0            x       Inactive (the TB flag for SS is always 0)
12499      *     1            0       Active-pending
12500      *     1            1       Active-not-pending
12501      */
12502     if (arm_singlestep_active(env)) {
12503         flags |= ARM_TBFLAG_SS_ACTIVE_MASK;
12504         if (is_a64(env)) {
12505             if (env->pstate & PSTATE_SS) {
12506                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
12507             }
12508         } else {
12509             if (env->uncached_cpsr & PSTATE_SS) {
12510                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
12511             }
12512         }
12513     }
12514     if (arm_cpu_data_is_big_endian(env)) {
12515         flags |= ARM_TBFLAG_BE_DATA_MASK;
12516     }
12517     flags |= fp_el << ARM_TBFLAG_FPEXC_EL_SHIFT;
12518
12519     if (arm_v7m_is_handler_mode(env)) {
12520         flags |= ARM_TBFLAG_HANDLER_MASK;
12521     }
12522
12523     *pflags = flags;
12524     *cs_base = 0;
12525 }
This page took 0.718549 seconds and 4 git commands to generate.