]> Git Repo - qemu.git/blob - target/arm/helper.c
tcg: drop global lock during TCG code execution
[qemu.git] / target / arm / helper.c
1 #include "qemu/osdep.h"
2 #include "trace.h"
3 #include "cpu.h"
4 #include "internals.h"
5 #include "exec/gdbstub.h"
6 #include "exec/helper-proto.h"
7 #include "qemu/host-utils.h"
8 #include "sysemu/arch_init.h"
9 #include "sysemu/sysemu.h"
10 #include "qemu/bitops.h"
11 #include "qemu/crc32c.h"
12 #include "exec/exec-all.h"
13 #include "exec/cpu_ldst.h"
14 #include "arm_ldst.h"
15 #include <zlib.h> /* For crc32 */
16 #include "exec/semihost.h"
17 #include "sysemu/kvm.h"
18
19 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
20
21 #ifndef CONFIG_USER_ONLY
22 static bool get_phys_addr(CPUARMState *env, target_ulong address,
23                           int access_type, ARMMMUIdx mmu_idx,
24                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
25                           target_ulong *page_size, uint32_t *fsr,
26                           ARMMMUFaultInfo *fi);
27
28 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
29                                int access_type, ARMMMUIdx mmu_idx,
30                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
31                                target_ulong *page_size_ptr, uint32_t *fsr,
32                                ARMMMUFaultInfo *fi);
33
34 /* Definitions for the PMCCNTR and PMCR registers */
35 #define PMCRD   0x8
36 #define PMCRC   0x4
37 #define PMCRE   0x1
38 #endif
39
40 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
41 {
42     int nregs;
43
44     /* VFP data registers are always little-endian.  */
45     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
46     if (reg < nregs) {
47         stfq_le_p(buf, env->vfp.regs[reg]);
48         return 8;
49     }
50     if (arm_feature(env, ARM_FEATURE_NEON)) {
51         /* Aliases for Q regs.  */
52         nregs += 16;
53         if (reg < nregs) {
54             stfq_le_p(buf, env->vfp.regs[(reg - 32) * 2]);
55             stfq_le_p(buf + 8, env->vfp.regs[(reg - 32) * 2 + 1]);
56             return 16;
57         }
58     }
59     switch (reg - nregs) {
60     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
61     case 1: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSCR]); return 4;
62     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
63     }
64     return 0;
65 }
66
67 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
68 {
69     int nregs;
70
71     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
72     if (reg < nregs) {
73         env->vfp.regs[reg] = ldfq_le_p(buf);
74         return 8;
75     }
76     if (arm_feature(env, ARM_FEATURE_NEON)) {
77         nregs += 16;
78         if (reg < nregs) {
79             env->vfp.regs[(reg - 32) * 2] = ldfq_le_p(buf);
80             env->vfp.regs[(reg - 32) * 2 + 1] = ldfq_le_p(buf + 8);
81             return 16;
82         }
83     }
84     switch (reg - nregs) {
85     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
86     case 1: env->vfp.xregs[ARM_VFP_FPSCR] = ldl_p(buf); return 4;
87     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
88     }
89     return 0;
90 }
91
92 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
93 {
94     switch (reg) {
95     case 0 ... 31:
96         /* 128 bit FP register */
97         stfq_le_p(buf, env->vfp.regs[reg * 2]);
98         stfq_le_p(buf + 8, env->vfp.regs[reg * 2 + 1]);
99         return 16;
100     case 32:
101         /* FPSR */
102         stl_p(buf, vfp_get_fpsr(env));
103         return 4;
104     case 33:
105         /* FPCR */
106         stl_p(buf, vfp_get_fpcr(env));
107         return 4;
108     default:
109         return 0;
110     }
111 }
112
113 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
114 {
115     switch (reg) {
116     case 0 ... 31:
117         /* 128 bit FP register */
118         env->vfp.regs[reg * 2] = ldfq_le_p(buf);
119         env->vfp.regs[reg * 2 + 1] = ldfq_le_p(buf + 8);
120         return 16;
121     case 32:
122         /* FPSR */
123         vfp_set_fpsr(env, ldl_p(buf));
124         return 4;
125     case 33:
126         /* FPCR */
127         vfp_set_fpcr(env, ldl_p(buf));
128         return 4;
129     default:
130         return 0;
131     }
132 }
133
134 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
135 {
136     assert(ri->fieldoffset);
137     if (cpreg_field_is_64bit(ri)) {
138         return CPREG_FIELD64(env, ri);
139     } else {
140         return CPREG_FIELD32(env, ri);
141     }
142 }
143
144 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
145                       uint64_t value)
146 {
147     assert(ri->fieldoffset);
148     if (cpreg_field_is_64bit(ri)) {
149         CPREG_FIELD64(env, ri) = value;
150     } else {
151         CPREG_FIELD32(env, ri) = value;
152     }
153 }
154
155 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
156 {
157     return (char *)env + ri->fieldoffset;
158 }
159
160 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
161 {
162     /* Raw read of a coprocessor register (as needed for migration, etc). */
163     if (ri->type & ARM_CP_CONST) {
164         return ri->resetvalue;
165     } else if (ri->raw_readfn) {
166         return ri->raw_readfn(env, ri);
167     } else if (ri->readfn) {
168         return ri->readfn(env, ri);
169     } else {
170         return raw_read(env, ri);
171     }
172 }
173
174 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
175                              uint64_t v)
176 {
177     /* Raw write of a coprocessor register (as needed for migration, etc).
178      * Note that constant registers are treated as write-ignored; the
179      * caller should check for success by whether a readback gives the
180      * value written.
181      */
182     if (ri->type & ARM_CP_CONST) {
183         return;
184     } else if (ri->raw_writefn) {
185         ri->raw_writefn(env, ri, v);
186     } else if (ri->writefn) {
187         ri->writefn(env, ri, v);
188     } else {
189         raw_write(env, ri, v);
190     }
191 }
192
193 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
194 {
195    /* Return true if the regdef would cause an assertion if you called
196     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
197     * program bug for it not to have the NO_RAW flag).
198     * NB that returning false here doesn't necessarily mean that calling
199     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
200     * read/write access functions which are safe for raw use" from "has
201     * read/write access functions which have side effects but has forgotten
202     * to provide raw access functions".
203     * The tests here line up with the conditions in read/write_raw_cp_reg()
204     * and assertions in raw_read()/raw_write().
205     */
206     if ((ri->type & ARM_CP_CONST) ||
207         ri->fieldoffset ||
208         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
209         return false;
210     }
211     return true;
212 }
213
214 bool write_cpustate_to_list(ARMCPU *cpu)
215 {
216     /* Write the coprocessor state from cpu->env to the (index,value) list. */
217     int i;
218     bool ok = true;
219
220     for (i = 0; i < cpu->cpreg_array_len; i++) {
221         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
222         const ARMCPRegInfo *ri;
223
224         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
225         if (!ri) {
226             ok = false;
227             continue;
228         }
229         if (ri->type & ARM_CP_NO_RAW) {
230             continue;
231         }
232         cpu->cpreg_values[i] = read_raw_cp_reg(&cpu->env, ri);
233     }
234     return ok;
235 }
236
237 bool write_list_to_cpustate(ARMCPU *cpu)
238 {
239     int i;
240     bool ok = true;
241
242     for (i = 0; i < cpu->cpreg_array_len; i++) {
243         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
244         uint64_t v = cpu->cpreg_values[i];
245         const ARMCPRegInfo *ri;
246
247         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
248         if (!ri) {
249             ok = false;
250             continue;
251         }
252         if (ri->type & ARM_CP_NO_RAW) {
253             continue;
254         }
255         /* Write value and confirm it reads back as written
256          * (to catch read-only registers and partially read-only
257          * registers where the incoming migration value doesn't match)
258          */
259         write_raw_cp_reg(&cpu->env, ri, v);
260         if (read_raw_cp_reg(&cpu->env, ri) != v) {
261             ok = false;
262         }
263     }
264     return ok;
265 }
266
267 static void add_cpreg_to_list(gpointer key, gpointer opaque)
268 {
269     ARMCPU *cpu = opaque;
270     uint64_t regidx;
271     const ARMCPRegInfo *ri;
272
273     regidx = *(uint32_t *)key;
274     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
275
276     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
277         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
278         /* The value array need not be initialized at this point */
279         cpu->cpreg_array_len++;
280     }
281 }
282
283 static void count_cpreg(gpointer key, gpointer opaque)
284 {
285     ARMCPU *cpu = opaque;
286     uint64_t regidx;
287     const ARMCPRegInfo *ri;
288
289     regidx = *(uint32_t *)key;
290     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
291
292     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
293         cpu->cpreg_array_len++;
294     }
295 }
296
297 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
298 {
299     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
300     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
301
302     if (aidx > bidx) {
303         return 1;
304     }
305     if (aidx < bidx) {
306         return -1;
307     }
308     return 0;
309 }
310
311 void init_cpreg_list(ARMCPU *cpu)
312 {
313     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
314      * Note that we require cpreg_tuples[] to be sorted by key ID.
315      */
316     GList *keys;
317     int arraylen;
318
319     keys = g_hash_table_get_keys(cpu->cp_regs);
320     keys = g_list_sort(keys, cpreg_key_compare);
321
322     cpu->cpreg_array_len = 0;
323
324     g_list_foreach(keys, count_cpreg, cpu);
325
326     arraylen = cpu->cpreg_array_len;
327     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
328     cpu->cpreg_values = g_new(uint64_t, arraylen);
329     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
330     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
331     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
332     cpu->cpreg_array_len = 0;
333
334     g_list_foreach(keys, add_cpreg_to_list, cpu);
335
336     assert(cpu->cpreg_array_len == arraylen);
337
338     g_list_free(keys);
339 }
340
341 /*
342  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
343  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
344  *
345  * access_el3_aa32ns: Used to check AArch32 register views.
346  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
347  */
348 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
349                                         const ARMCPRegInfo *ri,
350                                         bool isread)
351 {
352     bool secure = arm_is_secure_below_el3(env);
353
354     assert(!arm_el_is_aa64(env, 3));
355     if (secure) {
356         return CP_ACCESS_TRAP_UNCATEGORIZED;
357     }
358     return CP_ACCESS_OK;
359 }
360
361 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
362                                                 const ARMCPRegInfo *ri,
363                                                 bool isread)
364 {
365     if (!arm_el_is_aa64(env, 3)) {
366         return access_el3_aa32ns(env, ri, isread);
367     }
368     return CP_ACCESS_OK;
369 }
370
371 /* Some secure-only AArch32 registers trap to EL3 if used from
372  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
373  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
374  * We assume that the .access field is set to PL1_RW.
375  */
376 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
377                                             const ARMCPRegInfo *ri,
378                                             bool isread)
379 {
380     if (arm_current_el(env) == 3) {
381         return CP_ACCESS_OK;
382     }
383     if (arm_is_secure_below_el3(env)) {
384         return CP_ACCESS_TRAP_EL3;
385     }
386     /* This will be EL1 NS and EL2 NS, which just UNDEF */
387     return CP_ACCESS_TRAP_UNCATEGORIZED;
388 }
389
390 /* Check for traps to "powerdown debug" registers, which are controlled
391  * by MDCR.TDOSA
392  */
393 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
394                                    bool isread)
395 {
396     int el = arm_current_el(env);
397
398     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDOSA)
399         && !arm_is_secure_below_el3(env)) {
400         return CP_ACCESS_TRAP_EL2;
401     }
402     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
403         return CP_ACCESS_TRAP_EL3;
404     }
405     return CP_ACCESS_OK;
406 }
407
408 /* Check for traps to "debug ROM" registers, which are controlled
409  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
410  */
411 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
412                                   bool isread)
413 {
414     int el = arm_current_el(env);
415
416     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDRA)
417         && !arm_is_secure_below_el3(env)) {
418         return CP_ACCESS_TRAP_EL2;
419     }
420     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
421         return CP_ACCESS_TRAP_EL3;
422     }
423     return CP_ACCESS_OK;
424 }
425
426 /* Check for traps to general debug registers, which are controlled
427  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
428  */
429 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
430                                   bool isread)
431 {
432     int el = arm_current_el(env);
433
434     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDA)
435         && !arm_is_secure_below_el3(env)) {
436         return CP_ACCESS_TRAP_EL2;
437     }
438     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
439         return CP_ACCESS_TRAP_EL3;
440     }
441     return CP_ACCESS_OK;
442 }
443
444 /* Check for traps to performance monitor registers, which are controlled
445  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
446  */
447 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
448                                  bool isread)
449 {
450     int el = arm_current_el(env);
451
452     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
453         && !arm_is_secure_below_el3(env)) {
454         return CP_ACCESS_TRAP_EL2;
455     }
456     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
457         return CP_ACCESS_TRAP_EL3;
458     }
459     return CP_ACCESS_OK;
460 }
461
462 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
463 {
464     ARMCPU *cpu = arm_env_get_cpu(env);
465
466     raw_write(env, ri, value);
467     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
468 }
469
470 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
471 {
472     ARMCPU *cpu = arm_env_get_cpu(env);
473
474     if (raw_read(env, ri) != value) {
475         /* Unlike real hardware the qemu TLB uses virtual addresses,
476          * not modified virtual addresses, so this causes a TLB flush.
477          */
478         tlb_flush(CPU(cpu));
479         raw_write(env, ri, value);
480     }
481 }
482
483 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
484                              uint64_t value)
485 {
486     ARMCPU *cpu = arm_env_get_cpu(env);
487
488     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_MPU)
489         && !extended_addresses_enabled(env)) {
490         /* For VMSA (when not using the LPAE long descriptor page table
491          * format) this register includes the ASID, so do a TLB flush.
492          * For PMSA it is purely a process ID and no action is needed.
493          */
494         tlb_flush(CPU(cpu));
495     }
496     raw_write(env, ri, value);
497 }
498
499 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
500                           uint64_t value)
501 {
502     /* Invalidate all (TLBIALL) */
503     ARMCPU *cpu = arm_env_get_cpu(env);
504
505     tlb_flush(CPU(cpu));
506 }
507
508 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
509                           uint64_t value)
510 {
511     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
512     ARMCPU *cpu = arm_env_get_cpu(env);
513
514     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
515 }
516
517 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
518                            uint64_t value)
519 {
520     /* Invalidate by ASID (TLBIASID) */
521     ARMCPU *cpu = arm_env_get_cpu(env);
522
523     tlb_flush(CPU(cpu));
524 }
525
526 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
527                            uint64_t value)
528 {
529     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
530     ARMCPU *cpu = arm_env_get_cpu(env);
531
532     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
533 }
534
535 /* IS variants of TLB operations must affect all cores */
536 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
537                              uint64_t value)
538 {
539     CPUState *other_cs;
540
541     CPU_FOREACH(other_cs) {
542         tlb_flush(other_cs);
543     }
544 }
545
546 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
547                              uint64_t value)
548 {
549     CPUState *other_cs;
550
551     CPU_FOREACH(other_cs) {
552         tlb_flush(other_cs);
553     }
554 }
555
556 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
557                              uint64_t value)
558 {
559     CPUState *other_cs;
560
561     CPU_FOREACH(other_cs) {
562         tlb_flush_page(other_cs, value & TARGET_PAGE_MASK);
563     }
564 }
565
566 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
567                              uint64_t value)
568 {
569     CPUState *other_cs;
570
571     CPU_FOREACH(other_cs) {
572         tlb_flush_page(other_cs, value & TARGET_PAGE_MASK);
573     }
574 }
575
576 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
577                                uint64_t value)
578 {
579     CPUState *cs = ENV_GET_CPU(env);
580
581     tlb_flush_by_mmuidx(cs, ARMMMUIdx_S12NSE1, ARMMMUIdx_S12NSE0,
582                         ARMMMUIdx_S2NS, -1);
583 }
584
585 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
586                                   uint64_t value)
587 {
588     CPUState *other_cs;
589
590     CPU_FOREACH(other_cs) {
591         tlb_flush_by_mmuidx(other_cs, ARMMMUIdx_S12NSE1,
592                             ARMMMUIdx_S12NSE0, ARMMMUIdx_S2NS, -1);
593     }
594 }
595
596 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
597                             uint64_t value)
598 {
599     /* Invalidate by IPA. This has to invalidate any structures that
600      * contain only stage 2 translation information, but does not need
601      * to apply to structures that contain combined stage 1 and stage 2
602      * translation information.
603      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
604      */
605     CPUState *cs = ENV_GET_CPU(env);
606     uint64_t pageaddr;
607
608     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
609         return;
610     }
611
612     pageaddr = sextract64(value << 12, 0, 40);
613
614     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdx_S2NS, -1);
615 }
616
617 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
618                                uint64_t value)
619 {
620     CPUState *other_cs;
621     uint64_t pageaddr;
622
623     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
624         return;
625     }
626
627     pageaddr = sextract64(value << 12, 0, 40);
628
629     CPU_FOREACH(other_cs) {
630         tlb_flush_page_by_mmuidx(other_cs, pageaddr, ARMMMUIdx_S2NS, -1);
631     }
632 }
633
634 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
635                               uint64_t value)
636 {
637     CPUState *cs = ENV_GET_CPU(env);
638
639     tlb_flush_by_mmuidx(cs, ARMMMUIdx_S1E2, -1);
640 }
641
642 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
643                                  uint64_t value)
644 {
645     CPUState *other_cs;
646
647     CPU_FOREACH(other_cs) {
648         tlb_flush_by_mmuidx(other_cs, ARMMMUIdx_S1E2, -1);
649     }
650 }
651
652 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
653                               uint64_t value)
654 {
655     CPUState *cs = ENV_GET_CPU(env);
656     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
657
658     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdx_S1E2, -1);
659 }
660
661 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
662                                  uint64_t value)
663 {
664     CPUState *other_cs;
665     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
666
667     CPU_FOREACH(other_cs) {
668         tlb_flush_page_by_mmuidx(other_cs, pageaddr, ARMMMUIdx_S1E2, -1);
669     }
670 }
671
672 static const ARMCPRegInfo cp_reginfo[] = {
673     /* Define the secure and non-secure FCSE identifier CP registers
674      * separately because there is no secure bank in V8 (no _EL3).  This allows
675      * the secure register to be properly reset and migrated. There is also no
676      * v8 EL1 version of the register so the non-secure instance stands alone.
677      */
678     { .name = "FCSEIDR(NS)",
679       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
680       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
681       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
682       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
683     { .name = "FCSEIDR(S)",
684       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
685       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
686       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
687       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
688     /* Define the secure and non-secure context identifier CP registers
689      * separately because there is no secure bank in V8 (no _EL3).  This allows
690      * the secure register to be properly reset and migrated.  In the
691      * non-secure case, the 32-bit register will have reset and migration
692      * disabled during registration as it is handled by the 64-bit instance.
693      */
694     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
695       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
696       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
697       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
698       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
699     { .name = "CONTEXTIDR(S)", .state = ARM_CP_STATE_AA32,
700       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
701       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
702       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
703       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
704     REGINFO_SENTINEL
705 };
706
707 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
708     /* NB: Some of these registers exist in v8 but with more precise
709      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
710      */
711     /* MMU Domain access control / MPU write buffer control */
712     { .name = "DACR",
713       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
714       .access = PL1_RW, .resetvalue = 0,
715       .writefn = dacr_write, .raw_writefn = raw_write,
716       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
717                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
718     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
719      * For v6 and v5, these mappings are overly broad.
720      */
721     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
722       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
723     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
724       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
725     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
726       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
727     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
728       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
729     /* Cache maintenance ops; some of this space may be overridden later. */
730     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
731       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
732       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
733     REGINFO_SENTINEL
734 };
735
736 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
737     /* Not all pre-v6 cores implemented this WFI, so this is slightly
738      * over-broad.
739      */
740     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
741       .access = PL1_W, .type = ARM_CP_WFI },
742     REGINFO_SENTINEL
743 };
744
745 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
746     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
747      * is UNPREDICTABLE; we choose to NOP as most implementations do).
748      */
749     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
750       .access = PL1_W, .type = ARM_CP_WFI },
751     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
752      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
753      * OMAPCP will override this space.
754      */
755     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
756       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
757       .resetvalue = 0 },
758     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
759       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
760       .resetvalue = 0 },
761     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
762     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
763       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
764       .resetvalue = 0 },
765     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
766      * implementing it as RAZ means the "debug architecture version" bits
767      * will read as a reserved value, which should cause Linux to not try
768      * to use the debug hardware.
769      */
770     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
771       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
772     /* MMU TLB control. Note that the wildcarding means we cover not just
773      * the unified TLB ops but also the dside/iside/inner-shareable variants.
774      */
775     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
776       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
777       .type = ARM_CP_NO_RAW },
778     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
779       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
780       .type = ARM_CP_NO_RAW },
781     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
782       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
783       .type = ARM_CP_NO_RAW },
784     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
785       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
786       .type = ARM_CP_NO_RAW },
787     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
788       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
789     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
790       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
791     REGINFO_SENTINEL
792 };
793
794 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
795                         uint64_t value)
796 {
797     uint32_t mask = 0;
798
799     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
800     if (!arm_feature(env, ARM_FEATURE_V8)) {
801         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
802          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
803          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
804          */
805         if (arm_feature(env, ARM_FEATURE_VFP)) {
806             /* VFP coprocessor: cp10 & cp11 [23:20] */
807             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
808
809             if (!arm_feature(env, ARM_FEATURE_NEON)) {
810                 /* ASEDIS [31] bit is RAO/WI */
811                 value |= (1 << 31);
812             }
813
814             /* VFPv3 and upwards with NEON implement 32 double precision
815              * registers (D0-D31).
816              */
817             if (!arm_feature(env, ARM_FEATURE_NEON) ||
818                     !arm_feature(env, ARM_FEATURE_VFP3)) {
819                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
820                 value |= (1 << 30);
821             }
822         }
823         value &= mask;
824     }
825     env->cp15.cpacr_el1 = value;
826 }
827
828 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
829                                    bool isread)
830 {
831     if (arm_feature(env, ARM_FEATURE_V8)) {
832         /* Check if CPACR accesses are to be trapped to EL2 */
833         if (arm_current_el(env) == 1 &&
834             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
835             return CP_ACCESS_TRAP_EL2;
836         /* Check if CPACR accesses are to be trapped to EL3 */
837         } else if (arm_current_el(env) < 3 &&
838                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
839             return CP_ACCESS_TRAP_EL3;
840         }
841     }
842
843     return CP_ACCESS_OK;
844 }
845
846 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
847                                   bool isread)
848 {
849     /* Check if CPTR accesses are set to trap to EL3 */
850     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
851         return CP_ACCESS_TRAP_EL3;
852     }
853
854     return CP_ACCESS_OK;
855 }
856
857 static const ARMCPRegInfo v6_cp_reginfo[] = {
858     /* prefetch by MVA in v6, NOP in v7 */
859     { .name = "MVA_prefetch",
860       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
861       .access = PL1_W, .type = ARM_CP_NOP },
862     /* We need to break the TB after ISB to execute self-modifying code
863      * correctly and also to take any pending interrupts immediately.
864      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
865      */
866     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
867       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
868     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
869       .access = PL0_W, .type = ARM_CP_NOP },
870     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
871       .access = PL0_W, .type = ARM_CP_NOP },
872     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
873       .access = PL1_RW,
874       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
875                              offsetof(CPUARMState, cp15.ifar_ns) },
876       .resetvalue = 0, },
877     /* Watchpoint Fault Address Register : should actually only be present
878      * for 1136, 1176, 11MPCore.
879      */
880     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
881       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
882     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
883       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
884       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
885       .resetvalue = 0, .writefn = cpacr_write },
886     REGINFO_SENTINEL
887 };
888
889 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
890                                    bool isread)
891 {
892     /* Performance monitor registers user accessibility is controlled
893      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
894      * trapping to EL2 or EL3 for other accesses.
895      */
896     int el = arm_current_el(env);
897
898     if (el == 0 && !env->cp15.c9_pmuserenr) {
899         return CP_ACCESS_TRAP;
900     }
901     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
902         && !arm_is_secure_below_el3(env)) {
903         return CP_ACCESS_TRAP_EL2;
904     }
905     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
906         return CP_ACCESS_TRAP_EL3;
907     }
908
909     return CP_ACCESS_OK;
910 }
911
912 #ifndef CONFIG_USER_ONLY
913
914 static inline bool arm_ccnt_enabled(CPUARMState *env)
915 {
916     /* This does not support checking PMCCFILTR_EL0 register */
917
918     if (!(env->cp15.c9_pmcr & PMCRE)) {
919         return false;
920     }
921
922     return true;
923 }
924
925 void pmccntr_sync(CPUARMState *env)
926 {
927     uint64_t temp_ticks;
928
929     temp_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
930                           ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
931
932     if (env->cp15.c9_pmcr & PMCRD) {
933         /* Increment once every 64 processor clock cycles */
934         temp_ticks /= 64;
935     }
936
937     if (arm_ccnt_enabled(env)) {
938         env->cp15.c15_ccnt = temp_ticks - env->cp15.c15_ccnt;
939     }
940 }
941
942 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
943                        uint64_t value)
944 {
945     pmccntr_sync(env);
946
947     if (value & PMCRC) {
948         /* The counter has been reset */
949         env->cp15.c15_ccnt = 0;
950     }
951
952     /* only the DP, X, D and E bits are writable */
953     env->cp15.c9_pmcr &= ~0x39;
954     env->cp15.c9_pmcr |= (value & 0x39);
955
956     pmccntr_sync(env);
957 }
958
959 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
960 {
961     uint64_t total_ticks;
962
963     if (!arm_ccnt_enabled(env)) {
964         /* Counter is disabled, do not change value */
965         return env->cp15.c15_ccnt;
966     }
967
968     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
969                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
970
971     if (env->cp15.c9_pmcr & PMCRD) {
972         /* Increment once every 64 processor clock cycles */
973         total_ticks /= 64;
974     }
975     return total_ticks - env->cp15.c15_ccnt;
976 }
977
978 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
979                          uint64_t value)
980 {
981     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
982      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
983      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
984      * accessed.
985      */
986     env->cp15.c9_pmselr = value & 0x1f;
987 }
988
989 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
990                         uint64_t value)
991 {
992     uint64_t total_ticks;
993
994     if (!arm_ccnt_enabled(env)) {
995         /* Counter is disabled, set the absolute value */
996         env->cp15.c15_ccnt = value;
997         return;
998     }
999
1000     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1001                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1002
1003     if (env->cp15.c9_pmcr & PMCRD) {
1004         /* Increment once every 64 processor clock cycles */
1005         total_ticks /= 64;
1006     }
1007     env->cp15.c15_ccnt = total_ticks - value;
1008 }
1009
1010 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1011                             uint64_t value)
1012 {
1013     uint64_t cur_val = pmccntr_read(env, NULL);
1014
1015     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1016 }
1017
1018 #else /* CONFIG_USER_ONLY */
1019
1020 void pmccntr_sync(CPUARMState *env)
1021 {
1022 }
1023
1024 #endif
1025
1026 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1027                             uint64_t value)
1028 {
1029     pmccntr_sync(env);
1030     env->cp15.pmccfiltr_el0 = value & 0x7E000000;
1031     pmccntr_sync(env);
1032 }
1033
1034 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1035                             uint64_t value)
1036 {
1037     value &= (1 << 31);
1038     env->cp15.c9_pmcnten |= value;
1039 }
1040
1041 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1042                              uint64_t value)
1043 {
1044     value &= (1 << 31);
1045     env->cp15.c9_pmcnten &= ~value;
1046 }
1047
1048 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1049                          uint64_t value)
1050 {
1051     env->cp15.c9_pmovsr &= ~value;
1052 }
1053
1054 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1055                              uint64_t value)
1056 {
1057     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1058      * PMSELR value is equal to or greater than the number of implemented
1059      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1060      */
1061     if (env->cp15.c9_pmselr == 0x1f) {
1062         pmccfiltr_write(env, ri, value);
1063     }
1064 }
1065
1066 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1067 {
1068     /* We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1069      * are CONSTRAINED UNPREDICTABLE. See comments in pmxevtyper_write().
1070      */
1071     if (env->cp15.c9_pmselr == 0x1f) {
1072         return env->cp15.pmccfiltr_el0;
1073     } else {
1074         return 0;
1075     }
1076 }
1077
1078 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1079                             uint64_t value)
1080 {
1081     env->cp15.c9_pmuserenr = value & 1;
1082 }
1083
1084 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1085                              uint64_t value)
1086 {
1087     /* We have no event counters so only the C bit can be changed */
1088     value &= (1 << 31);
1089     env->cp15.c9_pminten |= value;
1090 }
1091
1092 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1093                              uint64_t value)
1094 {
1095     value &= (1 << 31);
1096     env->cp15.c9_pminten &= ~value;
1097 }
1098
1099 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1100                        uint64_t value)
1101 {
1102     /* Note that even though the AArch64 view of this register has bits
1103      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1104      * architectural requirements for bits which are RES0 only in some
1105      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1106      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1107      */
1108     raw_write(env, ri, value & ~0x1FULL);
1109 }
1110
1111 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1112 {
1113     /* We only mask off bits that are RES0 both for AArch64 and AArch32.
1114      * For bits that vary between AArch32/64, code needs to check the
1115      * current execution mode before directly using the feature bit.
1116      */
1117     uint32_t valid_mask = SCR_AARCH64_MASK | SCR_AARCH32_MASK;
1118
1119     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1120         valid_mask &= ~SCR_HCE;
1121
1122         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1123          * supported if EL2 exists. The bit is UNK/SBZP when
1124          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1125          * when EL2 is unavailable.
1126          * On ARMv8, this bit is always available.
1127          */
1128         if (arm_feature(env, ARM_FEATURE_V7) &&
1129             !arm_feature(env, ARM_FEATURE_V8)) {
1130             valid_mask &= ~SCR_SMD;
1131         }
1132     }
1133
1134     /* Clear all-context RES0 bits.  */
1135     value &= valid_mask;
1136     raw_write(env, ri, value);
1137 }
1138
1139 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1140 {
1141     ARMCPU *cpu = arm_env_get_cpu(env);
1142
1143     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1144      * bank
1145      */
1146     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1147                                         ri->secure & ARM_CP_SECSTATE_S);
1148
1149     return cpu->ccsidr[index];
1150 }
1151
1152 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1153                          uint64_t value)
1154 {
1155     raw_write(env, ri, value & 0xf);
1156 }
1157
1158 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1159 {
1160     CPUState *cs = ENV_GET_CPU(env);
1161     uint64_t ret = 0;
1162
1163     if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1164         ret |= CPSR_I;
1165     }
1166     if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1167         ret |= CPSR_F;
1168     }
1169     /* External aborts are not possible in QEMU so A bit is always clear */
1170     return ret;
1171 }
1172
1173 static const ARMCPRegInfo v7_cp_reginfo[] = {
1174     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1175     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1176       .access = PL1_W, .type = ARM_CP_NOP },
1177     /* Performance monitors are implementation defined in v7,
1178      * but with an ARM recommended set of registers, which we
1179      * follow (although we don't actually implement any counters)
1180      *
1181      * Performance registers fall into three categories:
1182      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1183      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1184      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1185      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1186      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1187      */
1188     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1189       .access = PL0_RW, .type = ARM_CP_ALIAS,
1190       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1191       .writefn = pmcntenset_write,
1192       .accessfn = pmreg_access,
1193       .raw_writefn = raw_write },
1194     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1195       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1196       .access = PL0_RW, .accessfn = pmreg_access,
1197       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1198       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1199     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1200       .access = PL0_RW,
1201       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1202       .accessfn = pmreg_access,
1203       .writefn = pmcntenclr_write,
1204       .type = ARM_CP_ALIAS },
1205     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1206       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1207       .access = PL0_RW, .accessfn = pmreg_access,
1208       .type = ARM_CP_ALIAS,
1209       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1210       .writefn = pmcntenclr_write },
1211     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1212       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1213       .accessfn = pmreg_access,
1214       .writefn = pmovsr_write,
1215       .raw_writefn = raw_write },
1216     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1217       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1218       .access = PL0_RW, .accessfn = pmreg_access,
1219       .type = ARM_CP_ALIAS,
1220       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1221       .writefn = pmovsr_write,
1222       .raw_writefn = raw_write },
1223     /* Unimplemented so WI. */
1224     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1225       .access = PL0_W, .accessfn = pmreg_access, .type = ARM_CP_NOP },
1226 #ifndef CONFIG_USER_ONLY
1227     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1228       .access = PL0_RW, .type = ARM_CP_ALIAS,
1229       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1230       .accessfn = pmreg_access, .writefn = pmselr_write,
1231       .raw_writefn = raw_write},
1232     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1233       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1234       .access = PL0_RW, .accessfn = pmreg_access,
1235       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1236       .writefn = pmselr_write, .raw_writefn = raw_write, },
1237     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1238       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_IO,
1239       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1240       .accessfn = pmreg_access },
1241     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1242       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1243       .access = PL0_RW, .accessfn = pmreg_access,
1244       .type = ARM_CP_IO,
1245       .readfn = pmccntr_read, .writefn = pmccntr_write, },
1246 #endif
1247     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1248       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1249       .writefn = pmccfiltr_write,
1250       .access = PL0_RW, .accessfn = pmreg_access,
1251       .type = ARM_CP_IO,
1252       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1253       .resetvalue = 0, },
1254     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1255       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1256       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1257     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1258       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1259       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1260       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1261     /* Unimplemented, RAZ/WI. */
1262     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
1263       .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0,
1264       .accessfn = pmreg_access },
1265     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
1266       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
1267       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
1268       .resetvalue = 0,
1269       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1270     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
1271       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
1272       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1273       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
1274       .resetvalue = 0,
1275       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1276     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
1277       .access = PL1_RW, .accessfn = access_tpm,
1278       .type = ARM_CP_ALIAS,
1279       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
1280       .resetvalue = 0,
1281       .writefn = pmintenset_write, .raw_writefn = raw_write },
1282     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
1283       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
1284       .access = PL1_RW, .accessfn = access_tpm,
1285       .type = ARM_CP_IO,
1286       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1287       .writefn = pmintenset_write, .raw_writefn = raw_write,
1288       .resetvalue = 0x0 },
1289     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
1290       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1291       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1292       .writefn = pmintenclr_write, },
1293     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
1294       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
1295       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1296       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1297       .writefn = pmintenclr_write },
1298     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
1299       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
1300       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
1301     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
1302       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
1303       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
1304       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
1305                              offsetof(CPUARMState, cp15.csselr_ns) } },
1306     /* Auxiliary ID register: this actually has an IMPDEF value but for now
1307      * just RAZ for all cores:
1308      */
1309     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
1310       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
1311       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
1312     /* Auxiliary fault status registers: these also are IMPDEF, and we
1313      * choose to RAZ/WI for all cores.
1314      */
1315     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
1316       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
1317       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1318     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
1319       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
1320       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1321     /* MAIR can just read-as-written because we don't implement caches
1322      * and so don't need to care about memory attributes.
1323      */
1324     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
1325       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
1326       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
1327       .resetvalue = 0 },
1328     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
1329       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
1330       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
1331       .resetvalue = 0 },
1332     /* For non-long-descriptor page tables these are PRRR and NMRR;
1333      * regardless they still act as reads-as-written for QEMU.
1334      */
1335      /* MAIR0/1 are defined separately from their 64-bit counterpart which
1336       * allows them to assign the correct fieldoffset based on the endianness
1337       * handled in the field definitions.
1338       */
1339     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
1340       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
1341       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
1342                              offsetof(CPUARMState, cp15.mair0_ns) },
1343       .resetfn = arm_cp_reset_ignore },
1344     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
1345       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
1346       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
1347                              offsetof(CPUARMState, cp15.mair1_ns) },
1348       .resetfn = arm_cp_reset_ignore },
1349     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
1350       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
1351       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
1352     /* 32 bit ITLB invalidates */
1353     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
1354       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1355     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
1356       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1357     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
1358       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1359     /* 32 bit DTLB invalidates */
1360     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
1361       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1362     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
1363       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1364     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
1365       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1366     /* 32 bit TLB invalidates */
1367     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
1368       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1369     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
1370       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1371     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
1372       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1373     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
1374       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
1375     REGINFO_SENTINEL
1376 };
1377
1378 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
1379     /* 32 bit TLB invalidates, Inner Shareable */
1380     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
1381       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
1382     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
1383       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
1384     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
1385       .type = ARM_CP_NO_RAW, .access = PL1_W,
1386       .writefn = tlbiasid_is_write },
1387     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
1388       .type = ARM_CP_NO_RAW, .access = PL1_W,
1389       .writefn = tlbimvaa_is_write },
1390     REGINFO_SENTINEL
1391 };
1392
1393 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1394                         uint64_t value)
1395 {
1396     value &= 1;
1397     env->teecr = value;
1398 }
1399
1400 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1401                                     bool isread)
1402 {
1403     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
1404         return CP_ACCESS_TRAP;
1405     }
1406     return CP_ACCESS_OK;
1407 }
1408
1409 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
1410     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
1411       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
1412       .resetvalue = 0,
1413       .writefn = teecr_write },
1414     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
1415       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
1416       .accessfn = teehbr_access, .resetvalue = 0 },
1417     REGINFO_SENTINEL
1418 };
1419
1420 static const ARMCPRegInfo v6k_cp_reginfo[] = {
1421     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
1422       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
1423       .access = PL0_RW,
1424       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
1425     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
1426       .access = PL0_RW,
1427       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
1428                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
1429       .resetfn = arm_cp_reset_ignore },
1430     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
1431       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
1432       .access = PL0_R|PL1_W,
1433       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
1434       .resetvalue = 0},
1435     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
1436       .access = PL0_R|PL1_W,
1437       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
1438                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
1439       .resetfn = arm_cp_reset_ignore },
1440     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
1441       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
1442       .access = PL1_RW,
1443       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
1444     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
1445       .access = PL1_RW,
1446       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
1447                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
1448       .resetvalue = 0 },
1449     REGINFO_SENTINEL
1450 };
1451
1452 #ifndef CONFIG_USER_ONLY
1453
1454 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
1455                                        bool isread)
1456 {
1457     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
1458      * Writable only at the highest implemented exception level.
1459      */
1460     int el = arm_current_el(env);
1461
1462     switch (el) {
1463     case 0:
1464         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
1465             return CP_ACCESS_TRAP;
1466         }
1467         break;
1468     case 1:
1469         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
1470             arm_is_secure_below_el3(env)) {
1471             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
1472             return CP_ACCESS_TRAP_UNCATEGORIZED;
1473         }
1474         break;
1475     case 2:
1476     case 3:
1477         break;
1478     }
1479
1480     if (!isread && el < arm_highest_el(env)) {
1481         return CP_ACCESS_TRAP_UNCATEGORIZED;
1482     }
1483
1484     return CP_ACCESS_OK;
1485 }
1486
1487 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
1488                                         bool isread)
1489 {
1490     unsigned int cur_el = arm_current_el(env);
1491     bool secure = arm_is_secure(env);
1492
1493     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
1494     if (cur_el == 0 &&
1495         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
1496         return CP_ACCESS_TRAP;
1497     }
1498
1499     if (arm_feature(env, ARM_FEATURE_EL2) &&
1500         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1501         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
1502         return CP_ACCESS_TRAP_EL2;
1503     }
1504     return CP_ACCESS_OK;
1505 }
1506
1507 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
1508                                       bool isread)
1509 {
1510     unsigned int cur_el = arm_current_el(env);
1511     bool secure = arm_is_secure(env);
1512
1513     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
1514      * EL0[PV]TEN is zero.
1515      */
1516     if (cur_el == 0 &&
1517         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
1518         return CP_ACCESS_TRAP;
1519     }
1520
1521     if (arm_feature(env, ARM_FEATURE_EL2) &&
1522         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1523         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
1524         return CP_ACCESS_TRAP_EL2;
1525     }
1526     return CP_ACCESS_OK;
1527 }
1528
1529 static CPAccessResult gt_pct_access(CPUARMState *env,
1530                                     const ARMCPRegInfo *ri,
1531                                     bool isread)
1532 {
1533     return gt_counter_access(env, GTIMER_PHYS, isread);
1534 }
1535
1536 static CPAccessResult gt_vct_access(CPUARMState *env,
1537                                     const ARMCPRegInfo *ri,
1538                                     bool isread)
1539 {
1540     return gt_counter_access(env, GTIMER_VIRT, isread);
1541 }
1542
1543 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1544                                        bool isread)
1545 {
1546     return gt_timer_access(env, GTIMER_PHYS, isread);
1547 }
1548
1549 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1550                                        bool isread)
1551 {
1552     return gt_timer_access(env, GTIMER_VIRT, isread);
1553 }
1554
1555 static CPAccessResult gt_stimer_access(CPUARMState *env,
1556                                        const ARMCPRegInfo *ri,
1557                                        bool isread)
1558 {
1559     /* The AArch64 register view of the secure physical timer is
1560      * always accessible from EL3, and configurably accessible from
1561      * Secure EL1.
1562      */
1563     switch (arm_current_el(env)) {
1564     case 1:
1565         if (!arm_is_secure(env)) {
1566             return CP_ACCESS_TRAP;
1567         }
1568         if (!(env->cp15.scr_el3 & SCR_ST)) {
1569             return CP_ACCESS_TRAP_EL3;
1570         }
1571         return CP_ACCESS_OK;
1572     case 0:
1573     case 2:
1574         return CP_ACCESS_TRAP;
1575     case 3:
1576         return CP_ACCESS_OK;
1577     default:
1578         g_assert_not_reached();
1579     }
1580 }
1581
1582 static uint64_t gt_get_countervalue(CPUARMState *env)
1583 {
1584     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
1585 }
1586
1587 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
1588 {
1589     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
1590
1591     if (gt->ctl & 1) {
1592         /* Timer enabled: calculate and set current ISTATUS, irq, and
1593          * reset timer to when ISTATUS next has to change
1594          */
1595         uint64_t offset = timeridx == GTIMER_VIRT ?
1596                                       cpu->env.cp15.cntvoff_el2 : 0;
1597         uint64_t count = gt_get_countervalue(&cpu->env);
1598         /* Note that this must be unsigned 64 bit arithmetic: */
1599         int istatus = count - offset >= gt->cval;
1600         uint64_t nexttick;
1601         int irqstate;
1602
1603         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
1604
1605         irqstate = (istatus && !(gt->ctl & 2));
1606         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1607
1608         if (istatus) {
1609             /* Next transition is when count rolls back over to zero */
1610             nexttick = UINT64_MAX;
1611         } else {
1612             /* Next transition is when we hit cval */
1613             nexttick = gt->cval + offset;
1614         }
1615         /* Note that the desired next expiry time might be beyond the
1616          * signed-64-bit range of a QEMUTimer -- in this case we just
1617          * set the timer for as far in the future as possible. When the
1618          * timer expires we will reset the timer for any remaining period.
1619          */
1620         if (nexttick > INT64_MAX / GTIMER_SCALE) {
1621             nexttick = INT64_MAX / GTIMER_SCALE;
1622         }
1623         timer_mod(cpu->gt_timer[timeridx], nexttick);
1624         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
1625     } else {
1626         /* Timer disabled: ISTATUS and timer output always clear */
1627         gt->ctl &= ~4;
1628         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
1629         timer_del(cpu->gt_timer[timeridx]);
1630         trace_arm_gt_recalc_disabled(timeridx);
1631     }
1632 }
1633
1634 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
1635                            int timeridx)
1636 {
1637     ARMCPU *cpu = arm_env_get_cpu(env);
1638
1639     timer_del(cpu->gt_timer[timeridx]);
1640 }
1641
1642 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1643 {
1644     return gt_get_countervalue(env);
1645 }
1646
1647 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1648 {
1649     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
1650 }
1651
1652 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1653                           int timeridx,
1654                           uint64_t value)
1655 {
1656     trace_arm_gt_cval_write(timeridx, value);
1657     env->cp15.c14_timer[timeridx].cval = value;
1658     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1659 }
1660
1661 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
1662                              int timeridx)
1663 {
1664     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1665
1666     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
1667                       (gt_get_countervalue(env) - offset));
1668 }
1669
1670 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1671                           int timeridx,
1672                           uint64_t value)
1673 {
1674     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1675
1676     trace_arm_gt_tval_write(timeridx, value);
1677     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
1678                                          sextract64(value, 0, 32);
1679     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1680 }
1681
1682 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1683                          int timeridx,
1684                          uint64_t value)
1685 {
1686     ARMCPU *cpu = arm_env_get_cpu(env);
1687     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
1688
1689     trace_arm_gt_ctl_write(timeridx, value);
1690     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
1691     if ((oldval ^ value) & 1) {
1692         /* Enable toggled */
1693         gt_recalc_timer(cpu, timeridx);
1694     } else if ((oldval ^ value) & 2) {
1695         /* IMASK toggled: don't need to recalculate,
1696          * just set the interrupt line based on ISTATUS
1697          */
1698         int irqstate = (oldval & 4) && !(value & 2);
1699
1700         trace_arm_gt_imask_toggle(timeridx, irqstate);
1701         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1702     }
1703 }
1704
1705 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1706 {
1707     gt_timer_reset(env, ri, GTIMER_PHYS);
1708 }
1709
1710 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1711                                uint64_t value)
1712 {
1713     gt_cval_write(env, ri, GTIMER_PHYS, value);
1714 }
1715
1716 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1717 {
1718     return gt_tval_read(env, ri, GTIMER_PHYS);
1719 }
1720
1721 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1722                                uint64_t value)
1723 {
1724     gt_tval_write(env, ri, GTIMER_PHYS, value);
1725 }
1726
1727 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1728                               uint64_t value)
1729 {
1730     gt_ctl_write(env, ri, GTIMER_PHYS, value);
1731 }
1732
1733 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1734 {
1735     gt_timer_reset(env, ri, GTIMER_VIRT);
1736 }
1737
1738 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1739                                uint64_t value)
1740 {
1741     gt_cval_write(env, ri, GTIMER_VIRT, value);
1742 }
1743
1744 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1745 {
1746     return gt_tval_read(env, ri, GTIMER_VIRT);
1747 }
1748
1749 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1750                                uint64_t value)
1751 {
1752     gt_tval_write(env, ri, GTIMER_VIRT, value);
1753 }
1754
1755 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1756                               uint64_t value)
1757 {
1758     gt_ctl_write(env, ri, GTIMER_VIRT, value);
1759 }
1760
1761 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
1762                               uint64_t value)
1763 {
1764     ARMCPU *cpu = arm_env_get_cpu(env);
1765
1766     trace_arm_gt_cntvoff_write(value);
1767     raw_write(env, ri, value);
1768     gt_recalc_timer(cpu, GTIMER_VIRT);
1769 }
1770
1771 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1772 {
1773     gt_timer_reset(env, ri, GTIMER_HYP);
1774 }
1775
1776 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1777                               uint64_t value)
1778 {
1779     gt_cval_write(env, ri, GTIMER_HYP, value);
1780 }
1781
1782 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1783 {
1784     return gt_tval_read(env, ri, GTIMER_HYP);
1785 }
1786
1787 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1788                               uint64_t value)
1789 {
1790     gt_tval_write(env, ri, GTIMER_HYP, value);
1791 }
1792
1793 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1794                               uint64_t value)
1795 {
1796     gt_ctl_write(env, ri, GTIMER_HYP, value);
1797 }
1798
1799 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1800 {
1801     gt_timer_reset(env, ri, GTIMER_SEC);
1802 }
1803
1804 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1805                               uint64_t value)
1806 {
1807     gt_cval_write(env, ri, GTIMER_SEC, value);
1808 }
1809
1810 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1811 {
1812     return gt_tval_read(env, ri, GTIMER_SEC);
1813 }
1814
1815 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1816                               uint64_t value)
1817 {
1818     gt_tval_write(env, ri, GTIMER_SEC, value);
1819 }
1820
1821 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1822                               uint64_t value)
1823 {
1824     gt_ctl_write(env, ri, GTIMER_SEC, value);
1825 }
1826
1827 void arm_gt_ptimer_cb(void *opaque)
1828 {
1829     ARMCPU *cpu = opaque;
1830
1831     gt_recalc_timer(cpu, GTIMER_PHYS);
1832 }
1833
1834 void arm_gt_vtimer_cb(void *opaque)
1835 {
1836     ARMCPU *cpu = opaque;
1837
1838     gt_recalc_timer(cpu, GTIMER_VIRT);
1839 }
1840
1841 void arm_gt_htimer_cb(void *opaque)
1842 {
1843     ARMCPU *cpu = opaque;
1844
1845     gt_recalc_timer(cpu, GTIMER_HYP);
1846 }
1847
1848 void arm_gt_stimer_cb(void *opaque)
1849 {
1850     ARMCPU *cpu = opaque;
1851
1852     gt_recalc_timer(cpu, GTIMER_SEC);
1853 }
1854
1855 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
1856     /* Note that CNTFRQ is purely reads-as-written for the benefit
1857      * of software; writing it doesn't actually change the timer frequency.
1858      * Our reset value matches the fixed frequency we implement the timer at.
1859      */
1860     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
1861       .type = ARM_CP_ALIAS,
1862       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1863       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
1864     },
1865     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
1866       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
1867       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1868       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
1869       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
1870     },
1871     /* overall control: mostly access permissions */
1872     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
1873       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
1874       .access = PL1_RW,
1875       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
1876       .resetvalue = 0,
1877     },
1878     /* per-timer control */
1879     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
1880       .secure = ARM_CP_SECSTATE_NS,
1881       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
1882       .accessfn = gt_ptimer_access,
1883       .fieldoffset = offsetoflow32(CPUARMState,
1884                                    cp15.c14_timer[GTIMER_PHYS].ctl),
1885       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
1886     },
1887     { .name = "CNTP_CTL(S)",
1888       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
1889       .secure = ARM_CP_SECSTATE_S,
1890       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
1891       .accessfn = gt_ptimer_access,
1892       .fieldoffset = offsetoflow32(CPUARMState,
1893                                    cp15.c14_timer[GTIMER_SEC].ctl),
1894       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
1895     },
1896     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
1897       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
1898       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
1899       .accessfn = gt_ptimer_access,
1900       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
1901       .resetvalue = 0,
1902       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
1903     },
1904     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
1905       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
1906       .accessfn = gt_vtimer_access,
1907       .fieldoffset = offsetoflow32(CPUARMState,
1908                                    cp15.c14_timer[GTIMER_VIRT].ctl),
1909       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
1910     },
1911     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
1912       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
1913       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
1914       .accessfn = gt_vtimer_access,
1915       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
1916       .resetvalue = 0,
1917       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
1918     },
1919     /* TimerValue views: a 32 bit downcounting view of the underlying state */
1920     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
1921       .secure = ARM_CP_SECSTATE_NS,
1922       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
1923       .accessfn = gt_ptimer_access,
1924       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
1925     },
1926     { .name = "CNTP_TVAL(S)",
1927       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
1928       .secure = ARM_CP_SECSTATE_S,
1929       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
1930       .accessfn = gt_ptimer_access,
1931       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
1932     },
1933     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
1934       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
1935       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
1936       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
1937       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
1938     },
1939     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
1940       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
1941       .accessfn = gt_vtimer_access,
1942       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
1943     },
1944     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
1945       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
1946       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
1947       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
1948       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
1949     },
1950     /* The counter itself */
1951     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
1952       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
1953       .accessfn = gt_pct_access,
1954       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
1955     },
1956     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
1957       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
1958       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1959       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
1960     },
1961     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
1962       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
1963       .accessfn = gt_vct_access,
1964       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
1965     },
1966     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
1967       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
1968       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1969       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
1970     },
1971     /* Comparison value, indicating when the timer goes off */
1972     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
1973       .secure = ARM_CP_SECSTATE_NS,
1974       .access = PL1_RW | PL0_R,
1975       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
1976       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
1977       .accessfn = gt_ptimer_access,
1978       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
1979     },
1980     { .name = "CNTP_CVAL(S)", .cp = 15, .crm = 14, .opc1 = 2,
1981       .secure = ARM_CP_SECSTATE_S,
1982       .access = PL1_RW | PL0_R,
1983       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
1984       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
1985       .accessfn = gt_ptimer_access,
1986       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
1987     },
1988     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
1989       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
1990       .access = PL1_RW | PL0_R,
1991       .type = ARM_CP_IO,
1992       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
1993       .resetvalue = 0, .accessfn = gt_ptimer_access,
1994       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
1995     },
1996     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
1997       .access = PL1_RW | PL0_R,
1998       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
1999       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2000       .accessfn = gt_vtimer_access,
2001       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2002     },
2003     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2004       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2005       .access = PL1_RW | PL0_R,
2006       .type = ARM_CP_IO,
2007       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2008       .resetvalue = 0, .accessfn = gt_vtimer_access,
2009       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2010     },
2011     /* Secure timer -- this is actually restricted to only EL3
2012      * and configurably Secure-EL1 via the accessfn.
2013      */
2014     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2015       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2016       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2017       .accessfn = gt_stimer_access,
2018       .readfn = gt_sec_tval_read,
2019       .writefn = gt_sec_tval_write,
2020       .resetfn = gt_sec_timer_reset,
2021     },
2022     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2023       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2024       .type = ARM_CP_IO, .access = PL1_RW,
2025       .accessfn = gt_stimer_access,
2026       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2027       .resetvalue = 0,
2028       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2029     },
2030     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2031       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2032       .type = ARM_CP_IO, .access = PL1_RW,
2033       .accessfn = gt_stimer_access,
2034       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2035       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2036     },
2037     REGINFO_SENTINEL
2038 };
2039
2040 #else
2041 /* In user-mode none of the generic timer registers are accessible,
2042  * and their implementation depends on QEMU_CLOCK_VIRTUAL and qdev gpio outputs,
2043  * so instead just don't register any of them.
2044  */
2045 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2046     REGINFO_SENTINEL
2047 };
2048
2049 #endif
2050
2051 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2052 {
2053     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2054         raw_write(env, ri, value);
2055     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2056         raw_write(env, ri, value & 0xfffff6ff);
2057     } else {
2058         raw_write(env, ri, value & 0xfffff1ff);
2059     }
2060 }
2061
2062 #ifndef CONFIG_USER_ONLY
2063 /* get_phys_addr() isn't present for user-mode-only targets */
2064
2065 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2066                                  bool isread)
2067 {
2068     if (ri->opc2 & 4) {
2069         /* The ATS12NSO* operations must trap to EL3 if executed in
2070          * Secure EL1 (which can only happen if EL3 is AArch64).
2071          * They are simply UNDEF if executed from NS EL1.
2072          * They function normally from EL2 or EL3.
2073          */
2074         if (arm_current_el(env) == 1) {
2075             if (arm_is_secure_below_el3(env)) {
2076                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2077             }
2078             return CP_ACCESS_TRAP_UNCATEGORIZED;
2079         }
2080     }
2081     return CP_ACCESS_OK;
2082 }
2083
2084 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2085                              int access_type, ARMMMUIdx mmu_idx)
2086 {
2087     hwaddr phys_addr;
2088     target_ulong page_size;
2089     int prot;
2090     uint32_t fsr;
2091     bool ret;
2092     uint64_t par64;
2093     MemTxAttrs attrs = {};
2094     ARMMMUFaultInfo fi = {};
2095
2096     ret = get_phys_addr(env, value, access_type, mmu_idx,
2097                         &phys_addr, &attrs, &prot, &page_size, &fsr, &fi);
2098     if (extended_addresses_enabled(env)) {
2099         /* fsr is a DFSR/IFSR value for the long descriptor
2100          * translation table format, but with WnR always clear.
2101          * Convert it to a 64-bit PAR.
2102          */
2103         par64 = (1 << 11); /* LPAE bit always set */
2104         if (!ret) {
2105             par64 |= phys_addr & ~0xfffULL;
2106             if (!attrs.secure) {
2107                 par64 |= (1 << 9); /* NS */
2108             }
2109             /* We don't set the ATTR or SH fields in the PAR. */
2110         } else {
2111             par64 |= 1; /* F */
2112             par64 |= (fsr & 0x3f) << 1; /* FS */
2113             /* Note that S2WLK and FSTAGE are always zero, because we don't
2114              * implement virtualization and therefore there can't be a stage 2
2115              * fault.
2116              */
2117         }
2118     } else {
2119         /* fsr is a DFSR/IFSR value for the short descriptor
2120          * translation table format (with WnR always clear).
2121          * Convert it to a 32-bit PAR.
2122          */
2123         if (!ret) {
2124             /* We do not set any attribute bits in the PAR */
2125             if (page_size == (1 << 24)
2126                 && arm_feature(env, ARM_FEATURE_V7)) {
2127                 par64 = (phys_addr & 0xff000000) | (1 << 1);
2128             } else {
2129                 par64 = phys_addr & 0xfffff000;
2130             }
2131             if (!attrs.secure) {
2132                 par64 |= (1 << 9); /* NS */
2133             }
2134         } else {
2135             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
2136                     ((fsr & 0xf) << 1) | 1;
2137         }
2138     }
2139     return par64;
2140 }
2141
2142 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2143 {
2144     int access_type = ri->opc2 & 1;
2145     uint64_t par64;
2146     ARMMMUIdx mmu_idx;
2147     int el = arm_current_el(env);
2148     bool secure = arm_is_secure_below_el3(env);
2149
2150     switch (ri->opc2 & 6) {
2151     case 0:
2152         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
2153         switch (el) {
2154         case 3:
2155             mmu_idx = ARMMMUIdx_S1E3;
2156             break;
2157         case 2:
2158             mmu_idx = ARMMMUIdx_S1NSE1;
2159             break;
2160         case 1:
2161             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2162             break;
2163         default:
2164             g_assert_not_reached();
2165         }
2166         break;
2167     case 2:
2168         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
2169         switch (el) {
2170         case 3:
2171             mmu_idx = ARMMMUIdx_S1SE0;
2172             break;
2173         case 2:
2174             mmu_idx = ARMMMUIdx_S1NSE0;
2175             break;
2176         case 1:
2177             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2178             break;
2179         default:
2180             g_assert_not_reached();
2181         }
2182         break;
2183     case 4:
2184         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
2185         mmu_idx = ARMMMUIdx_S12NSE1;
2186         break;
2187     case 6:
2188         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
2189         mmu_idx = ARMMMUIdx_S12NSE0;
2190         break;
2191     default:
2192         g_assert_not_reached();
2193     }
2194
2195     par64 = do_ats_write(env, value, access_type, mmu_idx);
2196
2197     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2198 }
2199
2200 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
2201                         uint64_t value)
2202 {
2203     int access_type = ri->opc2 & 1;
2204     uint64_t par64;
2205
2206     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S2NS);
2207
2208     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2209 }
2210
2211 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
2212                                      bool isread)
2213 {
2214     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
2215         return CP_ACCESS_TRAP;
2216     }
2217     return CP_ACCESS_OK;
2218 }
2219
2220 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
2221                         uint64_t value)
2222 {
2223     int access_type = ri->opc2 & 1;
2224     ARMMMUIdx mmu_idx;
2225     int secure = arm_is_secure_below_el3(env);
2226
2227     switch (ri->opc2 & 6) {
2228     case 0:
2229         switch (ri->opc1) {
2230         case 0: /* AT S1E1R, AT S1E1W */
2231             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2232             break;
2233         case 4: /* AT S1E2R, AT S1E2W */
2234             mmu_idx = ARMMMUIdx_S1E2;
2235             break;
2236         case 6: /* AT S1E3R, AT S1E3W */
2237             mmu_idx = ARMMMUIdx_S1E3;
2238             break;
2239         default:
2240             g_assert_not_reached();
2241         }
2242         break;
2243     case 2: /* AT S1E0R, AT S1E0W */
2244         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2245         break;
2246     case 4: /* AT S12E1R, AT S12E1W */
2247         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
2248         break;
2249     case 6: /* AT S12E0R, AT S12E0W */
2250         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
2251         break;
2252     default:
2253         g_assert_not_reached();
2254     }
2255
2256     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
2257 }
2258 #endif
2259
2260 static const ARMCPRegInfo vapa_cp_reginfo[] = {
2261     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
2262       .access = PL1_RW, .resetvalue = 0,
2263       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
2264                              offsetoflow32(CPUARMState, cp15.par_ns) },
2265       .writefn = par_write },
2266 #ifndef CONFIG_USER_ONLY
2267     /* This underdecoding is safe because the reginfo is NO_RAW. */
2268     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
2269       .access = PL1_W, .accessfn = ats_access,
2270       .writefn = ats_write, .type = ARM_CP_NO_RAW },
2271 #endif
2272     REGINFO_SENTINEL
2273 };
2274
2275 /* Return basic MPU access permission bits.  */
2276 static uint32_t simple_mpu_ap_bits(uint32_t val)
2277 {
2278     uint32_t ret;
2279     uint32_t mask;
2280     int i;
2281     ret = 0;
2282     mask = 3;
2283     for (i = 0; i < 16; i += 2) {
2284         ret |= (val >> i) & mask;
2285         mask <<= 2;
2286     }
2287     return ret;
2288 }
2289
2290 /* Pad basic MPU access permission bits to extended format.  */
2291 static uint32_t extended_mpu_ap_bits(uint32_t val)
2292 {
2293     uint32_t ret;
2294     uint32_t mask;
2295     int i;
2296     ret = 0;
2297     mask = 3;
2298     for (i = 0; i < 16; i += 2) {
2299         ret |= (val & mask) << i;
2300         mask <<= 2;
2301     }
2302     return ret;
2303 }
2304
2305 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2306                                  uint64_t value)
2307 {
2308     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
2309 }
2310
2311 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2312 {
2313     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
2314 }
2315
2316 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2317                                  uint64_t value)
2318 {
2319     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
2320 }
2321
2322 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2323 {
2324     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
2325 }
2326
2327 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
2328 {
2329     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2330
2331     if (!u32p) {
2332         return 0;
2333     }
2334
2335     u32p += env->cp15.c6_rgnr;
2336     return *u32p;
2337 }
2338
2339 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
2340                          uint64_t value)
2341 {
2342     ARMCPU *cpu = arm_env_get_cpu(env);
2343     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2344
2345     if (!u32p) {
2346         return;
2347     }
2348
2349     u32p += env->cp15.c6_rgnr;
2350     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
2351     *u32p = value;
2352 }
2353
2354 static void pmsav7_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2355 {
2356     ARMCPU *cpu = arm_env_get_cpu(env);
2357     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2358
2359     if (!u32p) {
2360         return;
2361     }
2362
2363     memset(u32p, 0, sizeof(*u32p) * cpu->pmsav7_dregion);
2364 }
2365
2366 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2367                               uint64_t value)
2368 {
2369     ARMCPU *cpu = arm_env_get_cpu(env);
2370     uint32_t nrgs = cpu->pmsav7_dregion;
2371
2372     if (value >= nrgs) {
2373         qemu_log_mask(LOG_GUEST_ERROR,
2374                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
2375                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
2376         return;
2377     }
2378
2379     raw_write(env, ri, value);
2380 }
2381
2382 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
2383     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
2384       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2385       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
2386       .readfn = pmsav7_read, .writefn = pmsav7_write, .resetfn = pmsav7_reset },
2387     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
2388       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2389       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
2390       .readfn = pmsav7_read, .writefn = pmsav7_write, .resetfn = pmsav7_reset },
2391     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
2392       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2393       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
2394       .readfn = pmsav7_read, .writefn = pmsav7_write, .resetfn = pmsav7_reset },
2395     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
2396       .access = PL1_RW,
2397       .fieldoffset = offsetof(CPUARMState, cp15.c6_rgnr),
2398       .writefn = pmsav7_rgnr_write },
2399     REGINFO_SENTINEL
2400 };
2401
2402 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
2403     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2404       .access = PL1_RW, .type = ARM_CP_ALIAS,
2405       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2406       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
2407     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2408       .access = PL1_RW, .type = ARM_CP_ALIAS,
2409       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2410       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
2411     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
2412       .access = PL1_RW,
2413       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2414       .resetvalue = 0, },
2415     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
2416       .access = PL1_RW,
2417       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2418       .resetvalue = 0, },
2419     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
2420       .access = PL1_RW,
2421       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
2422     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
2423       .access = PL1_RW,
2424       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
2425     /* Protection region base and size registers */
2426     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
2427       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2428       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
2429     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
2430       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2431       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
2432     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
2433       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2434       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
2435     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
2436       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2437       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
2438     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
2439       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2440       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
2441     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
2442       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2443       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
2444     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
2445       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2446       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
2447     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
2448       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2449       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
2450     REGINFO_SENTINEL
2451 };
2452
2453 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
2454                                  uint64_t value)
2455 {
2456     TCR *tcr = raw_ptr(env, ri);
2457     int maskshift = extract32(value, 0, 3);
2458
2459     if (!arm_feature(env, ARM_FEATURE_V8)) {
2460         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
2461             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
2462              * using Long-desciptor translation table format */
2463             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
2464         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
2465             /* In an implementation that includes the Security Extensions
2466              * TTBCR has additional fields PD0 [4] and PD1 [5] for
2467              * Short-descriptor translation table format.
2468              */
2469             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
2470         } else {
2471             value &= TTBCR_N;
2472         }
2473     }
2474
2475     /* Update the masks corresponding to the TCR bank being written
2476      * Note that we always calculate mask and base_mask, but
2477      * they are only used for short-descriptor tables (ie if EAE is 0);
2478      * for long-descriptor tables the TCR fields are used differently
2479      * and the mask and base_mask values are meaningless.
2480      */
2481     tcr->raw_tcr = value;
2482     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
2483     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
2484 }
2485
2486 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2487                              uint64_t value)
2488 {
2489     ARMCPU *cpu = arm_env_get_cpu(env);
2490
2491     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2492         /* With LPAE the TTBCR could result in a change of ASID
2493          * via the TTBCR.A1 bit, so do a TLB flush.
2494          */
2495         tlb_flush(CPU(cpu));
2496     }
2497     vmsa_ttbcr_raw_write(env, ri, value);
2498 }
2499
2500 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2501 {
2502     TCR *tcr = raw_ptr(env, ri);
2503
2504     /* Reset both the TCR as well as the masks corresponding to the bank of
2505      * the TCR being reset.
2506      */
2507     tcr->raw_tcr = 0;
2508     tcr->mask = 0;
2509     tcr->base_mask = 0xffffc000u;
2510 }
2511
2512 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
2513                                uint64_t value)
2514 {
2515     ARMCPU *cpu = arm_env_get_cpu(env);
2516     TCR *tcr = raw_ptr(env, ri);
2517
2518     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
2519     tlb_flush(CPU(cpu));
2520     tcr->raw_tcr = value;
2521 }
2522
2523 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2524                             uint64_t value)
2525 {
2526     /* 64 bit accesses to the TTBRs can change the ASID and so we
2527      * must flush the TLB.
2528      */
2529     if (cpreg_field_is_64bit(ri)) {
2530         ARMCPU *cpu = arm_env_get_cpu(env);
2531
2532         tlb_flush(CPU(cpu));
2533     }
2534     raw_write(env, ri, value);
2535 }
2536
2537 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2538                         uint64_t value)
2539 {
2540     ARMCPU *cpu = arm_env_get_cpu(env);
2541     CPUState *cs = CPU(cpu);
2542
2543     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
2544     if (raw_read(env, ri) != value) {
2545         tlb_flush_by_mmuidx(cs, ARMMMUIdx_S12NSE1, ARMMMUIdx_S12NSE0,
2546                             ARMMMUIdx_S2NS, -1);
2547         raw_write(env, ri, value);
2548     }
2549 }
2550
2551 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
2552     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2553       .access = PL1_RW, .type = ARM_CP_ALIAS,
2554       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
2555                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
2556     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2557       .access = PL1_RW, .resetvalue = 0,
2558       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
2559                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
2560     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
2561       .access = PL1_RW, .resetvalue = 0,
2562       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
2563                              offsetof(CPUARMState, cp15.dfar_ns) } },
2564     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
2565       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
2566       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
2567       .resetvalue = 0, },
2568     REGINFO_SENTINEL
2569 };
2570
2571 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
2572     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
2573       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
2574       .access = PL1_RW,
2575       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
2576     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
2577       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
2578       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2579       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2580                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
2581     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
2582       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
2583       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2584       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2585                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
2586     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
2587       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2588       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
2589       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
2590       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
2591     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2592       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
2593       .raw_writefn = vmsa_ttbcr_raw_write,
2594       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
2595                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
2596     REGINFO_SENTINEL
2597 };
2598
2599 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
2600                                 uint64_t value)
2601 {
2602     env->cp15.c15_ticonfig = value & 0xe7;
2603     /* The OS_TYPE bit in this register changes the reported CPUID! */
2604     env->cp15.c0_cpuid = (value & (1 << 5)) ?
2605         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
2606 }
2607
2608 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
2609                                 uint64_t value)
2610 {
2611     env->cp15.c15_threadid = value & 0xffff;
2612 }
2613
2614 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
2615                            uint64_t value)
2616 {
2617     /* Wait-for-interrupt (deprecated) */
2618     cpu_interrupt(CPU(arm_env_get_cpu(env)), CPU_INTERRUPT_HALT);
2619 }
2620
2621 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
2622                                   uint64_t value)
2623 {
2624     /* On OMAP there are registers indicating the max/min index of dcache lines
2625      * containing a dirty line; cache flush operations have to reset these.
2626      */
2627     env->cp15.c15_i_max = 0x000;
2628     env->cp15.c15_i_min = 0xff0;
2629 }
2630
2631 static const ARMCPRegInfo omap_cp_reginfo[] = {
2632     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
2633       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
2634       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
2635       .resetvalue = 0, },
2636     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
2637       .access = PL1_RW, .type = ARM_CP_NOP },
2638     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
2639       .access = PL1_RW,
2640       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
2641       .writefn = omap_ticonfig_write },
2642     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
2643       .access = PL1_RW,
2644       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
2645     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
2646       .access = PL1_RW, .resetvalue = 0xff0,
2647       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
2648     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
2649       .access = PL1_RW,
2650       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
2651       .writefn = omap_threadid_write },
2652     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
2653       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2654       .type = ARM_CP_NO_RAW,
2655       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
2656     /* TODO: Peripheral port remap register:
2657      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
2658      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
2659      * when MMU is off.
2660      */
2661     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
2662       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
2663       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
2664       .writefn = omap_cachemaint_write },
2665     { .name = "C9", .cp = 15, .crn = 9,
2666       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
2667       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
2668     REGINFO_SENTINEL
2669 };
2670
2671 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2672                               uint64_t value)
2673 {
2674     env->cp15.c15_cpar = value & 0x3fff;
2675 }
2676
2677 static const ARMCPRegInfo xscale_cp_reginfo[] = {
2678     { .name = "XSCALE_CPAR",
2679       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2680       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
2681       .writefn = xscale_cpar_write, },
2682     { .name = "XSCALE_AUXCR",
2683       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
2684       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
2685       .resetvalue = 0, },
2686     /* XScale specific cache-lockdown: since we have no cache we NOP these
2687      * and hope the guest does not really rely on cache behaviour.
2688      */
2689     { .name = "XSCALE_LOCK_ICACHE_LINE",
2690       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
2691       .access = PL1_W, .type = ARM_CP_NOP },
2692     { .name = "XSCALE_UNLOCK_ICACHE",
2693       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
2694       .access = PL1_W, .type = ARM_CP_NOP },
2695     { .name = "XSCALE_DCACHE_LOCK",
2696       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
2697       .access = PL1_RW, .type = ARM_CP_NOP },
2698     { .name = "XSCALE_UNLOCK_DCACHE",
2699       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
2700       .access = PL1_W, .type = ARM_CP_NOP },
2701     REGINFO_SENTINEL
2702 };
2703
2704 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
2705     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
2706      * implementation of this implementation-defined space.
2707      * Ideally this should eventually disappear in favour of actually
2708      * implementing the correct behaviour for all cores.
2709      */
2710     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
2711       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2712       .access = PL1_RW,
2713       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
2714       .resetvalue = 0 },
2715     REGINFO_SENTINEL
2716 };
2717
2718 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
2719     /* Cache status: RAZ because we have no cache so it's always clean */
2720     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
2721       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2722       .resetvalue = 0 },
2723     REGINFO_SENTINEL
2724 };
2725
2726 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
2727     /* We never have a a block transfer operation in progress */
2728     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
2729       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2730       .resetvalue = 0 },
2731     /* The cache ops themselves: these all NOP for QEMU */
2732     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
2733       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2734     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
2735       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2736     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
2737       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2738     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
2739       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2740     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
2741       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2742     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
2743       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2744     REGINFO_SENTINEL
2745 };
2746
2747 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
2748     /* The cache test-and-clean instructions always return (1 << 30)
2749      * to indicate that there are no dirty cache lines.
2750      */
2751     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
2752       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2753       .resetvalue = (1 << 30) },
2754     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
2755       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2756       .resetvalue = (1 << 30) },
2757     REGINFO_SENTINEL
2758 };
2759
2760 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
2761     /* Ignore ReadBuffer accesses */
2762     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
2763       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2764       .access = PL1_RW, .resetvalue = 0,
2765       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
2766     REGINFO_SENTINEL
2767 };
2768
2769 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2770 {
2771     ARMCPU *cpu = arm_env_get_cpu(env);
2772     unsigned int cur_el = arm_current_el(env);
2773     bool secure = arm_is_secure(env);
2774
2775     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2776         return env->cp15.vpidr_el2;
2777     }
2778     return raw_read(env, ri);
2779 }
2780
2781 static uint64_t mpidr_read_val(CPUARMState *env)
2782 {
2783     ARMCPU *cpu = ARM_CPU(arm_env_get_cpu(env));
2784     uint64_t mpidr = cpu->mp_affinity;
2785
2786     if (arm_feature(env, ARM_FEATURE_V7MP)) {
2787         mpidr |= (1U << 31);
2788         /* Cores which are uniprocessor (non-coherent)
2789          * but still implement the MP extensions set
2790          * bit 30. (For instance, Cortex-R5).
2791          */
2792         if (cpu->mp_is_up) {
2793             mpidr |= (1u << 30);
2794         }
2795     }
2796     return mpidr;
2797 }
2798
2799 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2800 {
2801     unsigned int cur_el = arm_current_el(env);
2802     bool secure = arm_is_secure(env);
2803
2804     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2805         return env->cp15.vmpidr_el2;
2806     }
2807     return mpidr_read_val(env);
2808 }
2809
2810 static const ARMCPRegInfo mpidr_cp_reginfo[] = {
2811     { .name = "MPIDR", .state = ARM_CP_STATE_BOTH,
2812       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
2813       .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
2814     REGINFO_SENTINEL
2815 };
2816
2817 static const ARMCPRegInfo lpae_cp_reginfo[] = {
2818     /* NOP AMAIR0/1 */
2819     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
2820       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
2821       .access = PL1_RW, .type = ARM_CP_CONST,
2822       .resetvalue = 0 },
2823     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
2824     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
2825       .access = PL1_RW, .type = ARM_CP_CONST,
2826       .resetvalue = 0 },
2827     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
2828       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
2829       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
2830                              offsetof(CPUARMState, cp15.par_ns)} },
2831     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
2832       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
2833       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2834                              offsetof(CPUARMState, cp15.ttbr0_ns) },
2835       .writefn = vmsa_ttbr_write, },
2836     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
2837       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
2838       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2839                              offsetof(CPUARMState, cp15.ttbr1_ns) },
2840       .writefn = vmsa_ttbr_write, },
2841     REGINFO_SENTINEL
2842 };
2843
2844 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2845 {
2846     return vfp_get_fpcr(env);
2847 }
2848
2849 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2850                             uint64_t value)
2851 {
2852     vfp_set_fpcr(env, value);
2853 }
2854
2855 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2856 {
2857     return vfp_get_fpsr(env);
2858 }
2859
2860 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2861                             uint64_t value)
2862 {
2863     vfp_set_fpsr(env, value);
2864 }
2865
2866 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
2867                                        bool isread)
2868 {
2869     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
2870         return CP_ACCESS_TRAP;
2871     }
2872     return CP_ACCESS_OK;
2873 }
2874
2875 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
2876                             uint64_t value)
2877 {
2878     env->daif = value & PSTATE_DAIF;
2879 }
2880
2881 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
2882                                           const ARMCPRegInfo *ri,
2883                                           bool isread)
2884 {
2885     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
2886      * SCTLR_EL1.UCI is set.
2887      */
2888     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
2889         return CP_ACCESS_TRAP;
2890     }
2891     return CP_ACCESS_OK;
2892 }
2893
2894 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
2895  * Page D4-1736 (DDI0487A.b)
2896  */
2897
2898 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
2899                                     uint64_t value)
2900 {
2901     ARMCPU *cpu = arm_env_get_cpu(env);
2902     CPUState *cs = CPU(cpu);
2903
2904     if (arm_is_secure_below_el3(env)) {
2905         tlb_flush_by_mmuidx(cs, ARMMMUIdx_S1SE1, ARMMMUIdx_S1SE0, -1);
2906     } else {
2907         tlb_flush_by_mmuidx(cs, ARMMMUIdx_S12NSE1, ARMMMUIdx_S12NSE0, -1);
2908     }
2909 }
2910
2911 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
2912                                       uint64_t value)
2913 {
2914     bool sec = arm_is_secure_below_el3(env);
2915     CPUState *other_cs;
2916
2917     CPU_FOREACH(other_cs) {
2918         if (sec) {
2919             tlb_flush_by_mmuidx(other_cs, ARMMMUIdx_S1SE1, ARMMMUIdx_S1SE0, -1);
2920         } else {
2921             tlb_flush_by_mmuidx(other_cs, ARMMMUIdx_S12NSE1,
2922                                 ARMMMUIdx_S12NSE0, -1);
2923         }
2924     }
2925 }
2926
2927 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
2928                                   uint64_t value)
2929 {
2930     /* Note that the 'ALL' scope must invalidate both stage 1 and
2931      * stage 2 translations, whereas most other scopes only invalidate
2932      * stage 1 translations.
2933      */
2934     ARMCPU *cpu = arm_env_get_cpu(env);
2935     CPUState *cs = CPU(cpu);
2936
2937     if (arm_is_secure_below_el3(env)) {
2938         tlb_flush_by_mmuidx(cs, ARMMMUIdx_S1SE1, ARMMMUIdx_S1SE0, -1);
2939     } else {
2940         if (arm_feature(env, ARM_FEATURE_EL2)) {
2941             tlb_flush_by_mmuidx(cs, ARMMMUIdx_S12NSE1, ARMMMUIdx_S12NSE0,
2942                                 ARMMMUIdx_S2NS, -1);
2943         } else {
2944             tlb_flush_by_mmuidx(cs, ARMMMUIdx_S12NSE1, ARMMMUIdx_S12NSE0, -1);
2945         }
2946     }
2947 }
2948
2949 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
2950                                   uint64_t value)
2951 {
2952     ARMCPU *cpu = arm_env_get_cpu(env);
2953     CPUState *cs = CPU(cpu);
2954
2955     tlb_flush_by_mmuidx(cs, ARMMMUIdx_S1E2, -1);
2956 }
2957
2958 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
2959                                   uint64_t value)
2960 {
2961     ARMCPU *cpu = arm_env_get_cpu(env);
2962     CPUState *cs = CPU(cpu);
2963
2964     tlb_flush_by_mmuidx(cs, ARMMMUIdx_S1E3, -1);
2965 }
2966
2967 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
2968                                     uint64_t value)
2969 {
2970     /* Note that the 'ALL' scope must invalidate both stage 1 and
2971      * stage 2 translations, whereas most other scopes only invalidate
2972      * stage 1 translations.
2973      */
2974     bool sec = arm_is_secure_below_el3(env);
2975     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
2976     CPUState *other_cs;
2977
2978     CPU_FOREACH(other_cs) {
2979         if (sec) {
2980             tlb_flush_by_mmuidx(other_cs, ARMMMUIdx_S1SE1, ARMMMUIdx_S1SE0, -1);
2981         } else if (has_el2) {
2982             tlb_flush_by_mmuidx(other_cs, ARMMMUIdx_S12NSE1,
2983                                 ARMMMUIdx_S12NSE0, ARMMMUIdx_S2NS, -1);
2984         } else {
2985             tlb_flush_by_mmuidx(other_cs, ARMMMUIdx_S12NSE1,
2986                                 ARMMMUIdx_S12NSE0, -1);
2987         }
2988     }
2989 }
2990
2991 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
2992                                     uint64_t value)
2993 {
2994     CPUState *other_cs;
2995
2996     CPU_FOREACH(other_cs) {
2997         tlb_flush_by_mmuidx(other_cs, ARMMMUIdx_S1E2, -1);
2998     }
2999 }
3000
3001 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3002                                     uint64_t value)
3003 {
3004     CPUState *other_cs;
3005
3006     CPU_FOREACH(other_cs) {
3007         tlb_flush_by_mmuidx(other_cs, ARMMMUIdx_S1E3, -1);
3008     }
3009 }
3010
3011 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3012                                  uint64_t value)
3013 {
3014     /* Invalidate by VA, EL1&0 (AArch64 version).
3015      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3016      * since we don't support flush-for-specific-ASID-only or
3017      * flush-last-level-only.
3018      */
3019     ARMCPU *cpu = arm_env_get_cpu(env);
3020     CPUState *cs = CPU(cpu);
3021     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3022
3023     if (arm_is_secure_below_el3(env)) {
3024         tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdx_S1SE1,
3025                                  ARMMMUIdx_S1SE0, -1);
3026     } else {
3027         tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdx_S12NSE1,
3028                                  ARMMMUIdx_S12NSE0, -1);
3029     }
3030 }
3031
3032 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3033                                  uint64_t value)
3034 {
3035     /* Invalidate by VA, EL2
3036      * Currently handles both VAE2 and VALE2, since we don't support
3037      * flush-last-level-only.
3038      */
3039     ARMCPU *cpu = arm_env_get_cpu(env);
3040     CPUState *cs = CPU(cpu);
3041     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3042
3043     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdx_S1E2, -1);
3044 }
3045
3046 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3047                                  uint64_t value)
3048 {
3049     /* Invalidate by VA, EL3
3050      * Currently handles both VAE3 and VALE3, since we don't support
3051      * flush-last-level-only.
3052      */
3053     ARMCPU *cpu = arm_env_get_cpu(env);
3054     CPUState *cs = CPU(cpu);
3055     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3056
3057     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdx_S1E3, -1);
3058 }
3059
3060 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3061                                    uint64_t value)
3062 {
3063     bool sec = arm_is_secure_below_el3(env);
3064     CPUState *other_cs;
3065     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3066
3067     CPU_FOREACH(other_cs) {
3068         if (sec) {
3069             tlb_flush_page_by_mmuidx(other_cs, pageaddr, ARMMMUIdx_S1SE1,
3070                                      ARMMMUIdx_S1SE0, -1);
3071         } else {
3072             tlb_flush_page_by_mmuidx(other_cs, pageaddr, ARMMMUIdx_S12NSE1,
3073                                      ARMMMUIdx_S12NSE0, -1);
3074         }
3075     }
3076 }
3077
3078 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3079                                    uint64_t value)
3080 {
3081     CPUState *other_cs;
3082     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3083
3084     CPU_FOREACH(other_cs) {
3085         tlb_flush_page_by_mmuidx(other_cs, pageaddr, ARMMMUIdx_S1E2, -1);
3086     }
3087 }
3088
3089 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3090                                    uint64_t value)
3091 {
3092     CPUState *other_cs;
3093     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3094
3095     CPU_FOREACH(other_cs) {
3096         tlb_flush_page_by_mmuidx(other_cs, pageaddr, ARMMMUIdx_S1E3, -1);
3097     }
3098 }
3099
3100 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3101                                     uint64_t value)
3102 {
3103     /* Invalidate by IPA. This has to invalidate any structures that
3104      * contain only stage 2 translation information, but does not need
3105      * to apply to structures that contain combined stage 1 and stage 2
3106      * translation information.
3107      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
3108      */
3109     ARMCPU *cpu = arm_env_get_cpu(env);
3110     CPUState *cs = CPU(cpu);
3111     uint64_t pageaddr;
3112
3113     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3114         return;
3115     }
3116
3117     pageaddr = sextract64(value << 12, 0, 48);
3118
3119     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdx_S2NS, -1);
3120 }
3121
3122 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3123                                       uint64_t value)
3124 {
3125     CPUState *other_cs;
3126     uint64_t pageaddr;
3127
3128     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3129         return;
3130     }
3131
3132     pageaddr = sextract64(value << 12, 0, 48);
3133
3134     CPU_FOREACH(other_cs) {
3135         tlb_flush_page_by_mmuidx(other_cs, pageaddr, ARMMMUIdx_S2NS, -1);
3136     }
3137 }
3138
3139 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
3140                                       bool isread)
3141 {
3142     /* We don't implement EL2, so the only control on DC ZVA is the
3143      * bit in the SCTLR which can prohibit access for EL0.
3144      */
3145     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
3146         return CP_ACCESS_TRAP;
3147     }
3148     return CP_ACCESS_OK;
3149 }
3150
3151 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
3152 {
3153     ARMCPU *cpu = arm_env_get_cpu(env);
3154     int dzp_bit = 1 << 4;
3155
3156     /* DZP indicates whether DC ZVA access is allowed */
3157     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
3158         dzp_bit = 0;
3159     }
3160     return cpu->dcz_blocksize | dzp_bit;
3161 }
3162
3163 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
3164                                     bool isread)
3165 {
3166     if (!(env->pstate & PSTATE_SP)) {
3167         /* Access to SP_EL0 is undefined if it's being used as
3168          * the stack pointer.
3169          */
3170         return CP_ACCESS_TRAP_UNCATEGORIZED;
3171     }
3172     return CP_ACCESS_OK;
3173 }
3174
3175 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
3176 {
3177     return env->pstate & PSTATE_SP;
3178 }
3179
3180 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
3181 {
3182     update_spsel(env, val);
3183 }
3184
3185 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3186                         uint64_t value)
3187 {
3188     ARMCPU *cpu = arm_env_get_cpu(env);
3189
3190     if (raw_read(env, ri) == value) {
3191         /* Skip the TLB flush if nothing actually changed; Linux likes
3192          * to do a lot of pointless SCTLR writes.
3193          */
3194         return;
3195     }
3196
3197     raw_write(env, ri, value);
3198     /* ??? Lots of these bits are not implemented.  */
3199     /* This may enable/disable the MMU, so do a TLB flush.  */
3200     tlb_flush(CPU(cpu));
3201 }
3202
3203 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
3204                                      bool isread)
3205 {
3206     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
3207         return CP_ACCESS_TRAP_FP_EL2;
3208     }
3209     if (env->cp15.cptr_el[3] & CPTR_TFP) {
3210         return CP_ACCESS_TRAP_FP_EL3;
3211     }
3212     return CP_ACCESS_OK;
3213 }
3214
3215 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3216                        uint64_t value)
3217 {
3218     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
3219 }
3220
3221 static const ARMCPRegInfo v8_cp_reginfo[] = {
3222     /* Minimal set of EL0-visible registers. This will need to be expanded
3223      * significantly for system emulation of AArch64 CPUs.
3224      */
3225     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
3226       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
3227       .access = PL0_RW, .type = ARM_CP_NZCV },
3228     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
3229       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
3230       .type = ARM_CP_NO_RAW,
3231       .access = PL0_RW, .accessfn = aa64_daif_access,
3232       .fieldoffset = offsetof(CPUARMState, daif),
3233       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
3234     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
3235       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
3236       .access = PL0_RW, .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
3237     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
3238       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
3239       .access = PL0_RW, .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
3240     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
3241       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
3242       .access = PL0_R, .type = ARM_CP_NO_RAW,
3243       .readfn = aa64_dczid_read },
3244     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
3245       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
3246       .access = PL0_W, .type = ARM_CP_DC_ZVA,
3247 #ifndef CONFIG_USER_ONLY
3248       /* Avoid overhead of an access check that always passes in user-mode */
3249       .accessfn = aa64_zva_access,
3250 #endif
3251     },
3252     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
3253       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
3254       .access = PL1_R, .type = ARM_CP_CURRENTEL },
3255     /* Cache ops: all NOPs since we don't emulate caches */
3256     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
3257       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3258       .access = PL1_W, .type = ARM_CP_NOP },
3259     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
3260       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3261       .access = PL1_W, .type = ARM_CP_NOP },
3262     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
3263       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
3264       .access = PL0_W, .type = ARM_CP_NOP,
3265       .accessfn = aa64_cacheop_access },
3266     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
3267       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3268       .access = PL1_W, .type = ARM_CP_NOP },
3269     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
3270       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3271       .access = PL1_W, .type = ARM_CP_NOP },
3272     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
3273       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
3274       .access = PL0_W, .type = ARM_CP_NOP,
3275       .accessfn = aa64_cacheop_access },
3276     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
3277       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3278       .access = PL1_W, .type = ARM_CP_NOP },
3279     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
3280       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
3281       .access = PL0_W, .type = ARM_CP_NOP,
3282       .accessfn = aa64_cacheop_access },
3283     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
3284       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
3285       .access = PL0_W, .type = ARM_CP_NOP,
3286       .accessfn = aa64_cacheop_access },
3287     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
3288       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3289       .access = PL1_W, .type = ARM_CP_NOP },
3290     /* TLBI operations */
3291     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
3292       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
3293       .access = PL1_W, .type = ARM_CP_NO_RAW,
3294       .writefn = tlbi_aa64_vmalle1is_write },
3295     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
3296       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
3297       .access = PL1_W, .type = ARM_CP_NO_RAW,
3298       .writefn = tlbi_aa64_vae1is_write },
3299     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
3300       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
3301       .access = PL1_W, .type = ARM_CP_NO_RAW,
3302       .writefn = tlbi_aa64_vmalle1is_write },
3303     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
3304       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
3305       .access = PL1_W, .type = ARM_CP_NO_RAW,
3306       .writefn = tlbi_aa64_vae1is_write },
3307     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
3308       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3309       .access = PL1_W, .type = ARM_CP_NO_RAW,
3310       .writefn = tlbi_aa64_vae1is_write },
3311     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
3312       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3313       .access = PL1_W, .type = ARM_CP_NO_RAW,
3314       .writefn = tlbi_aa64_vae1is_write },
3315     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
3316       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
3317       .access = PL1_W, .type = ARM_CP_NO_RAW,
3318       .writefn = tlbi_aa64_vmalle1_write },
3319     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
3320       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
3321       .access = PL1_W, .type = ARM_CP_NO_RAW,
3322       .writefn = tlbi_aa64_vae1_write },
3323     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
3324       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
3325       .access = PL1_W, .type = ARM_CP_NO_RAW,
3326       .writefn = tlbi_aa64_vmalle1_write },
3327     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
3328       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
3329       .access = PL1_W, .type = ARM_CP_NO_RAW,
3330       .writefn = tlbi_aa64_vae1_write },
3331     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
3332       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3333       .access = PL1_W, .type = ARM_CP_NO_RAW,
3334       .writefn = tlbi_aa64_vae1_write },
3335     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
3336       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3337       .access = PL1_W, .type = ARM_CP_NO_RAW,
3338       .writefn = tlbi_aa64_vae1_write },
3339     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
3340       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3341       .access = PL2_W, .type = ARM_CP_NO_RAW,
3342       .writefn = tlbi_aa64_ipas2e1is_write },
3343     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
3344       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3345       .access = PL2_W, .type = ARM_CP_NO_RAW,
3346       .writefn = tlbi_aa64_ipas2e1is_write },
3347     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
3348       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3349       .access = PL2_W, .type = ARM_CP_NO_RAW,
3350       .writefn = tlbi_aa64_alle1is_write },
3351     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
3352       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
3353       .access = PL2_W, .type = ARM_CP_NO_RAW,
3354       .writefn = tlbi_aa64_alle1is_write },
3355     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
3356       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3357       .access = PL2_W, .type = ARM_CP_NO_RAW,
3358       .writefn = tlbi_aa64_ipas2e1_write },
3359     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
3360       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3361       .access = PL2_W, .type = ARM_CP_NO_RAW,
3362       .writefn = tlbi_aa64_ipas2e1_write },
3363     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
3364       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3365       .access = PL2_W, .type = ARM_CP_NO_RAW,
3366       .writefn = tlbi_aa64_alle1_write },
3367     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
3368       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
3369       .access = PL2_W, .type = ARM_CP_NO_RAW,
3370       .writefn = tlbi_aa64_alle1is_write },
3371 #ifndef CONFIG_USER_ONLY
3372     /* 64 bit address translation operations */
3373     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
3374       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
3375       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3376     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
3377       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
3378       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3379     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
3380       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
3381       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3382     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
3383       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
3384       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3385     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
3386       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
3387       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3388     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
3389       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
3390       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3391     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
3392       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
3393       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3394     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
3395       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
3396       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3397     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
3398     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
3399       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
3400       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3401     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
3402       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
3403       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3404     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
3405       .type = ARM_CP_ALIAS,
3406       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
3407       .access = PL1_RW, .resetvalue = 0,
3408       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
3409       .writefn = par_write },
3410 #endif
3411     /* TLB invalidate last level of translation table walk */
3412     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3413       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
3414     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3415       .type = ARM_CP_NO_RAW, .access = PL1_W,
3416       .writefn = tlbimvaa_is_write },
3417     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3418       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
3419     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3420       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
3421     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3422       .type = ARM_CP_NO_RAW, .access = PL2_W,
3423       .writefn = tlbimva_hyp_write },
3424     { .name = "TLBIMVALHIS",
3425       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3426       .type = ARM_CP_NO_RAW, .access = PL2_W,
3427       .writefn = tlbimva_hyp_is_write },
3428     { .name = "TLBIIPAS2",
3429       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3430       .type = ARM_CP_NO_RAW, .access = PL2_W,
3431       .writefn = tlbiipas2_write },
3432     { .name = "TLBIIPAS2IS",
3433       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3434       .type = ARM_CP_NO_RAW, .access = PL2_W,
3435       .writefn = tlbiipas2_is_write },
3436     { .name = "TLBIIPAS2L",
3437       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3438       .type = ARM_CP_NO_RAW, .access = PL2_W,
3439       .writefn = tlbiipas2_write },
3440     { .name = "TLBIIPAS2LIS",
3441       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3442       .type = ARM_CP_NO_RAW, .access = PL2_W,
3443       .writefn = tlbiipas2_is_write },
3444     /* 32 bit cache operations */
3445     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3446       .type = ARM_CP_NOP, .access = PL1_W },
3447     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
3448       .type = ARM_CP_NOP, .access = PL1_W },
3449     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3450       .type = ARM_CP_NOP, .access = PL1_W },
3451     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
3452       .type = ARM_CP_NOP, .access = PL1_W },
3453     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
3454       .type = ARM_CP_NOP, .access = PL1_W },
3455     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
3456       .type = ARM_CP_NOP, .access = PL1_W },
3457     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3458       .type = ARM_CP_NOP, .access = PL1_W },
3459     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3460       .type = ARM_CP_NOP, .access = PL1_W },
3461     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
3462       .type = ARM_CP_NOP, .access = PL1_W },
3463     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3464       .type = ARM_CP_NOP, .access = PL1_W },
3465     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
3466       .type = ARM_CP_NOP, .access = PL1_W },
3467     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
3468       .type = ARM_CP_NOP, .access = PL1_W },
3469     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3470       .type = ARM_CP_NOP, .access = PL1_W },
3471     /* MMU Domain access control / MPU write buffer control */
3472     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
3473       .access = PL1_RW, .resetvalue = 0,
3474       .writefn = dacr_write, .raw_writefn = raw_write,
3475       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
3476                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
3477     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
3478       .type = ARM_CP_ALIAS,
3479       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
3480       .access = PL1_RW,
3481       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
3482     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
3483       .type = ARM_CP_ALIAS,
3484       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
3485       .access = PL1_RW,
3486       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
3487     /* We rely on the access checks not allowing the guest to write to the
3488      * state field when SPSel indicates that it's being used as the stack
3489      * pointer.
3490      */
3491     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
3492       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
3493       .access = PL1_RW, .accessfn = sp_el0_access,
3494       .type = ARM_CP_ALIAS,
3495       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
3496     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
3497       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
3498       .access = PL2_RW, .type = ARM_CP_ALIAS,
3499       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
3500     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
3501       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
3502       .type = ARM_CP_NO_RAW,
3503       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
3504     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
3505       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
3506       .type = ARM_CP_ALIAS,
3507       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
3508       .access = PL2_RW, .accessfn = fpexc32_access },
3509     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
3510       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
3511       .access = PL2_RW, .resetvalue = 0,
3512       .writefn = dacr_write, .raw_writefn = raw_write,
3513       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
3514     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
3515       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
3516       .access = PL2_RW, .resetvalue = 0,
3517       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
3518     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
3519       .type = ARM_CP_ALIAS,
3520       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
3521       .access = PL2_RW,
3522       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
3523     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
3524       .type = ARM_CP_ALIAS,
3525       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
3526       .access = PL2_RW,
3527       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
3528     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
3529       .type = ARM_CP_ALIAS,
3530       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
3531       .access = PL2_RW,
3532       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
3533     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
3534       .type = ARM_CP_ALIAS,
3535       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
3536       .access = PL2_RW,
3537       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
3538     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
3539       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
3540       .resetvalue = 0,
3541       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
3542     { .name = "SDCR", .type = ARM_CP_ALIAS,
3543       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
3544       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
3545       .writefn = sdcr_write,
3546       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
3547     REGINFO_SENTINEL
3548 };
3549
3550 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
3551 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
3552     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3553       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3554       .access = PL2_RW,
3555       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3556     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3557       .type = ARM_CP_NO_RAW,
3558       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3559       .access = PL2_RW,
3560       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3561     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3562       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3563       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3564     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3565       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3566       .access = PL2_RW, .type = ARM_CP_CONST,
3567       .resetvalue = 0 },
3568     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3569       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3570       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3571     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3572       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3573       .access = PL2_RW, .type = ARM_CP_CONST,
3574       .resetvalue = 0 },
3575     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3576       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3577       .access = PL2_RW, .type = ARM_CP_CONST,
3578       .resetvalue = 0 },
3579     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3580       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3581       .access = PL2_RW, .type = ARM_CP_CONST,
3582       .resetvalue = 0 },
3583     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3584       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3585       .access = PL2_RW, .type = ARM_CP_CONST,
3586       .resetvalue = 0 },
3587     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3588       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3589       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3590     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
3591       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3592       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3593       .type = ARM_CP_CONST, .resetvalue = 0 },
3594     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3595       .cp = 15, .opc1 = 6, .crm = 2,
3596       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3597       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
3598     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3599       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3600       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3601     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3602       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3603       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3604     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3605       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3606       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3607     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3608       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3609       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3610     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3611       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3612       .resetvalue = 0 },
3613     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3614       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3615       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3616     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
3617       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
3618       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3619     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
3620       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3621       .resetvalue = 0 },
3622     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
3623       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
3624       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3625     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
3626       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3627       .resetvalue = 0 },
3628     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
3629       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
3630       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3631     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
3632       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
3633       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3634     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
3635       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
3636       .access = PL2_RW, .accessfn = access_tda,
3637       .type = ARM_CP_CONST, .resetvalue = 0 },
3638     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
3639       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
3640       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3641       .type = ARM_CP_CONST, .resetvalue = 0 },
3642     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
3643       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
3644       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3645     REGINFO_SENTINEL
3646 };
3647
3648 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3649 {
3650     ARMCPU *cpu = arm_env_get_cpu(env);
3651     uint64_t valid_mask = HCR_MASK;
3652
3653     if (arm_feature(env, ARM_FEATURE_EL3)) {
3654         valid_mask &= ~HCR_HCD;
3655     } else {
3656         valid_mask &= ~HCR_TSC;
3657     }
3658
3659     /* Clear RES0 bits.  */
3660     value &= valid_mask;
3661
3662     /* These bits change the MMU setup:
3663      * HCR_VM enables stage 2 translation
3664      * HCR_PTW forbids certain page-table setups
3665      * HCR_DC Disables stage1 and enables stage2 translation
3666      */
3667     if ((raw_read(env, ri) ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
3668         tlb_flush(CPU(cpu));
3669     }
3670     raw_write(env, ri, value);
3671 }
3672
3673 static const ARMCPRegInfo el2_cp_reginfo[] = {
3674     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3675       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3676       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
3677       .writefn = hcr_write },
3678     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
3679       .type = ARM_CP_ALIAS,
3680       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
3681       .access = PL2_RW,
3682       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
3683     { .name = "ESR_EL2", .state = ARM_CP_STATE_AA64,
3684       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
3685       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
3686     { .name = "FAR_EL2", .state = ARM_CP_STATE_AA64,
3687       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
3688       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
3689     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
3690       .type = ARM_CP_ALIAS,
3691       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
3692       .access = PL2_RW,
3693       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
3694     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3695       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3696       .access = PL2_RW, .writefn = vbar_write,
3697       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
3698       .resetvalue = 0 },
3699     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
3700       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
3701       .access = PL3_RW, .type = ARM_CP_ALIAS,
3702       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
3703     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3704       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3705       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
3706       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]) },
3707     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3708       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3709       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
3710       .resetvalue = 0 },
3711     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3712       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3713       .access = PL2_RW, .type = ARM_CP_ALIAS,
3714       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
3715     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3716       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3717       .access = PL2_RW, .type = ARM_CP_CONST,
3718       .resetvalue = 0 },
3719     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
3720     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3721       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3722       .access = PL2_RW, .type = ARM_CP_CONST,
3723       .resetvalue = 0 },
3724     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3725       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3726       .access = PL2_RW, .type = ARM_CP_CONST,
3727       .resetvalue = 0 },
3728     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3729       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3730       .access = PL2_RW, .type = ARM_CP_CONST,
3731       .resetvalue = 0 },
3732     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3733       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3734       .access = PL2_RW,
3735       /* no .writefn needed as this can't cause an ASID change;
3736        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3737        */
3738       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
3739     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
3740       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3741       .type = ARM_CP_ALIAS,
3742       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3743       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3744     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
3745       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3746       .access = PL2_RW,
3747       /* no .writefn needed as this can't cause an ASID change;
3748        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3749        */
3750       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3751     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3752       .cp = 15, .opc1 = 6, .crm = 2,
3753       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3754       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3755       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
3756       .writefn = vttbr_write },
3757     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3758       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3759       .access = PL2_RW, .writefn = vttbr_write,
3760       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
3761     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3762       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3763       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
3764       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
3765     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3766       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3767       .access = PL2_RW, .resetvalue = 0,
3768       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
3769     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3770       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3771       .access = PL2_RW, .resetvalue = 0,
3772       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3773     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3774       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3775       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3776     { .name = "TLBIALLNSNH",
3777       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3778       .type = ARM_CP_NO_RAW, .access = PL2_W,
3779       .writefn = tlbiall_nsnh_write },
3780     { .name = "TLBIALLNSNHIS",
3781       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3782       .type = ARM_CP_NO_RAW, .access = PL2_W,
3783       .writefn = tlbiall_nsnh_is_write },
3784     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3785       .type = ARM_CP_NO_RAW, .access = PL2_W,
3786       .writefn = tlbiall_hyp_write },
3787     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
3788       .type = ARM_CP_NO_RAW, .access = PL2_W,
3789       .writefn = tlbiall_hyp_is_write },
3790     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
3791       .type = ARM_CP_NO_RAW, .access = PL2_W,
3792       .writefn = tlbimva_hyp_write },
3793     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
3794       .type = ARM_CP_NO_RAW, .access = PL2_W,
3795       .writefn = tlbimva_hyp_is_write },
3796     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
3797       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3798       .type = ARM_CP_NO_RAW, .access = PL2_W,
3799       .writefn = tlbi_aa64_alle2_write },
3800     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
3801       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
3802       .type = ARM_CP_NO_RAW, .access = PL2_W,
3803       .writefn = tlbi_aa64_vae2_write },
3804     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
3805       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3806       .access = PL2_W, .type = ARM_CP_NO_RAW,
3807       .writefn = tlbi_aa64_vae2_write },
3808     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
3809       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
3810       .access = PL2_W, .type = ARM_CP_NO_RAW,
3811       .writefn = tlbi_aa64_alle2is_write },
3812     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
3813       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
3814       .type = ARM_CP_NO_RAW, .access = PL2_W,
3815       .writefn = tlbi_aa64_vae2is_write },
3816     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
3817       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3818       .access = PL2_W, .type = ARM_CP_NO_RAW,
3819       .writefn = tlbi_aa64_vae2is_write },
3820 #ifndef CONFIG_USER_ONLY
3821     /* Unlike the other EL2-related AT operations, these must
3822      * UNDEF from EL3 if EL2 is not implemented, which is why we
3823      * define them here rather than with the rest of the AT ops.
3824      */
3825     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
3826       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
3827       .access = PL2_W, .accessfn = at_s1e2_access,
3828       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3829     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
3830       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
3831       .access = PL2_W, .accessfn = at_s1e2_access,
3832       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3833     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
3834      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
3835      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
3836      * to behave as if SCR.NS was 1.
3837      */
3838     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
3839       .access = PL2_W,
3840       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
3841     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
3842       .access = PL2_W,
3843       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
3844     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3845       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3846       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
3847        * reset values as IMPDEF. We choose to reset to 3 to comply with
3848        * both ARMv7 and ARMv8.
3849        */
3850       .access = PL2_RW, .resetvalue = 3,
3851       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
3852     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
3853       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
3854       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
3855       .writefn = gt_cntvoff_write,
3856       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
3857     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
3858       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
3859       .writefn = gt_cntvoff_write,
3860       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
3861     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
3862       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
3863       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
3864       .type = ARM_CP_IO, .access = PL2_RW,
3865       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
3866     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
3867       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
3868       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
3869       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
3870     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
3871       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
3872       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
3873       .resetfn = gt_hyp_timer_reset,
3874       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
3875     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
3876       .type = ARM_CP_IO,
3877       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
3878       .access = PL2_RW,
3879       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
3880       .resetvalue = 0,
3881       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
3882 #endif
3883     /* The only field of MDCR_EL2 that has a defined architectural reset value
3884      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
3885      * don't impelment any PMU event counters, so using zero as a reset
3886      * value for MDCR_EL2 is okay
3887      */
3888     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
3889       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
3890       .access = PL2_RW, .resetvalue = 0,
3891       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
3892     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
3893       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
3894       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3895       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
3896     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
3897       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
3898       .access = PL2_RW,
3899       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
3900     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
3901       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
3902       .access = PL2_RW,
3903       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
3904     REGINFO_SENTINEL
3905 };
3906
3907 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
3908                                    bool isread)
3909 {
3910     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
3911      * At Secure EL1 it traps to EL3.
3912      */
3913     if (arm_current_el(env) == 3) {
3914         return CP_ACCESS_OK;
3915     }
3916     if (arm_is_secure_below_el3(env)) {
3917         return CP_ACCESS_TRAP_EL3;
3918     }
3919     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
3920     if (isread) {
3921         return CP_ACCESS_OK;
3922     }
3923     return CP_ACCESS_TRAP_UNCATEGORIZED;
3924 }
3925
3926 static const ARMCPRegInfo el3_cp_reginfo[] = {
3927     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
3928       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
3929       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
3930       .resetvalue = 0, .writefn = scr_write },
3931     { .name = "SCR",  .type = ARM_CP_ALIAS,
3932       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
3933       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
3934       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
3935       .writefn = scr_write },
3936     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
3937       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
3938       .access = PL3_RW, .resetvalue = 0,
3939       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
3940     { .name = "SDER",
3941       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
3942       .access = PL3_RW, .resetvalue = 0,
3943       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
3944     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
3945       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
3946       .writefn = vbar_write, .resetvalue = 0,
3947       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
3948     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
3949       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
3950       .access = PL3_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3951       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
3952     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
3953       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
3954       .access = PL3_RW,
3955       /* no .writefn needed as this can't cause an ASID change;
3956        * we must provide a .raw_writefn and .resetfn because we handle
3957        * reset and migration for the AArch32 TTBCR(S), which might be
3958        * using mask and base_mask.
3959        */
3960       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
3961       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
3962     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
3963       .type = ARM_CP_ALIAS,
3964       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
3965       .access = PL3_RW,
3966       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
3967     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
3968       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
3969       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
3970     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
3971       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
3972       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
3973     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
3974       .type = ARM_CP_ALIAS,
3975       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
3976       .access = PL3_RW,
3977       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
3978     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
3979       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
3980       .access = PL3_RW, .writefn = vbar_write,
3981       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
3982       .resetvalue = 0 },
3983     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
3984       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
3985       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
3986       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
3987     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
3988       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
3989       .access = PL3_RW, .resetvalue = 0,
3990       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
3991     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
3992       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
3993       .access = PL3_RW, .type = ARM_CP_CONST,
3994       .resetvalue = 0 },
3995     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
3996       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
3997       .access = PL3_RW, .type = ARM_CP_CONST,
3998       .resetvalue = 0 },
3999     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
4000       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
4001       .access = PL3_RW, .type = ARM_CP_CONST,
4002       .resetvalue = 0 },
4003     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
4004       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
4005       .access = PL3_W, .type = ARM_CP_NO_RAW,
4006       .writefn = tlbi_aa64_alle3is_write },
4007     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
4008       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
4009       .access = PL3_W, .type = ARM_CP_NO_RAW,
4010       .writefn = tlbi_aa64_vae3is_write },
4011     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
4012       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
4013       .access = PL3_W, .type = ARM_CP_NO_RAW,
4014       .writefn = tlbi_aa64_vae3is_write },
4015     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
4016       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
4017       .access = PL3_W, .type = ARM_CP_NO_RAW,
4018       .writefn = tlbi_aa64_alle3_write },
4019     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
4020       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
4021       .access = PL3_W, .type = ARM_CP_NO_RAW,
4022       .writefn = tlbi_aa64_vae3_write },
4023     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
4024       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
4025       .access = PL3_W, .type = ARM_CP_NO_RAW,
4026       .writefn = tlbi_aa64_vae3_write },
4027     REGINFO_SENTINEL
4028 };
4029
4030 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4031                                      bool isread)
4032 {
4033     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
4034      * but the AArch32 CTR has its own reginfo struct)
4035      */
4036     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
4037         return CP_ACCESS_TRAP;
4038     }
4039     return CP_ACCESS_OK;
4040 }
4041
4042 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4043                         uint64_t value)
4044 {
4045     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
4046      * read via a bit in OSLSR_EL1.
4047      */
4048     int oslock;
4049
4050     if (ri->state == ARM_CP_STATE_AA32) {
4051         oslock = (value == 0xC5ACCE55);
4052     } else {
4053         oslock = value & 1;
4054     }
4055
4056     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
4057 }
4058
4059 static const ARMCPRegInfo debug_cp_reginfo[] = {
4060     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
4061      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
4062      * unlike DBGDRAR it is never accessible from EL0.
4063      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
4064      * accessor.
4065      */
4066     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
4067       .access = PL0_R, .accessfn = access_tdra,
4068       .type = ARM_CP_CONST, .resetvalue = 0 },
4069     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
4070       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
4071       .access = PL1_R, .accessfn = access_tdra,
4072       .type = ARM_CP_CONST, .resetvalue = 0 },
4073     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
4074       .access = PL0_R, .accessfn = access_tdra,
4075       .type = ARM_CP_CONST, .resetvalue = 0 },
4076     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
4077     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
4078       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4079       .access = PL1_RW, .accessfn = access_tda,
4080       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
4081       .resetvalue = 0 },
4082     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
4083      * We don't implement the configurable EL0 access.
4084      */
4085     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
4086       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4087       .type = ARM_CP_ALIAS,
4088       .access = PL1_R, .accessfn = access_tda,
4089       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
4090     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
4091       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
4092       .access = PL1_W, .type = ARM_CP_NO_RAW,
4093       .accessfn = access_tdosa,
4094       .writefn = oslar_write },
4095     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
4096       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
4097       .access = PL1_R, .resetvalue = 10,
4098       .accessfn = access_tdosa,
4099       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
4100     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
4101     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
4102       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
4103       .access = PL1_RW, .accessfn = access_tdosa,
4104       .type = ARM_CP_NOP },
4105     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
4106      * implement vector catch debug events yet.
4107      */
4108     { .name = "DBGVCR",
4109       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4110       .access = PL1_RW, .accessfn = access_tda,
4111       .type = ARM_CP_NOP },
4112     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
4113      * to save and restore a 32-bit guest's DBGVCR)
4114      */
4115     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
4116       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
4117       .access = PL2_RW, .accessfn = access_tda,
4118       .type = ARM_CP_NOP },
4119     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
4120      * Channel but Linux may try to access this register. The 32-bit
4121      * alias is DBGDCCINT.
4122      */
4123     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
4124       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4125       .access = PL1_RW, .accessfn = access_tda,
4126       .type = ARM_CP_NOP },
4127     REGINFO_SENTINEL
4128 };
4129
4130 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
4131     /* 64 bit access versions of the (dummy) debug registers */
4132     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
4133       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4134     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
4135       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4136     REGINFO_SENTINEL
4137 };
4138
4139 void hw_watchpoint_update(ARMCPU *cpu, int n)
4140 {
4141     CPUARMState *env = &cpu->env;
4142     vaddr len = 0;
4143     vaddr wvr = env->cp15.dbgwvr[n];
4144     uint64_t wcr = env->cp15.dbgwcr[n];
4145     int mask;
4146     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
4147
4148     if (env->cpu_watchpoint[n]) {
4149         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
4150         env->cpu_watchpoint[n] = NULL;
4151     }
4152
4153     if (!extract64(wcr, 0, 1)) {
4154         /* E bit clear : watchpoint disabled */
4155         return;
4156     }
4157
4158     switch (extract64(wcr, 3, 2)) {
4159     case 0:
4160         /* LSC 00 is reserved and must behave as if the wp is disabled */
4161         return;
4162     case 1:
4163         flags |= BP_MEM_READ;
4164         break;
4165     case 2:
4166         flags |= BP_MEM_WRITE;
4167         break;
4168     case 3:
4169         flags |= BP_MEM_ACCESS;
4170         break;
4171     }
4172
4173     /* Attempts to use both MASK and BAS fields simultaneously are
4174      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
4175      * thus generating a watchpoint for every byte in the masked region.
4176      */
4177     mask = extract64(wcr, 24, 4);
4178     if (mask == 1 || mask == 2) {
4179         /* Reserved values of MASK; we must act as if the mask value was
4180          * some non-reserved value, or as if the watchpoint were disabled.
4181          * We choose the latter.
4182          */
4183         return;
4184     } else if (mask) {
4185         /* Watchpoint covers an aligned area up to 2GB in size */
4186         len = 1ULL << mask;
4187         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
4188          * whether the watchpoint fires when the unmasked bits match; we opt
4189          * to generate the exceptions.
4190          */
4191         wvr &= ~(len - 1);
4192     } else {
4193         /* Watchpoint covers bytes defined by the byte address select bits */
4194         int bas = extract64(wcr, 5, 8);
4195         int basstart;
4196
4197         if (bas == 0) {
4198             /* This must act as if the watchpoint is disabled */
4199             return;
4200         }
4201
4202         if (extract64(wvr, 2, 1)) {
4203             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
4204              * ignored, and BAS[3:0] define which bytes to watch.
4205              */
4206             bas &= 0xf;
4207         }
4208         /* The BAS bits are supposed to be programmed to indicate a contiguous
4209          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
4210          * we fire for each byte in the word/doubleword addressed by the WVR.
4211          * We choose to ignore any non-zero bits after the first range of 1s.
4212          */
4213         basstart = ctz32(bas);
4214         len = cto32(bas >> basstart);
4215         wvr += basstart;
4216     }
4217
4218     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
4219                           &env->cpu_watchpoint[n]);
4220 }
4221
4222 void hw_watchpoint_update_all(ARMCPU *cpu)
4223 {
4224     int i;
4225     CPUARMState *env = &cpu->env;
4226
4227     /* Completely clear out existing QEMU watchpoints and our array, to
4228      * avoid possible stale entries following migration load.
4229      */
4230     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
4231     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
4232
4233     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
4234         hw_watchpoint_update(cpu, i);
4235     }
4236 }
4237
4238 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4239                          uint64_t value)
4240 {
4241     ARMCPU *cpu = arm_env_get_cpu(env);
4242     int i = ri->crm;
4243
4244     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
4245      * register reads and behaves as if values written are sign extended.
4246      * Bits [1:0] are RES0.
4247      */
4248     value = sextract64(value, 0, 49) & ~3ULL;
4249
4250     raw_write(env, ri, value);
4251     hw_watchpoint_update(cpu, i);
4252 }
4253
4254 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4255                          uint64_t value)
4256 {
4257     ARMCPU *cpu = arm_env_get_cpu(env);
4258     int i = ri->crm;
4259
4260     raw_write(env, ri, value);
4261     hw_watchpoint_update(cpu, i);
4262 }
4263
4264 void hw_breakpoint_update(ARMCPU *cpu, int n)
4265 {
4266     CPUARMState *env = &cpu->env;
4267     uint64_t bvr = env->cp15.dbgbvr[n];
4268     uint64_t bcr = env->cp15.dbgbcr[n];
4269     vaddr addr;
4270     int bt;
4271     int flags = BP_CPU;
4272
4273     if (env->cpu_breakpoint[n]) {
4274         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
4275         env->cpu_breakpoint[n] = NULL;
4276     }
4277
4278     if (!extract64(bcr, 0, 1)) {
4279         /* E bit clear : watchpoint disabled */
4280         return;
4281     }
4282
4283     bt = extract64(bcr, 20, 4);
4284
4285     switch (bt) {
4286     case 4: /* unlinked address mismatch (reserved if AArch64) */
4287     case 5: /* linked address mismatch (reserved if AArch64) */
4288         qemu_log_mask(LOG_UNIMP,
4289                       "arm: address mismatch breakpoint types not implemented");
4290         return;
4291     case 0: /* unlinked address match */
4292     case 1: /* linked address match */
4293     {
4294         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
4295          * we behave as if the register was sign extended. Bits [1:0] are
4296          * RES0. The BAS field is used to allow setting breakpoints on 16
4297          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
4298          * a bp will fire if the addresses covered by the bp and the addresses
4299          * covered by the insn overlap but the insn doesn't start at the
4300          * start of the bp address range. We choose to require the insn and
4301          * the bp to have the same address. The constraints on writing to
4302          * BAS enforced in dbgbcr_write mean we have only four cases:
4303          *  0b0000  => no breakpoint
4304          *  0b0011  => breakpoint on addr
4305          *  0b1100  => breakpoint on addr + 2
4306          *  0b1111  => breakpoint on addr
4307          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
4308          */
4309         int bas = extract64(bcr, 5, 4);
4310         addr = sextract64(bvr, 0, 49) & ~3ULL;
4311         if (bas == 0) {
4312             return;
4313         }
4314         if (bas == 0xc) {
4315             addr += 2;
4316         }
4317         break;
4318     }
4319     case 2: /* unlinked context ID match */
4320     case 8: /* unlinked VMID match (reserved if no EL2) */
4321     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
4322         qemu_log_mask(LOG_UNIMP,
4323                       "arm: unlinked context breakpoint types not implemented");
4324         return;
4325     case 9: /* linked VMID match (reserved if no EL2) */
4326     case 11: /* linked context ID and VMID match (reserved if no EL2) */
4327     case 3: /* linked context ID match */
4328     default:
4329         /* We must generate no events for Linked context matches (unless
4330          * they are linked to by some other bp/wp, which is handled in
4331          * updates for the linking bp/wp). We choose to also generate no events
4332          * for reserved values.
4333          */
4334         return;
4335     }
4336
4337     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
4338 }
4339
4340 void hw_breakpoint_update_all(ARMCPU *cpu)
4341 {
4342     int i;
4343     CPUARMState *env = &cpu->env;
4344
4345     /* Completely clear out existing QEMU breakpoints and our array, to
4346      * avoid possible stale entries following migration load.
4347      */
4348     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
4349     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
4350
4351     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
4352         hw_breakpoint_update(cpu, i);
4353     }
4354 }
4355
4356 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4357                          uint64_t value)
4358 {
4359     ARMCPU *cpu = arm_env_get_cpu(env);
4360     int i = ri->crm;
4361
4362     raw_write(env, ri, value);
4363     hw_breakpoint_update(cpu, i);
4364 }
4365
4366 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4367                          uint64_t value)
4368 {
4369     ARMCPU *cpu = arm_env_get_cpu(env);
4370     int i = ri->crm;
4371
4372     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
4373      * copy of BAS[0].
4374      */
4375     value = deposit64(value, 6, 1, extract64(value, 5, 1));
4376     value = deposit64(value, 8, 1, extract64(value, 7, 1));
4377
4378     raw_write(env, ri, value);
4379     hw_breakpoint_update(cpu, i);
4380 }
4381
4382 static void define_debug_regs(ARMCPU *cpu)
4383 {
4384     /* Define v7 and v8 architectural debug registers.
4385      * These are just dummy implementations for now.
4386      */
4387     int i;
4388     int wrps, brps, ctx_cmps;
4389     ARMCPRegInfo dbgdidr = {
4390         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
4391         .access = PL0_R, .accessfn = access_tda,
4392         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
4393     };
4394
4395     /* Note that all these register fields hold "number of Xs minus 1". */
4396     brps = extract32(cpu->dbgdidr, 24, 4);
4397     wrps = extract32(cpu->dbgdidr, 28, 4);
4398     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
4399
4400     assert(ctx_cmps <= brps);
4401
4402     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
4403      * of the debug registers such as number of breakpoints;
4404      * check that if they both exist then they agree.
4405      */
4406     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
4407         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
4408         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
4409         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
4410     }
4411
4412     define_one_arm_cp_reg(cpu, &dbgdidr);
4413     define_arm_cp_regs(cpu, debug_cp_reginfo);
4414
4415     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
4416         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
4417     }
4418
4419     for (i = 0; i < brps + 1; i++) {
4420         ARMCPRegInfo dbgregs[] = {
4421             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
4422               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
4423               .access = PL1_RW, .accessfn = access_tda,
4424               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
4425               .writefn = dbgbvr_write, .raw_writefn = raw_write
4426             },
4427             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
4428               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
4429               .access = PL1_RW, .accessfn = access_tda,
4430               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
4431               .writefn = dbgbcr_write, .raw_writefn = raw_write
4432             },
4433             REGINFO_SENTINEL
4434         };
4435         define_arm_cp_regs(cpu, dbgregs);
4436     }
4437
4438     for (i = 0; i < wrps + 1; i++) {
4439         ARMCPRegInfo dbgregs[] = {
4440             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
4441               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
4442               .access = PL1_RW, .accessfn = access_tda,
4443               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
4444               .writefn = dbgwvr_write, .raw_writefn = raw_write
4445             },
4446             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
4447               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
4448               .access = PL1_RW, .accessfn = access_tda,
4449               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
4450               .writefn = dbgwcr_write, .raw_writefn = raw_write
4451             },
4452             REGINFO_SENTINEL
4453         };
4454         define_arm_cp_regs(cpu, dbgregs);
4455     }
4456 }
4457
4458 void register_cp_regs_for_features(ARMCPU *cpu)
4459 {
4460     /* Register all the coprocessor registers based on feature bits */
4461     CPUARMState *env = &cpu->env;
4462     if (arm_feature(env, ARM_FEATURE_M)) {
4463         /* M profile has no coprocessor registers */
4464         return;
4465     }
4466
4467     define_arm_cp_regs(cpu, cp_reginfo);
4468     if (!arm_feature(env, ARM_FEATURE_V8)) {
4469         /* Must go early as it is full of wildcards that may be
4470          * overridden by later definitions.
4471          */
4472         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
4473     }
4474
4475     if (arm_feature(env, ARM_FEATURE_V6)) {
4476         /* The ID registers all have impdef reset values */
4477         ARMCPRegInfo v6_idregs[] = {
4478             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
4479               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4480               .access = PL1_R, .type = ARM_CP_CONST,
4481               .resetvalue = cpu->id_pfr0 },
4482             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
4483               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
4484               .access = PL1_R, .type = ARM_CP_CONST,
4485               .resetvalue = cpu->id_pfr1 },
4486             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
4487               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
4488               .access = PL1_R, .type = ARM_CP_CONST,
4489               .resetvalue = cpu->id_dfr0 },
4490             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
4491               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
4492               .access = PL1_R, .type = ARM_CP_CONST,
4493               .resetvalue = cpu->id_afr0 },
4494             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
4495               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
4496               .access = PL1_R, .type = ARM_CP_CONST,
4497               .resetvalue = cpu->id_mmfr0 },
4498             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
4499               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
4500               .access = PL1_R, .type = ARM_CP_CONST,
4501               .resetvalue = cpu->id_mmfr1 },
4502             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
4503               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
4504               .access = PL1_R, .type = ARM_CP_CONST,
4505               .resetvalue = cpu->id_mmfr2 },
4506             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
4507               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
4508               .access = PL1_R, .type = ARM_CP_CONST,
4509               .resetvalue = cpu->id_mmfr3 },
4510             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
4511               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4512               .access = PL1_R, .type = ARM_CP_CONST,
4513               .resetvalue = cpu->id_isar0 },
4514             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
4515               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
4516               .access = PL1_R, .type = ARM_CP_CONST,
4517               .resetvalue = cpu->id_isar1 },
4518             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
4519               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4520               .access = PL1_R, .type = ARM_CP_CONST,
4521               .resetvalue = cpu->id_isar2 },
4522             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
4523               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
4524               .access = PL1_R, .type = ARM_CP_CONST,
4525               .resetvalue = cpu->id_isar3 },
4526             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
4527               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
4528               .access = PL1_R, .type = ARM_CP_CONST,
4529               .resetvalue = cpu->id_isar4 },
4530             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
4531               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
4532               .access = PL1_R, .type = ARM_CP_CONST,
4533               .resetvalue = cpu->id_isar5 },
4534             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
4535               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
4536               .access = PL1_R, .type = ARM_CP_CONST,
4537               .resetvalue = cpu->id_mmfr4 },
4538             /* 7 is as yet unallocated and must RAZ */
4539             { .name = "ID_ISAR7_RESERVED", .state = ARM_CP_STATE_BOTH,
4540               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
4541               .access = PL1_R, .type = ARM_CP_CONST,
4542               .resetvalue = 0 },
4543             REGINFO_SENTINEL
4544         };
4545         define_arm_cp_regs(cpu, v6_idregs);
4546         define_arm_cp_regs(cpu, v6_cp_reginfo);
4547     } else {
4548         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
4549     }
4550     if (arm_feature(env, ARM_FEATURE_V6K)) {
4551         define_arm_cp_regs(cpu, v6k_cp_reginfo);
4552     }
4553     if (arm_feature(env, ARM_FEATURE_V7MP) &&
4554         !arm_feature(env, ARM_FEATURE_MPU)) {
4555         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
4556     }
4557     if (arm_feature(env, ARM_FEATURE_V7)) {
4558         /* v7 performance monitor control register: same implementor
4559          * field as main ID register, and we implement only the cycle
4560          * count register.
4561          */
4562 #ifndef CONFIG_USER_ONLY
4563         ARMCPRegInfo pmcr = {
4564             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
4565             .access = PL0_RW,
4566             .type = ARM_CP_IO | ARM_CP_ALIAS,
4567             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
4568             .accessfn = pmreg_access, .writefn = pmcr_write,
4569             .raw_writefn = raw_write,
4570         };
4571         ARMCPRegInfo pmcr64 = {
4572             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
4573             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
4574             .access = PL0_RW, .accessfn = pmreg_access,
4575             .type = ARM_CP_IO,
4576             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
4577             .resetvalue = cpu->midr & 0xff000000,
4578             .writefn = pmcr_write, .raw_writefn = raw_write,
4579         };
4580         define_one_arm_cp_reg(cpu, &pmcr);
4581         define_one_arm_cp_reg(cpu, &pmcr64);
4582 #endif
4583         ARMCPRegInfo clidr = {
4584             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
4585             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
4586             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
4587         };
4588         define_one_arm_cp_reg(cpu, &clidr);
4589         define_arm_cp_regs(cpu, v7_cp_reginfo);
4590         define_debug_regs(cpu);
4591     } else {
4592         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
4593     }
4594     if (arm_feature(env, ARM_FEATURE_V8)) {
4595         /* AArch64 ID registers, which all have impdef reset values.
4596          * Note that within the ID register ranges the unused slots
4597          * must all RAZ, not UNDEF; future architecture versions may
4598          * define new registers here.
4599          */
4600         ARMCPRegInfo v8_idregs[] = {
4601             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
4602               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
4603               .access = PL1_R, .type = ARM_CP_CONST,
4604               .resetvalue = cpu->id_aa64pfr0 },
4605             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
4606               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
4607               .access = PL1_R, .type = ARM_CP_CONST,
4608               .resetvalue = cpu->id_aa64pfr1},
4609             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4610               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
4611               .access = PL1_R, .type = ARM_CP_CONST,
4612               .resetvalue = 0 },
4613             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4614               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
4615               .access = PL1_R, .type = ARM_CP_CONST,
4616               .resetvalue = 0 },
4617             { .name = "ID_AA64PFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4618               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
4619               .access = PL1_R, .type = ARM_CP_CONST,
4620               .resetvalue = 0 },
4621             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4622               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
4623               .access = PL1_R, .type = ARM_CP_CONST,
4624               .resetvalue = 0 },
4625             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4626               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
4627               .access = PL1_R, .type = ARM_CP_CONST,
4628               .resetvalue = 0 },
4629             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4630               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
4631               .access = PL1_R, .type = ARM_CP_CONST,
4632               .resetvalue = 0 },
4633             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
4634               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
4635               .access = PL1_R, .type = ARM_CP_CONST,
4636               .resetvalue = cpu->id_aa64dfr0 },
4637             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
4638               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
4639               .access = PL1_R, .type = ARM_CP_CONST,
4640               .resetvalue = cpu->id_aa64dfr1 },
4641             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4642               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
4643               .access = PL1_R, .type = ARM_CP_CONST,
4644               .resetvalue = 0 },
4645             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4646               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
4647               .access = PL1_R, .type = ARM_CP_CONST,
4648               .resetvalue = 0 },
4649             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
4650               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
4651               .access = PL1_R, .type = ARM_CP_CONST,
4652               .resetvalue = cpu->id_aa64afr0 },
4653             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
4654               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
4655               .access = PL1_R, .type = ARM_CP_CONST,
4656               .resetvalue = cpu->id_aa64afr1 },
4657             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4658               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
4659               .access = PL1_R, .type = ARM_CP_CONST,
4660               .resetvalue = 0 },
4661             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4662               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
4663               .access = PL1_R, .type = ARM_CP_CONST,
4664               .resetvalue = 0 },
4665             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
4666               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
4667               .access = PL1_R, .type = ARM_CP_CONST,
4668               .resetvalue = cpu->id_aa64isar0 },
4669             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
4670               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
4671               .access = PL1_R, .type = ARM_CP_CONST,
4672               .resetvalue = cpu->id_aa64isar1 },
4673             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4674               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
4675               .access = PL1_R, .type = ARM_CP_CONST,
4676               .resetvalue = 0 },
4677             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4678               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
4679               .access = PL1_R, .type = ARM_CP_CONST,
4680               .resetvalue = 0 },
4681             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4682               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
4683               .access = PL1_R, .type = ARM_CP_CONST,
4684               .resetvalue = 0 },
4685             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4686               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
4687               .access = PL1_R, .type = ARM_CP_CONST,
4688               .resetvalue = 0 },
4689             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4690               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
4691               .access = PL1_R, .type = ARM_CP_CONST,
4692               .resetvalue = 0 },
4693             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4694               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
4695               .access = PL1_R, .type = ARM_CP_CONST,
4696               .resetvalue = 0 },
4697             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
4698               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4699               .access = PL1_R, .type = ARM_CP_CONST,
4700               .resetvalue = cpu->id_aa64mmfr0 },
4701             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
4702               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
4703               .access = PL1_R, .type = ARM_CP_CONST,
4704               .resetvalue = cpu->id_aa64mmfr1 },
4705             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4706               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
4707               .access = PL1_R, .type = ARM_CP_CONST,
4708               .resetvalue = 0 },
4709             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4710               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
4711               .access = PL1_R, .type = ARM_CP_CONST,
4712               .resetvalue = 0 },
4713             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4714               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
4715               .access = PL1_R, .type = ARM_CP_CONST,
4716               .resetvalue = 0 },
4717             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4718               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
4719               .access = PL1_R, .type = ARM_CP_CONST,
4720               .resetvalue = 0 },
4721             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4722               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
4723               .access = PL1_R, .type = ARM_CP_CONST,
4724               .resetvalue = 0 },
4725             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4726               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
4727               .access = PL1_R, .type = ARM_CP_CONST,
4728               .resetvalue = 0 },
4729             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
4730               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
4731               .access = PL1_R, .type = ARM_CP_CONST,
4732               .resetvalue = cpu->mvfr0 },
4733             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
4734               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
4735               .access = PL1_R, .type = ARM_CP_CONST,
4736               .resetvalue = cpu->mvfr1 },
4737             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
4738               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
4739               .access = PL1_R, .type = ARM_CP_CONST,
4740               .resetvalue = cpu->mvfr2 },
4741             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4742               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
4743               .access = PL1_R, .type = ARM_CP_CONST,
4744               .resetvalue = 0 },
4745             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4746               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
4747               .access = PL1_R, .type = ARM_CP_CONST,
4748               .resetvalue = 0 },
4749             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4750               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
4751               .access = PL1_R, .type = ARM_CP_CONST,
4752               .resetvalue = 0 },
4753             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4754               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
4755               .access = PL1_R, .type = ARM_CP_CONST,
4756               .resetvalue = 0 },
4757             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4758               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
4759               .access = PL1_R, .type = ARM_CP_CONST,
4760               .resetvalue = 0 },
4761             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
4762               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
4763               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
4764               .resetvalue = cpu->pmceid0 },
4765             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
4766               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
4767               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
4768               .resetvalue = cpu->pmceid0 },
4769             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
4770               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
4771               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
4772               .resetvalue = cpu->pmceid1 },
4773             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
4774               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
4775               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
4776               .resetvalue = cpu->pmceid1 },
4777             REGINFO_SENTINEL
4778         };
4779         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
4780         if (!arm_feature(env, ARM_FEATURE_EL3) &&
4781             !arm_feature(env, ARM_FEATURE_EL2)) {
4782             ARMCPRegInfo rvbar = {
4783                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
4784                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
4785                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
4786             };
4787             define_one_arm_cp_reg(cpu, &rvbar);
4788         }
4789         define_arm_cp_regs(cpu, v8_idregs);
4790         define_arm_cp_regs(cpu, v8_cp_reginfo);
4791     }
4792     if (arm_feature(env, ARM_FEATURE_EL2)) {
4793         uint64_t vmpidr_def = mpidr_read_val(env);
4794         ARMCPRegInfo vpidr_regs[] = {
4795             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
4796               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
4797               .access = PL2_RW, .accessfn = access_el3_aa32ns,
4798               .resetvalue = cpu->midr,
4799               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
4800             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
4801               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
4802               .access = PL2_RW, .resetvalue = cpu->midr,
4803               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
4804             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
4805               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
4806               .access = PL2_RW, .accessfn = access_el3_aa32ns,
4807               .resetvalue = vmpidr_def,
4808               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
4809             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
4810               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
4811               .access = PL2_RW,
4812               .resetvalue = vmpidr_def,
4813               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
4814             REGINFO_SENTINEL
4815         };
4816         define_arm_cp_regs(cpu, vpidr_regs);
4817         define_arm_cp_regs(cpu, el2_cp_reginfo);
4818         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
4819         if (!arm_feature(env, ARM_FEATURE_EL3)) {
4820             ARMCPRegInfo rvbar = {
4821                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
4822                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
4823                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
4824             };
4825             define_one_arm_cp_reg(cpu, &rvbar);
4826         }
4827     } else {
4828         /* If EL2 is missing but higher ELs are enabled, we need to
4829          * register the no_el2 reginfos.
4830          */
4831         if (arm_feature(env, ARM_FEATURE_EL3)) {
4832             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
4833              * of MIDR_EL1 and MPIDR_EL1.
4834              */
4835             ARMCPRegInfo vpidr_regs[] = {
4836                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4837                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
4838                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4839                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
4840                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
4841                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4842                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
4843                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4844                   .type = ARM_CP_NO_RAW,
4845                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
4846                 REGINFO_SENTINEL
4847             };
4848             define_arm_cp_regs(cpu, vpidr_regs);
4849             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
4850         }
4851     }
4852     if (arm_feature(env, ARM_FEATURE_EL3)) {
4853         define_arm_cp_regs(cpu, el3_cp_reginfo);
4854         ARMCPRegInfo el3_regs[] = {
4855             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
4856               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
4857               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
4858             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
4859               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
4860               .access = PL3_RW,
4861               .raw_writefn = raw_write, .writefn = sctlr_write,
4862               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
4863               .resetvalue = cpu->reset_sctlr },
4864             REGINFO_SENTINEL
4865         };
4866
4867         define_arm_cp_regs(cpu, el3_regs);
4868     }
4869     /* The behaviour of NSACR is sufficiently various that we don't
4870      * try to describe it in a single reginfo:
4871      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
4872      *     reads as constant 0xc00 from NS EL1 and NS EL2
4873      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
4874      *  if v7 without EL3, register doesn't exist
4875      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
4876      */
4877     if (arm_feature(env, ARM_FEATURE_EL3)) {
4878         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
4879             ARMCPRegInfo nsacr = {
4880                 .name = "NSACR", .type = ARM_CP_CONST,
4881                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
4882                 .access = PL1_RW, .accessfn = nsacr_access,
4883                 .resetvalue = 0xc00
4884             };
4885             define_one_arm_cp_reg(cpu, &nsacr);
4886         } else {
4887             ARMCPRegInfo nsacr = {
4888                 .name = "NSACR",
4889                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
4890                 .access = PL3_RW | PL1_R,
4891                 .resetvalue = 0,
4892                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
4893             };
4894             define_one_arm_cp_reg(cpu, &nsacr);
4895         }
4896     } else {
4897         if (arm_feature(env, ARM_FEATURE_V8)) {
4898             ARMCPRegInfo nsacr = {
4899                 .name = "NSACR", .type = ARM_CP_CONST,
4900                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
4901                 .access = PL1_R,
4902                 .resetvalue = 0xc00
4903             };
4904             define_one_arm_cp_reg(cpu, &nsacr);
4905         }
4906     }
4907
4908     if (arm_feature(env, ARM_FEATURE_MPU)) {
4909         if (arm_feature(env, ARM_FEATURE_V6)) {
4910             /* PMSAv6 not implemented */
4911             assert(arm_feature(env, ARM_FEATURE_V7));
4912             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
4913             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
4914         } else {
4915             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
4916         }
4917     } else {
4918         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
4919         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
4920     }
4921     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
4922         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
4923     }
4924     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
4925         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
4926     }
4927     if (arm_feature(env, ARM_FEATURE_VAPA)) {
4928         define_arm_cp_regs(cpu, vapa_cp_reginfo);
4929     }
4930     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
4931         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
4932     }
4933     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
4934         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
4935     }
4936     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
4937         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
4938     }
4939     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
4940         define_arm_cp_regs(cpu, omap_cp_reginfo);
4941     }
4942     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
4943         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
4944     }
4945     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
4946         define_arm_cp_regs(cpu, xscale_cp_reginfo);
4947     }
4948     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
4949         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
4950     }
4951     if (arm_feature(env, ARM_FEATURE_LPAE)) {
4952         define_arm_cp_regs(cpu, lpae_cp_reginfo);
4953     }
4954     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
4955      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
4956      * be read-only (ie write causes UNDEF exception).
4957      */
4958     {
4959         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
4960             /* Pre-v8 MIDR space.
4961              * Note that the MIDR isn't a simple constant register because
4962              * of the TI925 behaviour where writes to another register can
4963              * cause the MIDR value to change.
4964              *
4965              * Unimplemented registers in the c15 0 0 0 space default to
4966              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
4967              * and friends override accordingly.
4968              */
4969             { .name = "MIDR",
4970               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
4971               .access = PL1_R, .resetvalue = cpu->midr,
4972               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
4973               .readfn = midr_read,
4974               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
4975               .type = ARM_CP_OVERRIDE },
4976             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
4977             { .name = "DUMMY",
4978               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
4979               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
4980             { .name = "DUMMY",
4981               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
4982               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
4983             { .name = "DUMMY",
4984               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
4985               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
4986             { .name = "DUMMY",
4987               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
4988               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
4989             { .name = "DUMMY",
4990               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
4991               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
4992             REGINFO_SENTINEL
4993         };
4994         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
4995             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
4996               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
4997               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
4998               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
4999               .readfn = midr_read },
5000             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
5001             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5002               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5003               .access = PL1_R, .resetvalue = cpu->midr },
5004             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5005               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
5006               .access = PL1_R, .resetvalue = cpu->midr },
5007             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
5008               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
5009               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
5010             REGINFO_SENTINEL
5011         };
5012         ARMCPRegInfo id_cp_reginfo[] = {
5013             /* These are common to v8 and pre-v8 */
5014             { .name = "CTR",
5015               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
5016               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5017             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
5018               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
5019               .access = PL0_R, .accessfn = ctr_el0_access,
5020               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5021             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
5022             { .name = "TCMTR",
5023               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
5024               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5025             REGINFO_SENTINEL
5026         };
5027         /* TLBTR is specific to VMSA */
5028         ARMCPRegInfo id_tlbtr_reginfo = {
5029               .name = "TLBTR",
5030               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
5031               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
5032         };
5033         /* MPUIR is specific to PMSA V6+ */
5034         ARMCPRegInfo id_mpuir_reginfo = {
5035               .name = "MPUIR",
5036               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5037               .access = PL1_R, .type = ARM_CP_CONST,
5038               .resetvalue = cpu->pmsav7_dregion << 8
5039         };
5040         ARMCPRegInfo crn0_wi_reginfo = {
5041             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
5042             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
5043             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
5044         };
5045         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
5046             arm_feature(env, ARM_FEATURE_STRONGARM)) {
5047             ARMCPRegInfo *r;
5048             /* Register the blanket "writes ignored" value first to cover the
5049              * whole space. Then update the specific ID registers to allow write
5050              * access, so that they ignore writes rather than causing them to
5051              * UNDEF.
5052              */
5053             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
5054             for (r = id_pre_v8_midr_cp_reginfo;
5055                  r->type != ARM_CP_SENTINEL; r++) {
5056                 r->access = PL1_RW;
5057             }
5058             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
5059                 r->access = PL1_RW;
5060             }
5061             id_tlbtr_reginfo.access = PL1_RW;
5062             id_tlbtr_reginfo.access = PL1_RW;
5063         }
5064         if (arm_feature(env, ARM_FEATURE_V8)) {
5065             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
5066         } else {
5067             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
5068         }
5069         define_arm_cp_regs(cpu, id_cp_reginfo);
5070         if (!arm_feature(env, ARM_FEATURE_MPU)) {
5071             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
5072         } else if (arm_feature(env, ARM_FEATURE_V7)) {
5073             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
5074         }
5075     }
5076
5077     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
5078         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
5079     }
5080
5081     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
5082         ARMCPRegInfo auxcr_reginfo[] = {
5083             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
5084               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
5085               .access = PL1_RW, .type = ARM_CP_CONST,
5086               .resetvalue = cpu->reset_auxcr },
5087             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
5088               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
5089               .access = PL2_RW, .type = ARM_CP_CONST,
5090               .resetvalue = 0 },
5091             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
5092               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
5093               .access = PL3_RW, .type = ARM_CP_CONST,
5094               .resetvalue = 0 },
5095             REGINFO_SENTINEL
5096         };
5097         define_arm_cp_regs(cpu, auxcr_reginfo);
5098     }
5099
5100     if (arm_feature(env, ARM_FEATURE_CBAR)) {
5101         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5102             /* 32 bit view is [31:18] 0...0 [43:32]. */
5103             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
5104                 | extract64(cpu->reset_cbar, 32, 12);
5105             ARMCPRegInfo cbar_reginfo[] = {
5106                 { .name = "CBAR",
5107                   .type = ARM_CP_CONST,
5108                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5109                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
5110                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
5111                   .type = ARM_CP_CONST,
5112                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
5113                   .access = PL1_R, .resetvalue = cbar32 },
5114                 REGINFO_SENTINEL
5115             };
5116             /* We don't implement a r/w 64 bit CBAR currently */
5117             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
5118             define_arm_cp_regs(cpu, cbar_reginfo);
5119         } else {
5120             ARMCPRegInfo cbar = {
5121                 .name = "CBAR",
5122                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5123                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
5124                 .fieldoffset = offsetof(CPUARMState,
5125                                         cp15.c15_config_base_address)
5126             };
5127             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
5128                 cbar.access = PL1_R;
5129                 cbar.fieldoffset = 0;
5130                 cbar.type = ARM_CP_CONST;
5131             }
5132             define_one_arm_cp_reg(cpu, &cbar);
5133         }
5134     }
5135
5136     if (arm_feature(env, ARM_FEATURE_VBAR)) {
5137         ARMCPRegInfo vbar_cp_reginfo[] = {
5138             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
5139               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
5140               .access = PL1_RW, .writefn = vbar_write,
5141               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
5142                                      offsetof(CPUARMState, cp15.vbar_ns) },
5143               .resetvalue = 0 },
5144             REGINFO_SENTINEL
5145         };
5146         define_arm_cp_regs(cpu, vbar_cp_reginfo);
5147     }
5148
5149     /* Generic registers whose values depend on the implementation */
5150     {
5151         ARMCPRegInfo sctlr = {
5152             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
5153             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5154             .access = PL1_RW,
5155             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
5156                                    offsetof(CPUARMState, cp15.sctlr_ns) },
5157             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
5158             .raw_writefn = raw_write,
5159         };
5160         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5161             /* Normally we would always end the TB on an SCTLR write, but Linux
5162              * arch/arm/mach-pxa/sleep.S expects two instructions following
5163              * an MMU enable to execute from cache.  Imitate this behaviour.
5164              */
5165             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
5166         }
5167         define_one_arm_cp_reg(cpu, &sctlr);
5168     }
5169 }
5170
5171 ARMCPU *cpu_arm_init(const char *cpu_model)
5172 {
5173     return ARM_CPU(cpu_generic_init(TYPE_ARM_CPU, cpu_model));
5174 }
5175
5176 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
5177 {
5178     CPUState *cs = CPU(cpu);
5179     CPUARMState *env = &cpu->env;
5180
5181     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5182         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
5183                                  aarch64_fpu_gdb_set_reg,
5184                                  34, "aarch64-fpu.xml", 0);
5185     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
5186         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5187                                  51, "arm-neon.xml", 0);
5188     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
5189         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5190                                  35, "arm-vfp3.xml", 0);
5191     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
5192         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5193                                  19, "arm-vfp.xml", 0);
5194     }
5195 }
5196
5197 /* Sort alphabetically by type name, except for "any". */
5198 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
5199 {
5200     ObjectClass *class_a = (ObjectClass *)a;
5201     ObjectClass *class_b = (ObjectClass *)b;
5202     const char *name_a, *name_b;
5203
5204     name_a = object_class_get_name(class_a);
5205     name_b = object_class_get_name(class_b);
5206     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
5207         return 1;
5208     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
5209         return -1;
5210     } else {
5211         return strcmp(name_a, name_b);
5212     }
5213 }
5214
5215 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
5216 {
5217     ObjectClass *oc = data;
5218     CPUListState *s = user_data;
5219     const char *typename;
5220     char *name;
5221
5222     typename = object_class_get_name(oc);
5223     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
5224     (*s->cpu_fprintf)(s->file, "  %s\n",
5225                       name);
5226     g_free(name);
5227 }
5228
5229 void arm_cpu_list(FILE *f, fprintf_function cpu_fprintf)
5230 {
5231     CPUListState s = {
5232         .file = f,
5233         .cpu_fprintf = cpu_fprintf,
5234     };
5235     GSList *list;
5236
5237     list = object_class_get_list(TYPE_ARM_CPU, false);
5238     list = g_slist_sort(list, arm_cpu_list_compare);
5239     (*cpu_fprintf)(f, "Available CPUs:\n");
5240     g_slist_foreach(list, arm_cpu_list_entry, &s);
5241     g_slist_free(list);
5242 #ifdef CONFIG_KVM
5243     /* The 'host' CPU type is dynamically registered only if KVM is
5244      * enabled, so we have to special-case it here:
5245      */
5246     (*cpu_fprintf)(f, "  host (only available in KVM mode)\n");
5247 #endif
5248 }
5249
5250 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
5251 {
5252     ObjectClass *oc = data;
5253     CpuDefinitionInfoList **cpu_list = user_data;
5254     CpuDefinitionInfoList *entry;
5255     CpuDefinitionInfo *info;
5256     const char *typename;
5257
5258     typename = object_class_get_name(oc);
5259     info = g_malloc0(sizeof(*info));
5260     info->name = g_strndup(typename,
5261                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
5262     info->q_typename = g_strdup(typename);
5263
5264     entry = g_malloc0(sizeof(*entry));
5265     entry->value = info;
5266     entry->next = *cpu_list;
5267     *cpu_list = entry;
5268 }
5269
5270 CpuDefinitionInfoList *arch_query_cpu_definitions(Error **errp)
5271 {
5272     CpuDefinitionInfoList *cpu_list = NULL;
5273     GSList *list;
5274
5275     list = object_class_get_list(TYPE_ARM_CPU, false);
5276     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
5277     g_slist_free(list);
5278
5279     return cpu_list;
5280 }
5281
5282 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
5283                                    void *opaque, int state, int secstate,
5284                                    int crm, int opc1, int opc2)
5285 {
5286     /* Private utility function for define_one_arm_cp_reg_with_opaque():
5287      * add a single reginfo struct to the hash table.
5288      */
5289     uint32_t *key = g_new(uint32_t, 1);
5290     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
5291     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
5292     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
5293
5294     /* Reset the secure state to the specific incoming state.  This is
5295      * necessary as the register may have been defined with both states.
5296      */
5297     r2->secure = secstate;
5298
5299     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5300         /* Register is banked (using both entries in array).
5301          * Overwriting fieldoffset as the array is only used to define
5302          * banked registers but later only fieldoffset is used.
5303          */
5304         r2->fieldoffset = r->bank_fieldoffsets[ns];
5305     }
5306
5307     if (state == ARM_CP_STATE_AA32) {
5308         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5309             /* If the register is banked then we don't need to migrate or
5310              * reset the 32-bit instance in certain cases:
5311              *
5312              * 1) If the register has both 32-bit and 64-bit instances then we
5313              *    can count on the 64-bit instance taking care of the
5314              *    non-secure bank.
5315              * 2) If ARMv8 is enabled then we can count on a 64-bit version
5316              *    taking care of the secure bank.  This requires that separate
5317              *    32 and 64-bit definitions are provided.
5318              */
5319             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
5320                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
5321                 r2->type |= ARM_CP_ALIAS;
5322             }
5323         } else if ((secstate != r->secure) && !ns) {
5324             /* The register is not banked so we only want to allow migration of
5325              * the non-secure instance.
5326              */
5327             r2->type |= ARM_CP_ALIAS;
5328         }
5329
5330         if (r->state == ARM_CP_STATE_BOTH) {
5331             /* We assume it is a cp15 register if the .cp field is left unset.
5332              */
5333             if (r2->cp == 0) {
5334                 r2->cp = 15;
5335             }
5336
5337 #ifdef HOST_WORDS_BIGENDIAN
5338             if (r2->fieldoffset) {
5339                 r2->fieldoffset += sizeof(uint32_t);
5340             }
5341 #endif
5342         }
5343     }
5344     if (state == ARM_CP_STATE_AA64) {
5345         /* To allow abbreviation of ARMCPRegInfo
5346          * definitions, we treat cp == 0 as equivalent to
5347          * the value for "standard guest-visible sysreg".
5348          * STATE_BOTH definitions are also always "standard
5349          * sysreg" in their AArch64 view (the .cp value may
5350          * be non-zero for the benefit of the AArch32 view).
5351          */
5352         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
5353             r2->cp = CP_REG_ARM64_SYSREG_CP;
5354         }
5355         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
5356                                   r2->opc0, opc1, opc2);
5357     } else {
5358         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
5359     }
5360     if (opaque) {
5361         r2->opaque = opaque;
5362     }
5363     /* reginfo passed to helpers is correct for the actual access,
5364      * and is never ARM_CP_STATE_BOTH:
5365      */
5366     r2->state = state;
5367     /* Make sure reginfo passed to helpers for wildcarded regs
5368      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
5369      */
5370     r2->crm = crm;
5371     r2->opc1 = opc1;
5372     r2->opc2 = opc2;
5373     /* By convention, for wildcarded registers only the first
5374      * entry is used for migration; the others are marked as
5375      * ALIAS so we don't try to transfer the register
5376      * multiple times. Special registers (ie NOP/WFI) are
5377      * never migratable and not even raw-accessible.
5378      */
5379     if ((r->type & ARM_CP_SPECIAL)) {
5380         r2->type |= ARM_CP_NO_RAW;
5381     }
5382     if (((r->crm == CP_ANY) && crm != 0) ||
5383         ((r->opc1 == CP_ANY) && opc1 != 0) ||
5384         ((r->opc2 == CP_ANY) && opc2 != 0)) {
5385         r2->type |= ARM_CP_ALIAS;
5386     }
5387
5388     /* Check that raw accesses are either forbidden or handled. Note that
5389      * we can't assert this earlier because the setup of fieldoffset for
5390      * banked registers has to be done first.
5391      */
5392     if (!(r2->type & ARM_CP_NO_RAW)) {
5393         assert(!raw_accessors_invalid(r2));
5394     }
5395
5396     /* Overriding of an existing definition must be explicitly
5397      * requested.
5398      */
5399     if (!(r->type & ARM_CP_OVERRIDE)) {
5400         ARMCPRegInfo *oldreg;
5401         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
5402         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
5403             fprintf(stderr, "Register redefined: cp=%d %d bit "
5404                     "crn=%d crm=%d opc1=%d opc2=%d, "
5405                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
5406                     r2->crn, r2->crm, r2->opc1, r2->opc2,
5407                     oldreg->name, r2->name);
5408             g_assert_not_reached();
5409         }
5410     }
5411     g_hash_table_insert(cpu->cp_regs, key, r2);
5412 }
5413
5414
5415 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
5416                                        const ARMCPRegInfo *r, void *opaque)
5417 {
5418     /* Define implementations of coprocessor registers.
5419      * We store these in a hashtable because typically
5420      * there are less than 150 registers in a space which
5421      * is 16*16*16*8*8 = 262144 in size.
5422      * Wildcarding is supported for the crm, opc1 and opc2 fields.
5423      * If a register is defined twice then the second definition is
5424      * used, so this can be used to define some generic registers and
5425      * then override them with implementation specific variations.
5426      * At least one of the original and the second definition should
5427      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
5428      * against accidental use.
5429      *
5430      * The state field defines whether the register is to be
5431      * visible in the AArch32 or AArch64 execution state. If the
5432      * state is set to ARM_CP_STATE_BOTH then we synthesise a
5433      * reginfo structure for the AArch32 view, which sees the lower
5434      * 32 bits of the 64 bit register.
5435      *
5436      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
5437      * be wildcarded. AArch64 registers are always considered to be 64
5438      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
5439      * the register, if any.
5440      */
5441     int crm, opc1, opc2, state;
5442     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
5443     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
5444     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
5445     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
5446     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
5447     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
5448     /* 64 bit registers have only CRm and Opc1 fields */
5449     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
5450     /* op0 only exists in the AArch64 encodings */
5451     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
5452     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
5453     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
5454     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
5455      * encodes a minimum access level for the register. We roll this
5456      * runtime check into our general permission check code, so check
5457      * here that the reginfo's specified permissions are strict enough
5458      * to encompass the generic architectural permission check.
5459      */
5460     if (r->state != ARM_CP_STATE_AA32) {
5461         int mask = 0;
5462         switch (r->opc1) {
5463         case 0: case 1: case 2:
5464             /* min_EL EL1 */
5465             mask = PL1_RW;
5466             break;
5467         case 3:
5468             /* min_EL EL0 */
5469             mask = PL0_RW;
5470             break;
5471         case 4:
5472             /* min_EL EL2 */
5473             mask = PL2_RW;
5474             break;
5475         case 5:
5476             /* unallocated encoding, so not possible */
5477             assert(false);
5478             break;
5479         case 6:
5480             /* min_EL EL3 */
5481             mask = PL3_RW;
5482             break;
5483         case 7:
5484             /* min_EL EL1, secure mode only (we don't check the latter) */
5485             mask = PL1_RW;
5486             break;
5487         default:
5488             /* broken reginfo with out-of-range opc1 */
5489             assert(false);
5490             break;
5491         }
5492         /* assert our permissions are not too lax (stricter is fine) */
5493         assert((r->access & ~mask) == 0);
5494     }
5495
5496     /* Check that the register definition has enough info to handle
5497      * reads and writes if they are permitted.
5498      */
5499     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
5500         if (r->access & PL3_R) {
5501             assert((r->fieldoffset ||
5502                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5503                    r->readfn);
5504         }
5505         if (r->access & PL3_W) {
5506             assert((r->fieldoffset ||
5507                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5508                    r->writefn);
5509         }
5510     }
5511     /* Bad type field probably means missing sentinel at end of reg list */
5512     assert(cptype_valid(r->type));
5513     for (crm = crmmin; crm <= crmmax; crm++) {
5514         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
5515             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
5516                 for (state = ARM_CP_STATE_AA32;
5517                      state <= ARM_CP_STATE_AA64; state++) {
5518                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
5519                         continue;
5520                     }
5521                     if (state == ARM_CP_STATE_AA32) {
5522                         /* Under AArch32 CP registers can be common
5523                          * (same for secure and non-secure world) or banked.
5524                          */
5525                         switch (r->secure) {
5526                         case ARM_CP_SECSTATE_S:
5527                         case ARM_CP_SECSTATE_NS:
5528                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5529                                                    r->secure, crm, opc1, opc2);
5530                             break;
5531                         default:
5532                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5533                                                    ARM_CP_SECSTATE_S,
5534                                                    crm, opc1, opc2);
5535                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5536                                                    ARM_CP_SECSTATE_NS,
5537                                                    crm, opc1, opc2);
5538                             break;
5539                         }
5540                     } else {
5541                         /* AArch64 registers get mapped to non-secure instance
5542                          * of AArch32 */
5543                         add_cpreg_to_hashtable(cpu, r, opaque, state,
5544                                                ARM_CP_SECSTATE_NS,
5545                                                crm, opc1, opc2);
5546                     }
5547                 }
5548             }
5549         }
5550     }
5551 }
5552
5553 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
5554                                     const ARMCPRegInfo *regs, void *opaque)
5555 {
5556     /* Define a whole list of registers */
5557     const ARMCPRegInfo *r;
5558     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
5559         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
5560     }
5561 }
5562
5563 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
5564 {
5565     return g_hash_table_lookup(cpregs, &encoded_cp);
5566 }
5567
5568 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
5569                          uint64_t value)
5570 {
5571     /* Helper coprocessor write function for write-ignore registers */
5572 }
5573
5574 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
5575 {
5576     /* Helper coprocessor write function for read-as-zero registers */
5577     return 0;
5578 }
5579
5580 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
5581 {
5582     /* Helper coprocessor reset function for do-nothing-on-reset registers */
5583 }
5584
5585 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
5586 {
5587     /* Return true if it is not valid for us to switch to
5588      * this CPU mode (ie all the UNPREDICTABLE cases in
5589      * the ARM ARM CPSRWriteByInstr pseudocode).
5590      */
5591
5592     /* Changes to or from Hyp via MSR and CPS are illegal. */
5593     if (write_type == CPSRWriteByInstr &&
5594         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
5595          mode == ARM_CPU_MODE_HYP)) {
5596         return 1;
5597     }
5598
5599     switch (mode) {
5600     case ARM_CPU_MODE_USR:
5601         return 0;
5602     case ARM_CPU_MODE_SYS:
5603     case ARM_CPU_MODE_SVC:
5604     case ARM_CPU_MODE_ABT:
5605     case ARM_CPU_MODE_UND:
5606     case ARM_CPU_MODE_IRQ:
5607     case ARM_CPU_MODE_FIQ:
5608         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
5609          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
5610          */
5611         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
5612          * and CPS are treated as illegal mode changes.
5613          */
5614         if (write_type == CPSRWriteByInstr &&
5615             (env->cp15.hcr_el2 & HCR_TGE) &&
5616             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
5617             !arm_is_secure_below_el3(env)) {
5618             return 1;
5619         }
5620         return 0;
5621     case ARM_CPU_MODE_HYP:
5622         return !arm_feature(env, ARM_FEATURE_EL2)
5623             || arm_current_el(env) < 2 || arm_is_secure(env);
5624     case ARM_CPU_MODE_MON:
5625         return arm_current_el(env) < 3;
5626     default:
5627         return 1;
5628     }
5629 }
5630
5631 uint32_t cpsr_read(CPUARMState *env)
5632 {
5633     int ZF;
5634     ZF = (env->ZF == 0);
5635     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
5636         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
5637         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
5638         | ((env->condexec_bits & 0xfc) << 8)
5639         | (env->GE << 16) | (env->daif & CPSR_AIF);
5640 }
5641
5642 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
5643                 CPSRWriteType write_type)
5644 {
5645     uint32_t changed_daif;
5646
5647     if (mask & CPSR_NZCV) {
5648         env->ZF = (~val) & CPSR_Z;
5649         env->NF = val;
5650         env->CF = (val >> 29) & 1;
5651         env->VF = (val << 3) & 0x80000000;
5652     }
5653     if (mask & CPSR_Q)
5654         env->QF = ((val & CPSR_Q) != 0);
5655     if (mask & CPSR_T)
5656         env->thumb = ((val & CPSR_T) != 0);
5657     if (mask & CPSR_IT_0_1) {
5658         env->condexec_bits &= ~3;
5659         env->condexec_bits |= (val >> 25) & 3;
5660     }
5661     if (mask & CPSR_IT_2_7) {
5662         env->condexec_bits &= 3;
5663         env->condexec_bits |= (val >> 8) & 0xfc;
5664     }
5665     if (mask & CPSR_GE) {
5666         env->GE = (val >> 16) & 0xf;
5667     }
5668
5669     /* In a V7 implementation that includes the security extensions but does
5670      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
5671      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
5672      * bits respectively.
5673      *
5674      * In a V8 implementation, it is permitted for privileged software to
5675      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
5676      */
5677     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
5678         arm_feature(env, ARM_FEATURE_EL3) &&
5679         !arm_feature(env, ARM_FEATURE_EL2) &&
5680         !arm_is_secure(env)) {
5681
5682         changed_daif = (env->daif ^ val) & mask;
5683
5684         if (changed_daif & CPSR_A) {
5685             /* Check to see if we are allowed to change the masking of async
5686              * abort exceptions from a non-secure state.
5687              */
5688             if (!(env->cp15.scr_el3 & SCR_AW)) {
5689                 qemu_log_mask(LOG_GUEST_ERROR,
5690                               "Ignoring attempt to switch CPSR_A flag from "
5691                               "non-secure world with SCR.AW bit clear\n");
5692                 mask &= ~CPSR_A;
5693             }
5694         }
5695
5696         if (changed_daif & CPSR_F) {
5697             /* Check to see if we are allowed to change the masking of FIQ
5698              * exceptions from a non-secure state.
5699              */
5700             if (!(env->cp15.scr_el3 & SCR_FW)) {
5701                 qemu_log_mask(LOG_GUEST_ERROR,
5702                               "Ignoring attempt to switch CPSR_F flag from "
5703                               "non-secure world with SCR.FW bit clear\n");
5704                 mask &= ~CPSR_F;
5705             }
5706
5707             /* Check whether non-maskable FIQ (NMFI) support is enabled.
5708              * If this bit is set software is not allowed to mask
5709              * FIQs, but is allowed to set CPSR_F to 0.
5710              */
5711             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
5712                 (val & CPSR_F)) {
5713                 qemu_log_mask(LOG_GUEST_ERROR,
5714                               "Ignoring attempt to enable CPSR_F flag "
5715                               "(non-maskable FIQ [NMFI] support enabled)\n");
5716                 mask &= ~CPSR_F;
5717             }
5718         }
5719     }
5720
5721     env->daif &= ~(CPSR_AIF & mask);
5722     env->daif |= val & CPSR_AIF & mask;
5723
5724     if (write_type != CPSRWriteRaw &&
5725         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
5726         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
5727             /* Note that we can only get here in USR mode if this is a
5728              * gdb stub write; for this case we follow the architectural
5729              * behaviour for guest writes in USR mode of ignoring an attempt
5730              * to switch mode. (Those are caught by translate.c for writes
5731              * triggered by guest instructions.)
5732              */
5733             mask &= ~CPSR_M;
5734         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
5735             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
5736              * v7, and has defined behaviour in v8:
5737              *  + leave CPSR.M untouched
5738              *  + allow changes to the other CPSR fields
5739              *  + set PSTATE.IL
5740              * For user changes via the GDB stub, we don't set PSTATE.IL,
5741              * as this would be unnecessarily harsh for a user error.
5742              */
5743             mask &= ~CPSR_M;
5744             if (write_type != CPSRWriteByGDBStub &&
5745                 arm_feature(env, ARM_FEATURE_V8)) {
5746                 mask |= CPSR_IL;
5747                 val |= CPSR_IL;
5748             }
5749         } else {
5750             switch_mode(env, val & CPSR_M);
5751         }
5752     }
5753     mask &= ~CACHED_CPSR_BITS;
5754     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
5755 }
5756
5757 /* Sign/zero extend */
5758 uint32_t HELPER(sxtb16)(uint32_t x)
5759 {
5760     uint32_t res;
5761     res = (uint16_t)(int8_t)x;
5762     res |= (uint32_t)(int8_t)(x >> 16) << 16;
5763     return res;
5764 }
5765
5766 uint32_t HELPER(uxtb16)(uint32_t x)
5767 {
5768     uint32_t res;
5769     res = (uint16_t)(uint8_t)x;
5770     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
5771     return res;
5772 }
5773
5774 int32_t HELPER(sdiv)(int32_t num, int32_t den)
5775 {
5776     if (den == 0)
5777       return 0;
5778     if (num == INT_MIN && den == -1)
5779       return INT_MIN;
5780     return num / den;
5781 }
5782
5783 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
5784 {
5785     if (den == 0)
5786       return 0;
5787     return num / den;
5788 }
5789
5790 uint32_t HELPER(rbit)(uint32_t x)
5791 {
5792     return revbit32(x);
5793 }
5794
5795 #if defined(CONFIG_USER_ONLY)
5796
5797 /* These should probably raise undefined insn exceptions.  */
5798 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
5799 {
5800     ARMCPU *cpu = arm_env_get_cpu(env);
5801
5802     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
5803 }
5804
5805 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
5806 {
5807     ARMCPU *cpu = arm_env_get_cpu(env);
5808
5809     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
5810     return 0;
5811 }
5812
5813 void switch_mode(CPUARMState *env, int mode)
5814 {
5815     ARMCPU *cpu = arm_env_get_cpu(env);
5816
5817     if (mode != ARM_CPU_MODE_USR) {
5818         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
5819     }
5820 }
5821
5822 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
5823                                  uint32_t cur_el, bool secure)
5824 {
5825     return 1;
5826 }
5827
5828 void aarch64_sync_64_to_32(CPUARMState *env)
5829 {
5830     g_assert_not_reached();
5831 }
5832
5833 #else
5834
5835 void switch_mode(CPUARMState *env, int mode)
5836 {
5837     int old_mode;
5838     int i;
5839
5840     old_mode = env->uncached_cpsr & CPSR_M;
5841     if (mode == old_mode)
5842         return;
5843
5844     if (old_mode == ARM_CPU_MODE_FIQ) {
5845         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
5846         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
5847     } else if (mode == ARM_CPU_MODE_FIQ) {
5848         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
5849         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
5850     }
5851
5852     i = bank_number(old_mode);
5853     env->banked_r13[i] = env->regs[13];
5854     env->banked_r14[i] = env->regs[14];
5855     env->banked_spsr[i] = env->spsr;
5856
5857     i = bank_number(mode);
5858     env->regs[13] = env->banked_r13[i];
5859     env->regs[14] = env->banked_r14[i];
5860     env->spsr = env->banked_spsr[i];
5861 }
5862
5863 /* Physical Interrupt Target EL Lookup Table
5864  *
5865  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
5866  *
5867  * The below multi-dimensional table is used for looking up the target
5868  * exception level given numerous condition criteria.  Specifically, the
5869  * target EL is based on SCR and HCR routing controls as well as the
5870  * currently executing EL and secure state.
5871  *
5872  *    Dimensions:
5873  *    target_el_table[2][2][2][2][2][4]
5874  *                    |  |  |  |  |  +--- Current EL
5875  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
5876  *                    |  |  |  +--------- HCR mask override
5877  *                    |  |  +------------ SCR exec state control
5878  *                    |  +--------------- SCR mask override
5879  *                    +------------------ 32-bit(0)/64-bit(1) EL3
5880  *
5881  *    The table values are as such:
5882  *    0-3 = EL0-EL3
5883  *     -1 = Cannot occur
5884  *
5885  * The ARM ARM target EL table includes entries indicating that an "exception
5886  * is not taken".  The two cases where this is applicable are:
5887  *    1) An exception is taken from EL3 but the SCR does not have the exception
5888  *    routed to EL3.
5889  *    2) An exception is taken from EL2 but the HCR does not have the exception
5890  *    routed to EL2.
5891  * In these two cases, the below table contain a target of EL1.  This value is
5892  * returned as it is expected that the consumer of the table data will check
5893  * for "target EL >= current EL" to ensure the exception is not taken.
5894  *
5895  *            SCR     HCR
5896  *         64  EA     AMO                 From
5897  *        BIT IRQ     IMO      Non-secure         Secure
5898  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
5899  */
5900 static const int8_t target_el_table[2][2][2][2][2][4] = {
5901     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
5902        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
5903       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
5904        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
5905      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
5906        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
5907       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
5908        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
5909     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
5910        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
5911       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
5912        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
5913      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
5914        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
5915       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
5916        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
5917 };
5918
5919 /*
5920  * Determine the target EL for physical exceptions
5921  */
5922 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
5923                                  uint32_t cur_el, bool secure)
5924 {
5925     CPUARMState *env = cs->env_ptr;
5926     int rw;
5927     int scr;
5928     int hcr;
5929     int target_el;
5930     /* Is the highest EL AArch64? */
5931     int is64 = arm_feature(env, ARM_FEATURE_AARCH64);
5932
5933     if (arm_feature(env, ARM_FEATURE_EL3)) {
5934         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
5935     } else {
5936         /* Either EL2 is the highest EL (and so the EL2 register width
5937          * is given by is64); or there is no EL2 or EL3, in which case
5938          * the value of 'rw' does not affect the table lookup anyway.
5939          */
5940         rw = is64;
5941     }
5942
5943     switch (excp_idx) {
5944     case EXCP_IRQ:
5945         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
5946         hcr = ((env->cp15.hcr_el2 & HCR_IMO) == HCR_IMO);
5947         break;
5948     case EXCP_FIQ:
5949         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
5950         hcr = ((env->cp15.hcr_el2 & HCR_FMO) == HCR_FMO);
5951         break;
5952     default:
5953         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
5954         hcr = ((env->cp15.hcr_el2 & HCR_AMO) == HCR_AMO);
5955         break;
5956     };
5957
5958     /* If HCR.TGE is set then HCR is treated as being 1 */
5959     hcr |= ((env->cp15.hcr_el2 & HCR_TGE) == HCR_TGE);
5960
5961     /* Perform a table-lookup for the target EL given the current state */
5962     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
5963
5964     assert(target_el > 0);
5965
5966     return target_el;
5967 }
5968
5969 static void v7m_push(CPUARMState *env, uint32_t val)
5970 {
5971     CPUState *cs = CPU(arm_env_get_cpu(env));
5972
5973     env->regs[13] -= 4;
5974     stl_phys(cs->as, env->regs[13], val);
5975 }
5976
5977 static uint32_t v7m_pop(CPUARMState *env)
5978 {
5979     CPUState *cs = CPU(arm_env_get_cpu(env));
5980     uint32_t val;
5981
5982     val = ldl_phys(cs->as, env->regs[13]);
5983     env->regs[13] += 4;
5984     return val;
5985 }
5986
5987 /* Switch to V7M main or process stack pointer.  */
5988 static void switch_v7m_sp(CPUARMState *env, bool new_spsel)
5989 {
5990     uint32_t tmp;
5991     bool old_spsel = env->v7m.control & R_V7M_CONTROL_SPSEL_MASK;
5992
5993     if (old_spsel != new_spsel) {
5994         tmp = env->v7m.other_sp;
5995         env->v7m.other_sp = env->regs[13];
5996         env->regs[13] = tmp;
5997
5998         env->v7m.control = deposit32(env->v7m.control,
5999                                      R_V7M_CONTROL_SPSEL_SHIFT,
6000                                      R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);
6001     }
6002 }
6003
6004 static void do_v7m_exception_exit(CPUARMState *env)
6005 {
6006     uint32_t type;
6007     uint32_t xpsr;
6008
6009     type = env->regs[15];
6010     if (env->v7m.exception != ARMV7M_EXCP_NMI) {
6011         /* Auto-clear FAULTMASK on return from other than NMI */
6012         env->daif &= ~PSTATE_F;
6013     }
6014     if (env->v7m.exception != 0) {
6015         armv7m_nvic_complete_irq(env->nvic, env->v7m.exception);
6016     }
6017
6018     /* Switch to the target stack.  */
6019     switch_v7m_sp(env, (type & 4) != 0);
6020     /* Pop registers.  */
6021     env->regs[0] = v7m_pop(env);
6022     env->regs[1] = v7m_pop(env);
6023     env->regs[2] = v7m_pop(env);
6024     env->regs[3] = v7m_pop(env);
6025     env->regs[12] = v7m_pop(env);
6026     env->regs[14] = v7m_pop(env);
6027     env->regs[15] = v7m_pop(env);
6028     if (env->regs[15] & 1) {
6029         qemu_log_mask(LOG_GUEST_ERROR,
6030                       "M profile return from interrupt with misaligned "
6031                       "PC is UNPREDICTABLE\n");
6032         /* Actual hardware seems to ignore the lsbit, and there are several
6033          * RTOSes out there which incorrectly assume the r15 in the stack
6034          * frame should be a Thumb-style "lsbit indicates ARM/Thumb" value.
6035          */
6036         env->regs[15] &= ~1U;
6037     }
6038     xpsr = v7m_pop(env);
6039     xpsr_write(env, xpsr, 0xfffffdff);
6040     /* Undo stack alignment.  */
6041     if (xpsr & 0x200)
6042         env->regs[13] |= 4;
6043     /* ??? The exception return type specifies Thread/Handler mode.  However
6044        this is also implied by the xPSR value. Not sure what to do
6045        if there is a mismatch.  */
6046     /* ??? Likewise for mismatches between the CONTROL register and the stack
6047        pointer.  */
6048 }
6049
6050 static void arm_log_exception(int idx)
6051 {
6052     if (qemu_loglevel_mask(CPU_LOG_INT)) {
6053         const char *exc = NULL;
6054
6055         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
6056             exc = excnames[idx];
6057         }
6058         if (!exc) {
6059             exc = "unknown";
6060         }
6061         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
6062     }
6063 }
6064
6065 static uint32_t arm_v7m_load_vector(ARMCPU *cpu)
6066
6067 {
6068     CPUState *cs = CPU(cpu);
6069     CPUARMState *env = &cpu->env;
6070     MemTxResult result;
6071     hwaddr vec = env->v7m.vecbase + env->v7m.exception * 4;
6072     uint32_t addr;
6073
6074     addr = address_space_ldl(cs->as, vec,
6075                              MEMTXATTRS_UNSPECIFIED, &result);
6076     if (result != MEMTX_OK) {
6077         /* Architecturally this should cause a HardFault setting HSFR.VECTTBL,
6078          * which would then be immediately followed by our failing to load
6079          * the entry vector for that HardFault, which is a Lockup case.
6080          * Since we don't model Lockup, we just report this guest error
6081          * via cpu_abort().
6082          */
6083         cpu_abort(cs, "Failed to read from exception vector table "
6084                   "entry %08x\n", (unsigned)vec);
6085     }
6086     return addr;
6087 }
6088
6089 void arm_v7m_cpu_do_interrupt(CPUState *cs)
6090 {
6091     ARMCPU *cpu = ARM_CPU(cs);
6092     CPUARMState *env = &cpu->env;
6093     uint32_t xpsr = xpsr_read(env);
6094     uint32_t lr;
6095     uint32_t addr;
6096
6097     arm_log_exception(cs->exception_index);
6098
6099     lr = 0xfffffff1;
6100     if (env->v7m.control & R_V7M_CONTROL_SPSEL_MASK) {
6101         lr |= 4;
6102     }
6103     if (env->v7m.exception == 0)
6104         lr |= 8;
6105
6106     /* For exceptions we just mark as pending on the NVIC, and let that
6107        handle it.  */
6108     /* TODO: Need to escalate if the current priority is higher than the
6109        one we're raising.  */
6110     switch (cs->exception_index) {
6111     case EXCP_UDEF:
6112         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE);
6113         env->v7m.cfsr |= R_V7M_CFSR_UNDEFINSTR_MASK;
6114         return;
6115     case EXCP_NOCP:
6116         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE);
6117         env->v7m.cfsr |= R_V7M_CFSR_NOCP_MASK;
6118         return;
6119     case EXCP_SWI:
6120         /* The PC already points to the next instruction.  */
6121         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC);
6122         return;
6123     case EXCP_PREFETCH_ABORT:
6124     case EXCP_DATA_ABORT:
6125         /* TODO: if we implemented the MPU registers, this is where we
6126          * should set the MMFAR, etc from exception.fsr and exception.vaddress.
6127          */
6128         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM);
6129         return;
6130     case EXCP_BKPT:
6131         if (semihosting_enabled()) {
6132             int nr;
6133             nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;
6134             if (nr == 0xab) {
6135                 env->regs[15] += 2;
6136                 qemu_log_mask(CPU_LOG_INT,
6137                               "...handling as semihosting call 0x%x\n",
6138                               env->regs[0]);
6139                 env->regs[0] = do_arm_semihosting(env);
6140                 return;
6141             }
6142         }
6143         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG);
6144         return;
6145     case EXCP_IRQ:
6146         env->v7m.exception = armv7m_nvic_acknowledge_irq(env->nvic);
6147         break;
6148     case EXCP_EXCEPTION_EXIT:
6149         do_v7m_exception_exit(env);
6150         return;
6151     default:
6152         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
6153         return; /* Never happens.  Keep compiler happy.  */
6154     }
6155
6156     /* Align stack pointer if the guest wants that */
6157     if ((env->regs[13] & 4) && (env->v7m.ccr & R_V7M_CCR_STKALIGN_MASK)) {
6158         env->regs[13] -= 4;
6159         xpsr |= 0x200;
6160     }
6161     /* Switch to the handler mode.  */
6162     v7m_push(env, xpsr);
6163     v7m_push(env, env->regs[15]);
6164     v7m_push(env, env->regs[14]);
6165     v7m_push(env, env->regs[12]);
6166     v7m_push(env, env->regs[3]);
6167     v7m_push(env, env->regs[2]);
6168     v7m_push(env, env->regs[1]);
6169     v7m_push(env, env->regs[0]);
6170     switch_v7m_sp(env, 0);
6171     /* Clear IT bits */
6172     env->condexec_bits = 0;
6173     env->regs[14] = lr;
6174     addr = arm_v7m_load_vector(cpu);
6175     env->regs[15] = addr & 0xfffffffe;
6176     env->thumb = addr & 1;
6177 }
6178
6179 /* Function used to synchronize QEMU's AArch64 register set with AArch32
6180  * register set.  This is necessary when switching between AArch32 and AArch64
6181  * execution state.
6182  */
6183 void aarch64_sync_32_to_64(CPUARMState *env)
6184 {
6185     int i;
6186     uint32_t mode = env->uncached_cpsr & CPSR_M;
6187
6188     /* We can blanket copy R[0:7] to X[0:7] */
6189     for (i = 0; i < 8; i++) {
6190         env->xregs[i] = env->regs[i];
6191     }
6192
6193     /* Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
6194      * Otherwise, they come from the banked user regs.
6195      */
6196     if (mode == ARM_CPU_MODE_FIQ) {
6197         for (i = 8; i < 13; i++) {
6198             env->xregs[i] = env->usr_regs[i - 8];
6199         }
6200     } else {
6201         for (i = 8; i < 13; i++) {
6202             env->xregs[i] = env->regs[i];
6203         }
6204     }
6205
6206     /* Registers x13-x23 are the various mode SP and FP registers. Registers
6207      * r13 and r14 are only copied if we are in that mode, otherwise we copy
6208      * from the mode banked register.
6209      */
6210     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
6211         env->xregs[13] = env->regs[13];
6212         env->xregs[14] = env->regs[14];
6213     } else {
6214         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
6215         /* HYP is an exception in that it is copied from r14 */
6216         if (mode == ARM_CPU_MODE_HYP) {
6217             env->xregs[14] = env->regs[14];
6218         } else {
6219             env->xregs[14] = env->banked_r14[bank_number(ARM_CPU_MODE_USR)];
6220         }
6221     }
6222
6223     if (mode == ARM_CPU_MODE_HYP) {
6224         env->xregs[15] = env->regs[13];
6225     } else {
6226         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
6227     }
6228
6229     if (mode == ARM_CPU_MODE_IRQ) {
6230         env->xregs[16] = env->regs[14];
6231         env->xregs[17] = env->regs[13];
6232     } else {
6233         env->xregs[16] = env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)];
6234         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
6235     }
6236
6237     if (mode == ARM_CPU_MODE_SVC) {
6238         env->xregs[18] = env->regs[14];
6239         env->xregs[19] = env->regs[13];
6240     } else {
6241         env->xregs[18] = env->banked_r14[bank_number(ARM_CPU_MODE_SVC)];
6242         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
6243     }
6244
6245     if (mode == ARM_CPU_MODE_ABT) {
6246         env->xregs[20] = env->regs[14];
6247         env->xregs[21] = env->regs[13];
6248     } else {
6249         env->xregs[20] = env->banked_r14[bank_number(ARM_CPU_MODE_ABT)];
6250         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
6251     }
6252
6253     if (mode == ARM_CPU_MODE_UND) {
6254         env->xregs[22] = env->regs[14];
6255         env->xregs[23] = env->regs[13];
6256     } else {
6257         env->xregs[22] = env->banked_r14[bank_number(ARM_CPU_MODE_UND)];
6258         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
6259     }
6260
6261     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
6262      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
6263      * FIQ bank for r8-r14.
6264      */
6265     if (mode == ARM_CPU_MODE_FIQ) {
6266         for (i = 24; i < 31; i++) {
6267             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
6268         }
6269     } else {
6270         for (i = 24; i < 29; i++) {
6271             env->xregs[i] = env->fiq_regs[i - 24];
6272         }
6273         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
6274         env->xregs[30] = env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)];
6275     }
6276
6277     env->pc = env->regs[15];
6278 }
6279
6280 /* Function used to synchronize QEMU's AArch32 register set with AArch64
6281  * register set.  This is necessary when switching between AArch32 and AArch64
6282  * execution state.
6283  */
6284 void aarch64_sync_64_to_32(CPUARMState *env)
6285 {
6286     int i;
6287     uint32_t mode = env->uncached_cpsr & CPSR_M;
6288
6289     /* We can blanket copy X[0:7] to R[0:7] */
6290     for (i = 0; i < 8; i++) {
6291         env->regs[i] = env->xregs[i];
6292     }
6293
6294     /* Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
6295      * Otherwise, we copy x8-x12 into the banked user regs.
6296      */
6297     if (mode == ARM_CPU_MODE_FIQ) {
6298         for (i = 8; i < 13; i++) {
6299             env->usr_regs[i - 8] = env->xregs[i];
6300         }
6301     } else {
6302         for (i = 8; i < 13; i++) {
6303             env->regs[i] = env->xregs[i];
6304         }
6305     }
6306
6307     /* Registers r13 & r14 depend on the current mode.
6308      * If we are in a given mode, we copy the corresponding x registers to r13
6309      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
6310      * for the mode.
6311      */
6312     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
6313         env->regs[13] = env->xregs[13];
6314         env->regs[14] = env->xregs[14];
6315     } else {
6316         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
6317
6318         /* HYP is an exception in that it does not have its own banked r14 but
6319          * shares the USR r14
6320          */
6321         if (mode == ARM_CPU_MODE_HYP) {
6322             env->regs[14] = env->xregs[14];
6323         } else {
6324             env->banked_r14[bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
6325         }
6326     }
6327
6328     if (mode == ARM_CPU_MODE_HYP) {
6329         env->regs[13] = env->xregs[15];
6330     } else {
6331         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
6332     }
6333
6334     if (mode == ARM_CPU_MODE_IRQ) {
6335         env->regs[14] = env->xregs[16];
6336         env->regs[13] = env->xregs[17];
6337     } else {
6338         env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
6339         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
6340     }
6341
6342     if (mode == ARM_CPU_MODE_SVC) {
6343         env->regs[14] = env->xregs[18];
6344         env->regs[13] = env->xregs[19];
6345     } else {
6346         env->banked_r14[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
6347         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
6348     }
6349
6350     if (mode == ARM_CPU_MODE_ABT) {
6351         env->regs[14] = env->xregs[20];
6352         env->regs[13] = env->xregs[21];
6353     } else {
6354         env->banked_r14[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
6355         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
6356     }
6357
6358     if (mode == ARM_CPU_MODE_UND) {
6359         env->regs[14] = env->xregs[22];
6360         env->regs[13] = env->xregs[23];
6361     } else {
6362         env->banked_r14[bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
6363         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
6364     }
6365
6366     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
6367      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
6368      * FIQ bank for r8-r14.
6369      */
6370     if (mode == ARM_CPU_MODE_FIQ) {
6371         for (i = 24; i < 31; i++) {
6372             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
6373         }
6374     } else {
6375         for (i = 24; i < 29; i++) {
6376             env->fiq_regs[i - 24] = env->xregs[i];
6377         }
6378         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
6379         env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
6380     }
6381
6382     env->regs[15] = env->pc;
6383 }
6384
6385 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
6386 {
6387     ARMCPU *cpu = ARM_CPU(cs);
6388     CPUARMState *env = &cpu->env;
6389     uint32_t addr;
6390     uint32_t mask;
6391     int new_mode;
6392     uint32_t offset;
6393     uint32_t moe;
6394
6395     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
6396     switch (env->exception.syndrome >> ARM_EL_EC_SHIFT) {
6397     case EC_BREAKPOINT:
6398     case EC_BREAKPOINT_SAME_EL:
6399         moe = 1;
6400         break;
6401     case EC_WATCHPOINT:
6402     case EC_WATCHPOINT_SAME_EL:
6403         moe = 10;
6404         break;
6405     case EC_AA32_BKPT:
6406         moe = 3;
6407         break;
6408     case EC_VECTORCATCH:
6409         moe = 5;
6410         break;
6411     default:
6412         moe = 0;
6413         break;
6414     }
6415
6416     if (moe) {
6417         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
6418     }
6419
6420     /* TODO: Vectored interrupt controller.  */
6421     switch (cs->exception_index) {
6422     case EXCP_UDEF:
6423         new_mode = ARM_CPU_MODE_UND;
6424         addr = 0x04;
6425         mask = CPSR_I;
6426         if (env->thumb)
6427             offset = 2;
6428         else
6429             offset = 4;
6430         break;
6431     case EXCP_SWI:
6432         new_mode = ARM_CPU_MODE_SVC;
6433         addr = 0x08;
6434         mask = CPSR_I;
6435         /* The PC already points to the next instruction.  */
6436         offset = 0;
6437         break;
6438     case EXCP_BKPT:
6439         env->exception.fsr = 2;
6440         /* Fall through to prefetch abort.  */
6441     case EXCP_PREFETCH_ABORT:
6442         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
6443         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
6444         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
6445                       env->exception.fsr, (uint32_t)env->exception.vaddress);
6446         new_mode = ARM_CPU_MODE_ABT;
6447         addr = 0x0c;
6448         mask = CPSR_A | CPSR_I;
6449         offset = 4;
6450         break;
6451     case EXCP_DATA_ABORT:
6452         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
6453         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
6454         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
6455                       env->exception.fsr,
6456                       (uint32_t)env->exception.vaddress);
6457         new_mode = ARM_CPU_MODE_ABT;
6458         addr = 0x10;
6459         mask = CPSR_A | CPSR_I;
6460         offset = 8;
6461         break;
6462     case EXCP_IRQ:
6463         new_mode = ARM_CPU_MODE_IRQ;
6464         addr = 0x18;
6465         /* Disable IRQ and imprecise data aborts.  */
6466         mask = CPSR_A | CPSR_I;
6467         offset = 4;
6468         if (env->cp15.scr_el3 & SCR_IRQ) {
6469             /* IRQ routed to monitor mode */
6470             new_mode = ARM_CPU_MODE_MON;
6471             mask |= CPSR_F;
6472         }
6473         break;
6474     case EXCP_FIQ:
6475         new_mode = ARM_CPU_MODE_FIQ;
6476         addr = 0x1c;
6477         /* Disable FIQ, IRQ and imprecise data aborts.  */
6478         mask = CPSR_A | CPSR_I | CPSR_F;
6479         if (env->cp15.scr_el3 & SCR_FIQ) {
6480             /* FIQ routed to monitor mode */
6481             new_mode = ARM_CPU_MODE_MON;
6482         }
6483         offset = 4;
6484         break;
6485     case EXCP_VIRQ:
6486         new_mode = ARM_CPU_MODE_IRQ;
6487         addr = 0x18;
6488         /* Disable IRQ and imprecise data aborts.  */
6489         mask = CPSR_A | CPSR_I;
6490         offset = 4;
6491         break;
6492     case EXCP_VFIQ:
6493         new_mode = ARM_CPU_MODE_FIQ;
6494         addr = 0x1c;
6495         /* Disable FIQ, IRQ and imprecise data aborts.  */
6496         mask = CPSR_A | CPSR_I | CPSR_F;
6497         offset = 4;
6498         break;
6499     case EXCP_SMC:
6500         new_mode = ARM_CPU_MODE_MON;
6501         addr = 0x08;
6502         mask = CPSR_A | CPSR_I | CPSR_F;
6503         offset = 0;
6504         break;
6505     default:
6506         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
6507         return; /* Never happens.  Keep compiler happy.  */
6508     }
6509
6510     if (new_mode == ARM_CPU_MODE_MON) {
6511         addr += env->cp15.mvbar;
6512     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
6513         /* High vectors. When enabled, base address cannot be remapped. */
6514         addr += 0xffff0000;
6515     } else {
6516         /* ARM v7 architectures provide a vector base address register to remap
6517          * the interrupt vector table.
6518          * This register is only followed in non-monitor mode, and is banked.
6519          * Note: only bits 31:5 are valid.
6520          */
6521         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
6522     }
6523
6524     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
6525         env->cp15.scr_el3 &= ~SCR_NS;
6526     }
6527
6528     switch_mode (env, new_mode);
6529     /* For exceptions taken to AArch32 we must clear the SS bit in both
6530      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
6531      */
6532     env->uncached_cpsr &= ~PSTATE_SS;
6533     env->spsr = cpsr_read(env);
6534     /* Clear IT bits.  */
6535     env->condexec_bits = 0;
6536     /* Switch to the new mode, and to the correct instruction set.  */
6537     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
6538     /* Set new mode endianness */
6539     env->uncached_cpsr &= ~CPSR_E;
6540     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
6541         env->uncached_cpsr |= CPSR_E;
6542     }
6543     env->daif |= mask;
6544     /* this is a lie, as the was no c1_sys on V4T/V5, but who cares
6545      * and we should just guard the thumb mode on V4 */
6546     if (arm_feature(env, ARM_FEATURE_V4T)) {
6547         env->thumb = (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
6548     }
6549     env->regs[14] = env->regs[15] + offset;
6550     env->regs[15] = addr;
6551 }
6552
6553 /* Handle exception entry to a target EL which is using AArch64 */
6554 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
6555 {
6556     ARMCPU *cpu = ARM_CPU(cs);
6557     CPUARMState *env = &cpu->env;
6558     unsigned int new_el = env->exception.target_el;
6559     target_ulong addr = env->cp15.vbar_el[new_el];
6560     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
6561
6562     if (arm_current_el(env) < new_el) {
6563         /* Entry vector offset depends on whether the implemented EL
6564          * immediately lower than the target level is using AArch32 or AArch64
6565          */
6566         bool is_aa64;
6567
6568         switch (new_el) {
6569         case 3:
6570             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
6571             break;
6572         case 2:
6573             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
6574             break;
6575         case 1:
6576             is_aa64 = is_a64(env);
6577             break;
6578         default:
6579             g_assert_not_reached();
6580         }
6581
6582         if (is_aa64) {
6583             addr += 0x400;
6584         } else {
6585             addr += 0x600;
6586         }
6587     } else if (pstate_read(env) & PSTATE_SP) {
6588         addr += 0x200;
6589     }
6590
6591     switch (cs->exception_index) {
6592     case EXCP_PREFETCH_ABORT:
6593     case EXCP_DATA_ABORT:
6594         env->cp15.far_el[new_el] = env->exception.vaddress;
6595         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
6596                       env->cp15.far_el[new_el]);
6597         /* fall through */
6598     case EXCP_BKPT:
6599     case EXCP_UDEF:
6600     case EXCP_SWI:
6601     case EXCP_HVC:
6602     case EXCP_HYP_TRAP:
6603     case EXCP_SMC:
6604         env->cp15.esr_el[new_el] = env->exception.syndrome;
6605         break;
6606     case EXCP_IRQ:
6607     case EXCP_VIRQ:
6608         addr += 0x80;
6609         break;
6610     case EXCP_FIQ:
6611     case EXCP_VFIQ:
6612         addr += 0x100;
6613         break;
6614     case EXCP_SEMIHOST:
6615         qemu_log_mask(CPU_LOG_INT,
6616                       "...handling as semihosting call 0x%" PRIx64 "\n",
6617                       env->xregs[0]);
6618         env->xregs[0] = do_arm_semihosting(env);
6619         return;
6620     default:
6621         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
6622     }
6623
6624     if (is_a64(env)) {
6625         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
6626         aarch64_save_sp(env, arm_current_el(env));
6627         env->elr_el[new_el] = env->pc;
6628     } else {
6629         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
6630         env->elr_el[new_el] = env->regs[15];
6631
6632         aarch64_sync_32_to_64(env);
6633
6634         env->condexec_bits = 0;
6635     }
6636     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
6637                   env->elr_el[new_el]);
6638
6639     pstate_write(env, PSTATE_DAIF | new_mode);
6640     env->aarch64 = 1;
6641     aarch64_restore_sp(env, new_el);
6642
6643     env->pc = addr;
6644
6645     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
6646                   new_el, env->pc, pstate_read(env));
6647 }
6648
6649 static inline bool check_for_semihosting(CPUState *cs)
6650 {
6651     /* Check whether this exception is a semihosting call; if so
6652      * then handle it and return true; otherwise return false.
6653      */
6654     ARMCPU *cpu = ARM_CPU(cs);
6655     CPUARMState *env = &cpu->env;
6656
6657     if (is_a64(env)) {
6658         if (cs->exception_index == EXCP_SEMIHOST) {
6659             /* This is always the 64-bit semihosting exception.
6660              * The "is this usermode" and "is semihosting enabled"
6661              * checks have been done at translate time.
6662              */
6663             qemu_log_mask(CPU_LOG_INT,
6664                           "...handling as semihosting call 0x%" PRIx64 "\n",
6665                           env->xregs[0]);
6666             env->xregs[0] = do_arm_semihosting(env);
6667             return true;
6668         }
6669         return false;
6670     } else {
6671         uint32_t imm;
6672
6673         /* Only intercept calls from privileged modes, to provide some
6674          * semblance of security.
6675          */
6676         if (cs->exception_index != EXCP_SEMIHOST &&
6677             (!semihosting_enabled() ||
6678              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
6679             return false;
6680         }
6681
6682         switch (cs->exception_index) {
6683         case EXCP_SEMIHOST:
6684             /* This is always a semihosting call; the "is this usermode"
6685              * and "is semihosting enabled" checks have been done at
6686              * translate time.
6687              */
6688             break;
6689         case EXCP_SWI:
6690             /* Check for semihosting interrupt.  */
6691             if (env->thumb) {
6692                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
6693                     & 0xff;
6694                 if (imm == 0xab) {
6695                     break;
6696                 }
6697             } else {
6698                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
6699                     & 0xffffff;
6700                 if (imm == 0x123456) {
6701                     break;
6702                 }
6703             }
6704             return false;
6705         case EXCP_BKPT:
6706             /* See if this is a semihosting syscall.  */
6707             if (env->thumb) {
6708                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
6709                     & 0xff;
6710                 if (imm == 0xab) {
6711                     env->regs[15] += 2;
6712                     break;
6713                 }
6714             }
6715             return false;
6716         default:
6717             return false;
6718         }
6719
6720         qemu_log_mask(CPU_LOG_INT,
6721                       "...handling as semihosting call 0x%x\n",
6722                       env->regs[0]);
6723         env->regs[0] = do_arm_semihosting(env);
6724         return true;
6725     }
6726 }
6727
6728 /* Handle a CPU exception for A and R profile CPUs.
6729  * Do any appropriate logging, handle PSCI calls, and then hand off
6730  * to the AArch64-entry or AArch32-entry function depending on the
6731  * target exception level's register width.
6732  */
6733 void arm_cpu_do_interrupt(CPUState *cs)
6734 {
6735     ARMCPU *cpu = ARM_CPU(cs);
6736     CPUARMState *env = &cpu->env;
6737     unsigned int new_el = env->exception.target_el;
6738
6739     assert(!arm_feature(env, ARM_FEATURE_M));
6740
6741     arm_log_exception(cs->exception_index);
6742     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
6743                   new_el);
6744     if (qemu_loglevel_mask(CPU_LOG_INT)
6745         && !excp_is_internal(cs->exception_index)) {
6746         qemu_log_mask(CPU_LOG_INT, "...with ESR %x/0x%" PRIx32 "\n",
6747                       env->exception.syndrome >> ARM_EL_EC_SHIFT,
6748                       env->exception.syndrome);
6749     }
6750
6751     if (arm_is_psci_call(cpu, cs->exception_index)) {
6752         arm_handle_psci_call(cpu);
6753         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
6754         return;
6755     }
6756
6757     /* Semihosting semantics depend on the register width of the
6758      * code that caused the exception, not the target exception level,
6759      * so must be handled here.
6760      */
6761     if (check_for_semihosting(cs)) {
6762         return;
6763     }
6764
6765     assert(!excp_is_internal(cs->exception_index));
6766     if (arm_el_is_aa64(env, new_el)) {
6767         arm_cpu_do_interrupt_aarch64(cs);
6768     } else {
6769         arm_cpu_do_interrupt_aarch32(cs);
6770     }
6771
6772     /* Hooks may change global state so BQL should be held, also the
6773      * BQL needs to be held for any modification of
6774      * cs->interrupt_request.
6775      */
6776     g_assert(qemu_mutex_iothread_locked());
6777
6778     arm_call_el_change_hook(cpu);
6779
6780     if (!kvm_enabled()) {
6781         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
6782     }
6783 }
6784
6785 /* Return the exception level which controls this address translation regime */
6786 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
6787 {
6788     switch (mmu_idx) {
6789     case ARMMMUIdx_S2NS:
6790     case ARMMMUIdx_S1E2:
6791         return 2;
6792     case ARMMMUIdx_S1E3:
6793         return 3;
6794     case ARMMMUIdx_S1SE0:
6795         return arm_el_is_aa64(env, 3) ? 1 : 3;
6796     case ARMMMUIdx_S1SE1:
6797     case ARMMMUIdx_S1NSE0:
6798     case ARMMMUIdx_S1NSE1:
6799         return 1;
6800     default:
6801         g_assert_not_reached();
6802     }
6803 }
6804
6805 /* Return true if this address translation regime is secure */
6806 static inline bool regime_is_secure(CPUARMState *env, ARMMMUIdx mmu_idx)
6807 {
6808     switch (mmu_idx) {
6809     case ARMMMUIdx_S12NSE0:
6810     case ARMMMUIdx_S12NSE1:
6811     case ARMMMUIdx_S1NSE0:
6812     case ARMMMUIdx_S1NSE1:
6813     case ARMMMUIdx_S1E2:
6814     case ARMMMUIdx_S2NS:
6815         return false;
6816     case ARMMMUIdx_S1E3:
6817     case ARMMMUIdx_S1SE0:
6818     case ARMMMUIdx_S1SE1:
6819         return true;
6820     default:
6821         g_assert_not_reached();
6822     }
6823 }
6824
6825 /* Return the SCTLR value which controls this address translation regime */
6826 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
6827 {
6828     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
6829 }
6830
6831 /* Return true if the specified stage of address translation is disabled */
6832 static inline bool regime_translation_disabled(CPUARMState *env,
6833                                                ARMMMUIdx mmu_idx)
6834 {
6835     if (mmu_idx == ARMMMUIdx_S2NS) {
6836         return (env->cp15.hcr_el2 & HCR_VM) == 0;
6837     }
6838     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
6839 }
6840
6841 static inline bool regime_translation_big_endian(CPUARMState *env,
6842                                                  ARMMMUIdx mmu_idx)
6843 {
6844     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
6845 }
6846
6847 /* Return the TCR controlling this translation regime */
6848 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
6849 {
6850     if (mmu_idx == ARMMMUIdx_S2NS) {
6851         return &env->cp15.vtcr_el2;
6852     }
6853     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
6854 }
6855
6856 /* Returns TBI0 value for current regime el */
6857 uint32_t arm_regime_tbi0(CPUARMState *env, ARMMMUIdx mmu_idx)
6858 {
6859     TCR *tcr;
6860     uint32_t el;
6861
6862     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
6863        * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
6864        */
6865     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
6866         mmu_idx += ARMMMUIdx_S1NSE0;
6867     }
6868
6869     tcr = regime_tcr(env, mmu_idx);
6870     el = regime_el(env, mmu_idx);
6871
6872     if (el > 1) {
6873         return extract64(tcr->raw_tcr, 20, 1);
6874     } else {
6875         return extract64(tcr->raw_tcr, 37, 1);
6876     }
6877 }
6878
6879 /* Returns TBI1 value for current regime el */
6880 uint32_t arm_regime_tbi1(CPUARMState *env, ARMMMUIdx mmu_idx)
6881 {
6882     TCR *tcr;
6883     uint32_t el;
6884
6885     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
6886        * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
6887        */
6888     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
6889         mmu_idx += ARMMMUIdx_S1NSE0;
6890     }
6891
6892     tcr = regime_tcr(env, mmu_idx);
6893     el = regime_el(env, mmu_idx);
6894
6895     if (el > 1) {
6896         return 0;
6897     } else {
6898         return extract64(tcr->raw_tcr, 38, 1);
6899     }
6900 }
6901
6902 /* Return the TTBR associated with this translation regime */
6903 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
6904                                    int ttbrn)
6905 {
6906     if (mmu_idx == ARMMMUIdx_S2NS) {
6907         return env->cp15.vttbr_el2;
6908     }
6909     if (ttbrn == 0) {
6910         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
6911     } else {
6912         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
6913     }
6914 }
6915
6916 /* Return true if the translation regime is using LPAE format page tables */
6917 static inline bool regime_using_lpae_format(CPUARMState *env,
6918                                             ARMMMUIdx mmu_idx)
6919 {
6920     int el = regime_el(env, mmu_idx);
6921     if (el == 2 || arm_el_is_aa64(env, el)) {
6922         return true;
6923     }
6924     if (arm_feature(env, ARM_FEATURE_LPAE)
6925         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
6926         return true;
6927     }
6928     return false;
6929 }
6930
6931 /* Returns true if the stage 1 translation regime is using LPAE format page
6932  * tables. Used when raising alignment exceptions, whose FSR changes depending
6933  * on whether the long or short descriptor format is in use. */
6934 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
6935 {
6936     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
6937         mmu_idx += ARMMMUIdx_S1NSE0;
6938     }
6939
6940     return regime_using_lpae_format(env, mmu_idx);
6941 }
6942
6943 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
6944 {
6945     switch (mmu_idx) {
6946     case ARMMMUIdx_S1SE0:
6947     case ARMMMUIdx_S1NSE0:
6948         return true;
6949     default:
6950         return false;
6951     case ARMMMUIdx_S12NSE0:
6952     case ARMMMUIdx_S12NSE1:
6953         g_assert_not_reached();
6954     }
6955 }
6956
6957 /* Translate section/page access permissions to page
6958  * R/W protection flags
6959  *
6960  * @env:         CPUARMState
6961  * @mmu_idx:     MMU index indicating required translation regime
6962  * @ap:          The 3-bit access permissions (AP[2:0])
6963  * @domain_prot: The 2-bit domain access permissions
6964  */
6965 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
6966                                 int ap, int domain_prot)
6967 {
6968     bool is_user = regime_is_user(env, mmu_idx);
6969
6970     if (domain_prot == 3) {
6971         return PAGE_READ | PAGE_WRITE;
6972     }
6973
6974     switch (ap) {
6975     case 0:
6976         if (arm_feature(env, ARM_FEATURE_V7)) {
6977             return 0;
6978         }
6979         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
6980         case SCTLR_S:
6981             return is_user ? 0 : PAGE_READ;
6982         case SCTLR_R:
6983             return PAGE_READ;
6984         default:
6985             return 0;
6986         }
6987     case 1:
6988         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
6989     case 2:
6990         if (is_user) {
6991             return PAGE_READ;
6992         } else {
6993             return PAGE_READ | PAGE_WRITE;
6994         }
6995     case 3:
6996         return PAGE_READ | PAGE_WRITE;
6997     case 4: /* Reserved.  */
6998         return 0;
6999     case 5:
7000         return is_user ? 0 : PAGE_READ;
7001     case 6:
7002         return PAGE_READ;
7003     case 7:
7004         if (!arm_feature(env, ARM_FEATURE_V6K)) {
7005             return 0;
7006         }
7007         return PAGE_READ;
7008     default:
7009         g_assert_not_reached();
7010     }
7011 }
7012
7013 /* Translate section/page access permissions to page
7014  * R/W protection flags.
7015  *
7016  * @ap:      The 2-bit simple AP (AP[2:1])
7017  * @is_user: TRUE if accessing from PL0
7018  */
7019 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
7020 {
7021     switch (ap) {
7022     case 0:
7023         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
7024     case 1:
7025         return PAGE_READ | PAGE_WRITE;
7026     case 2:
7027         return is_user ? 0 : PAGE_READ;
7028     case 3:
7029         return PAGE_READ;
7030     default:
7031         g_assert_not_reached();
7032     }
7033 }
7034
7035 static inline int
7036 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
7037 {
7038     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
7039 }
7040
7041 /* Translate S2 section/page access permissions to protection flags
7042  *
7043  * @env:     CPUARMState
7044  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
7045  * @xn:      XN (execute-never) bit
7046  */
7047 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
7048 {
7049     int prot = 0;
7050
7051     if (s2ap & 1) {
7052         prot |= PAGE_READ;
7053     }
7054     if (s2ap & 2) {
7055         prot |= PAGE_WRITE;
7056     }
7057     if (!xn) {
7058         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
7059             prot |= PAGE_EXEC;
7060         }
7061     }
7062     return prot;
7063 }
7064
7065 /* Translate section/page access permissions to protection flags
7066  *
7067  * @env:     CPUARMState
7068  * @mmu_idx: MMU index indicating required translation regime
7069  * @is_aa64: TRUE if AArch64
7070  * @ap:      The 2-bit simple AP (AP[2:1])
7071  * @ns:      NS (non-secure) bit
7072  * @xn:      XN (execute-never) bit
7073  * @pxn:     PXN (privileged execute-never) bit
7074  */
7075 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
7076                       int ap, int ns, int xn, int pxn)
7077 {
7078     bool is_user = regime_is_user(env, mmu_idx);
7079     int prot_rw, user_rw;
7080     bool have_wxn;
7081     int wxn = 0;
7082
7083     assert(mmu_idx != ARMMMUIdx_S2NS);
7084
7085     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
7086     if (is_user) {
7087         prot_rw = user_rw;
7088     } else {
7089         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
7090     }
7091
7092     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
7093         return prot_rw;
7094     }
7095
7096     /* TODO have_wxn should be replaced with
7097      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
7098      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
7099      * compatible processors have EL2, which is required for [U]WXN.
7100      */
7101     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
7102
7103     if (have_wxn) {
7104         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
7105     }
7106
7107     if (is_aa64) {
7108         switch (regime_el(env, mmu_idx)) {
7109         case 1:
7110             if (!is_user) {
7111                 xn = pxn || (user_rw & PAGE_WRITE);
7112             }
7113             break;
7114         case 2:
7115         case 3:
7116             break;
7117         }
7118     } else if (arm_feature(env, ARM_FEATURE_V7)) {
7119         switch (regime_el(env, mmu_idx)) {
7120         case 1:
7121         case 3:
7122             if (is_user) {
7123                 xn = xn || !(user_rw & PAGE_READ);
7124             } else {
7125                 int uwxn = 0;
7126                 if (have_wxn) {
7127                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
7128                 }
7129                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
7130                      (uwxn && (user_rw & PAGE_WRITE));
7131             }
7132             break;
7133         case 2:
7134             break;
7135         }
7136     } else {
7137         xn = wxn = 0;
7138     }
7139
7140     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
7141         return prot_rw;
7142     }
7143     return prot_rw | PAGE_EXEC;
7144 }
7145
7146 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
7147                                      uint32_t *table, uint32_t address)
7148 {
7149     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
7150     TCR *tcr = regime_tcr(env, mmu_idx);
7151
7152     if (address & tcr->mask) {
7153         if (tcr->raw_tcr & TTBCR_PD1) {
7154             /* Translation table walk disabled for TTBR1 */
7155             return false;
7156         }
7157         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
7158     } else {
7159         if (tcr->raw_tcr & TTBCR_PD0) {
7160             /* Translation table walk disabled for TTBR0 */
7161             return false;
7162         }
7163         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
7164     }
7165     *table |= (address >> 18) & 0x3ffc;
7166     return true;
7167 }
7168
7169 /* Translate a S1 pagetable walk through S2 if needed.  */
7170 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
7171                                hwaddr addr, MemTxAttrs txattrs,
7172                                uint32_t *fsr,
7173                                ARMMMUFaultInfo *fi)
7174 {
7175     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
7176         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
7177         target_ulong s2size;
7178         hwaddr s2pa;
7179         int s2prot;
7180         int ret;
7181
7182         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
7183                                  &txattrs, &s2prot, &s2size, fsr, fi);
7184         if (ret) {
7185             fi->s2addr = addr;
7186             fi->stage2 = true;
7187             fi->s1ptw = true;
7188             return ~0;
7189         }
7190         addr = s2pa;
7191     }
7192     return addr;
7193 }
7194
7195 /* All loads done in the course of a page table walk go through here.
7196  * TODO: rather than ignoring errors from physical memory reads (which
7197  * are external aborts in ARM terminology) we should propagate this
7198  * error out so that we can turn it into a Data Abort if this walk
7199  * was being done for a CPU load/store or an address translation instruction
7200  * (but not if it was for a debug access).
7201  */
7202 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
7203                             ARMMMUIdx mmu_idx, uint32_t *fsr,
7204                             ARMMMUFaultInfo *fi)
7205 {
7206     ARMCPU *cpu = ARM_CPU(cs);
7207     CPUARMState *env = &cpu->env;
7208     MemTxAttrs attrs = {};
7209     AddressSpace *as;
7210
7211     attrs.secure = is_secure;
7212     as = arm_addressspace(cs, attrs);
7213     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fsr, fi);
7214     if (fi->s1ptw) {
7215         return 0;
7216     }
7217     if (regime_translation_big_endian(env, mmu_idx)) {
7218         return address_space_ldl_be(as, addr, attrs, NULL);
7219     } else {
7220         return address_space_ldl_le(as, addr, attrs, NULL);
7221     }
7222 }
7223
7224 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
7225                             ARMMMUIdx mmu_idx, uint32_t *fsr,
7226                             ARMMMUFaultInfo *fi)
7227 {
7228     ARMCPU *cpu = ARM_CPU(cs);
7229     CPUARMState *env = &cpu->env;
7230     MemTxAttrs attrs = {};
7231     AddressSpace *as;
7232
7233     attrs.secure = is_secure;
7234     as = arm_addressspace(cs, attrs);
7235     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fsr, fi);
7236     if (fi->s1ptw) {
7237         return 0;
7238     }
7239     if (regime_translation_big_endian(env, mmu_idx)) {
7240         return address_space_ldq_be(as, addr, attrs, NULL);
7241     } else {
7242         return address_space_ldq_le(as, addr, attrs, NULL);
7243     }
7244 }
7245
7246 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
7247                              int access_type, ARMMMUIdx mmu_idx,
7248                              hwaddr *phys_ptr, int *prot,
7249                              target_ulong *page_size, uint32_t *fsr,
7250                              ARMMMUFaultInfo *fi)
7251 {
7252     CPUState *cs = CPU(arm_env_get_cpu(env));
7253     int code;
7254     uint32_t table;
7255     uint32_t desc;
7256     int type;
7257     int ap;
7258     int domain = 0;
7259     int domain_prot;
7260     hwaddr phys_addr;
7261     uint32_t dacr;
7262
7263     /* Pagetable walk.  */
7264     /* Lookup l1 descriptor.  */
7265     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
7266         /* Section translation fault if page walk is disabled by PD0 or PD1 */
7267         code = 5;
7268         goto do_fault;
7269     }
7270     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
7271                        mmu_idx, fsr, fi);
7272     type = (desc & 3);
7273     domain = (desc >> 5) & 0x0f;
7274     if (regime_el(env, mmu_idx) == 1) {
7275         dacr = env->cp15.dacr_ns;
7276     } else {
7277         dacr = env->cp15.dacr_s;
7278     }
7279     domain_prot = (dacr >> (domain * 2)) & 3;
7280     if (type == 0) {
7281         /* Section translation fault.  */
7282         code = 5;
7283         goto do_fault;
7284     }
7285     if (domain_prot == 0 || domain_prot == 2) {
7286         if (type == 2)
7287             code = 9; /* Section domain fault.  */
7288         else
7289             code = 11; /* Page domain fault.  */
7290         goto do_fault;
7291     }
7292     if (type == 2) {
7293         /* 1Mb section.  */
7294         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
7295         ap = (desc >> 10) & 3;
7296         code = 13;
7297         *page_size = 1024 * 1024;
7298     } else {
7299         /* Lookup l2 entry.  */
7300         if (type == 1) {
7301             /* Coarse pagetable.  */
7302             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
7303         } else {
7304             /* Fine pagetable.  */
7305             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
7306         }
7307         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
7308                            mmu_idx, fsr, fi);
7309         switch (desc & 3) {
7310         case 0: /* Page translation fault.  */
7311             code = 7;
7312             goto do_fault;
7313         case 1: /* 64k page.  */
7314             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
7315             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
7316             *page_size = 0x10000;
7317             break;
7318         case 2: /* 4k page.  */
7319             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
7320             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
7321             *page_size = 0x1000;
7322             break;
7323         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
7324             if (type == 1) {
7325                 /* ARMv6/XScale extended small page format */
7326                 if (arm_feature(env, ARM_FEATURE_XSCALE)
7327                     || arm_feature(env, ARM_FEATURE_V6)) {
7328                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
7329                     *page_size = 0x1000;
7330                 } else {
7331                     /* UNPREDICTABLE in ARMv5; we choose to take a
7332                      * page translation fault.
7333                      */
7334                     code = 7;
7335                     goto do_fault;
7336                 }
7337             } else {
7338                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
7339                 *page_size = 0x400;
7340             }
7341             ap = (desc >> 4) & 3;
7342             break;
7343         default:
7344             /* Never happens, but compiler isn't smart enough to tell.  */
7345             abort();
7346         }
7347         code = 15;
7348     }
7349     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
7350     *prot |= *prot ? PAGE_EXEC : 0;
7351     if (!(*prot & (1 << access_type))) {
7352         /* Access permission fault.  */
7353         goto do_fault;
7354     }
7355     *phys_ptr = phys_addr;
7356     return false;
7357 do_fault:
7358     *fsr = code | (domain << 4);
7359     return true;
7360 }
7361
7362 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
7363                              int access_type, ARMMMUIdx mmu_idx,
7364                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
7365                              target_ulong *page_size, uint32_t *fsr,
7366                              ARMMMUFaultInfo *fi)
7367 {
7368     CPUState *cs = CPU(arm_env_get_cpu(env));
7369     int code;
7370     uint32_t table;
7371     uint32_t desc;
7372     uint32_t xn;
7373     uint32_t pxn = 0;
7374     int type;
7375     int ap;
7376     int domain = 0;
7377     int domain_prot;
7378     hwaddr phys_addr;
7379     uint32_t dacr;
7380     bool ns;
7381
7382     /* Pagetable walk.  */
7383     /* Lookup l1 descriptor.  */
7384     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
7385         /* Section translation fault if page walk is disabled by PD0 or PD1 */
7386         code = 5;
7387         goto do_fault;
7388     }
7389     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
7390                        mmu_idx, fsr, fi);
7391     type = (desc & 3);
7392     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
7393         /* Section translation fault, or attempt to use the encoding
7394          * which is Reserved on implementations without PXN.
7395          */
7396         code = 5;
7397         goto do_fault;
7398     }
7399     if ((type == 1) || !(desc & (1 << 18))) {
7400         /* Page or Section.  */
7401         domain = (desc >> 5) & 0x0f;
7402     }
7403     if (regime_el(env, mmu_idx) == 1) {
7404         dacr = env->cp15.dacr_ns;
7405     } else {
7406         dacr = env->cp15.dacr_s;
7407     }
7408     domain_prot = (dacr >> (domain * 2)) & 3;
7409     if (domain_prot == 0 || domain_prot == 2) {
7410         if (type != 1) {
7411             code = 9; /* Section domain fault.  */
7412         } else {
7413             code = 11; /* Page domain fault.  */
7414         }
7415         goto do_fault;
7416     }
7417     if (type != 1) {
7418         if (desc & (1 << 18)) {
7419             /* Supersection.  */
7420             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
7421             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
7422             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
7423             *page_size = 0x1000000;
7424         } else {
7425             /* Section.  */
7426             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
7427             *page_size = 0x100000;
7428         }
7429         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
7430         xn = desc & (1 << 4);
7431         pxn = desc & 1;
7432         code = 13;
7433         ns = extract32(desc, 19, 1);
7434     } else {
7435         if (arm_feature(env, ARM_FEATURE_PXN)) {
7436             pxn = (desc >> 2) & 1;
7437         }
7438         ns = extract32(desc, 3, 1);
7439         /* Lookup l2 entry.  */
7440         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
7441         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
7442                            mmu_idx, fsr, fi);
7443         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
7444         switch (desc & 3) {
7445         case 0: /* Page translation fault.  */
7446             code = 7;
7447             goto do_fault;
7448         case 1: /* 64k page.  */
7449             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
7450             xn = desc & (1 << 15);
7451             *page_size = 0x10000;
7452             break;
7453         case 2: case 3: /* 4k page.  */
7454             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
7455             xn = desc & 1;
7456             *page_size = 0x1000;
7457             break;
7458         default:
7459             /* Never happens, but compiler isn't smart enough to tell.  */
7460             abort();
7461         }
7462         code = 15;
7463     }
7464     if (domain_prot == 3) {
7465         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
7466     } else {
7467         if (pxn && !regime_is_user(env, mmu_idx)) {
7468             xn = 1;
7469         }
7470         if (xn && access_type == 2)
7471             goto do_fault;
7472
7473         if (arm_feature(env, ARM_FEATURE_V6K) &&
7474                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
7475             /* The simplified model uses AP[0] as an access control bit.  */
7476             if ((ap & 1) == 0) {
7477                 /* Access flag fault.  */
7478                 code = (code == 15) ? 6 : 3;
7479                 goto do_fault;
7480             }
7481             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
7482         } else {
7483             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
7484         }
7485         if (*prot && !xn) {
7486             *prot |= PAGE_EXEC;
7487         }
7488         if (!(*prot & (1 << access_type))) {
7489             /* Access permission fault.  */
7490             goto do_fault;
7491         }
7492     }
7493     if (ns) {
7494         /* The NS bit will (as required by the architecture) have no effect if
7495          * the CPU doesn't support TZ or this is a non-secure translation
7496          * regime, because the attribute will already be non-secure.
7497          */
7498         attrs->secure = false;
7499     }
7500     *phys_ptr = phys_addr;
7501     return false;
7502 do_fault:
7503     *fsr = code | (domain << 4);
7504     return true;
7505 }
7506
7507 /* Fault type for long-descriptor MMU fault reporting; this corresponds
7508  * to bits [5..2] in the STATUS field in long-format DFSR/IFSR.
7509  */
7510 typedef enum {
7511     translation_fault = 1,
7512     access_fault = 2,
7513     permission_fault = 3,
7514 } MMUFaultType;
7515
7516 /*
7517  * check_s2_mmu_setup
7518  * @cpu:        ARMCPU
7519  * @is_aa64:    True if the translation regime is in AArch64 state
7520  * @startlevel: Suggested starting level
7521  * @inputsize:  Bitsize of IPAs
7522  * @stride:     Page-table stride (See the ARM ARM)
7523  *
7524  * Returns true if the suggested S2 translation parameters are OK and
7525  * false otherwise.
7526  */
7527 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
7528                                int inputsize, int stride)
7529 {
7530     const int grainsize = stride + 3;
7531     int startsizecheck;
7532
7533     /* Negative levels are never allowed.  */
7534     if (level < 0) {
7535         return false;
7536     }
7537
7538     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
7539     if (startsizecheck < 1 || startsizecheck > stride + 4) {
7540         return false;
7541     }
7542
7543     if (is_aa64) {
7544         CPUARMState *env = &cpu->env;
7545         unsigned int pamax = arm_pamax(cpu);
7546
7547         switch (stride) {
7548         case 13: /* 64KB Pages.  */
7549             if (level == 0 || (level == 1 && pamax <= 42)) {
7550                 return false;
7551             }
7552             break;
7553         case 11: /* 16KB Pages.  */
7554             if (level == 0 || (level == 1 && pamax <= 40)) {
7555                 return false;
7556             }
7557             break;
7558         case 9: /* 4KB Pages.  */
7559             if (level == 0 && pamax <= 42) {
7560                 return false;
7561             }
7562             break;
7563         default:
7564             g_assert_not_reached();
7565         }
7566
7567         /* Inputsize checks.  */
7568         if (inputsize > pamax &&
7569             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
7570             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
7571             return false;
7572         }
7573     } else {
7574         /* AArch32 only supports 4KB pages. Assert on that.  */
7575         assert(stride == 9);
7576
7577         if (level == 0) {
7578             return false;
7579         }
7580     }
7581     return true;
7582 }
7583
7584 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
7585                                int access_type, ARMMMUIdx mmu_idx,
7586                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
7587                                target_ulong *page_size_ptr, uint32_t *fsr,
7588                                ARMMMUFaultInfo *fi)
7589 {
7590     ARMCPU *cpu = arm_env_get_cpu(env);
7591     CPUState *cs = CPU(cpu);
7592     /* Read an LPAE long-descriptor translation table. */
7593     MMUFaultType fault_type = translation_fault;
7594     uint32_t level;
7595     uint32_t epd = 0;
7596     int32_t t0sz, t1sz;
7597     uint32_t tg;
7598     uint64_t ttbr;
7599     int ttbr_select;
7600     hwaddr descaddr, indexmask, indexmask_grainsize;
7601     uint32_t tableattrs;
7602     target_ulong page_size;
7603     uint32_t attrs;
7604     int32_t stride = 9;
7605     int32_t addrsize;
7606     int inputsize;
7607     int32_t tbi = 0;
7608     TCR *tcr = regime_tcr(env, mmu_idx);
7609     int ap, ns, xn, pxn;
7610     uint32_t el = regime_el(env, mmu_idx);
7611     bool ttbr1_valid = true;
7612     uint64_t descaddrmask;
7613     bool aarch64 = arm_el_is_aa64(env, el);
7614
7615     /* TODO:
7616      * This code does not handle the different format TCR for VTCR_EL2.
7617      * This code also does not support shareability levels.
7618      * Attribute and permission bit handling should also be checked when adding
7619      * support for those page table walks.
7620      */
7621     if (aarch64) {
7622         level = 0;
7623         addrsize = 64;
7624         if (el > 1) {
7625             if (mmu_idx != ARMMMUIdx_S2NS) {
7626                 tbi = extract64(tcr->raw_tcr, 20, 1);
7627             }
7628         } else {
7629             if (extract64(address, 55, 1)) {
7630                 tbi = extract64(tcr->raw_tcr, 38, 1);
7631             } else {
7632                 tbi = extract64(tcr->raw_tcr, 37, 1);
7633             }
7634         }
7635         tbi *= 8;
7636
7637         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
7638          * invalid.
7639          */
7640         if (el > 1) {
7641             ttbr1_valid = false;
7642         }
7643     } else {
7644         level = 1;
7645         addrsize = 32;
7646         /* There is no TTBR1 for EL2 */
7647         if (el == 2) {
7648             ttbr1_valid = false;
7649         }
7650     }
7651
7652     /* Determine whether this address is in the region controlled by
7653      * TTBR0 or TTBR1 (or if it is in neither region and should fault).
7654      * This is a Non-secure PL0/1 stage 1 translation, so controlled by
7655      * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:
7656      */
7657     if (aarch64) {
7658         /* AArch64 translation.  */
7659         t0sz = extract32(tcr->raw_tcr, 0, 6);
7660         t0sz = MIN(t0sz, 39);
7661         t0sz = MAX(t0sz, 16);
7662     } else if (mmu_idx != ARMMMUIdx_S2NS) {
7663         /* AArch32 stage 1 translation.  */
7664         t0sz = extract32(tcr->raw_tcr, 0, 3);
7665     } else {
7666         /* AArch32 stage 2 translation.  */
7667         bool sext = extract32(tcr->raw_tcr, 4, 1);
7668         bool sign = extract32(tcr->raw_tcr, 3, 1);
7669         /* Address size is 40-bit for a stage 2 translation,
7670          * and t0sz can be negative (from -8 to 7),
7671          * so we need to adjust it to use the TTBR selecting logic below.
7672          */
7673         addrsize = 40;
7674         t0sz = sextract32(tcr->raw_tcr, 0, 4) + 8;
7675
7676         /* If the sign-extend bit is not the same as t0sz[3], the result
7677          * is unpredictable. Flag this as a guest error.  */
7678         if (sign != sext) {
7679             qemu_log_mask(LOG_GUEST_ERROR,
7680                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
7681         }
7682     }
7683     t1sz = extract32(tcr->raw_tcr, 16, 6);
7684     if (aarch64) {
7685         t1sz = MIN(t1sz, 39);
7686         t1sz = MAX(t1sz, 16);
7687     }
7688     if (t0sz && !extract64(address, addrsize - t0sz, t0sz - tbi)) {
7689         /* there is a ttbr0 region and we are in it (high bits all zero) */
7690         ttbr_select = 0;
7691     } else if (ttbr1_valid && t1sz &&
7692                !extract64(~address, addrsize - t1sz, t1sz - tbi)) {
7693         /* there is a ttbr1 region and we are in it (high bits all one) */
7694         ttbr_select = 1;
7695     } else if (!t0sz) {
7696         /* ttbr0 region is "everything not in the ttbr1 region" */
7697         ttbr_select = 0;
7698     } else if (!t1sz && ttbr1_valid) {
7699         /* ttbr1 region is "everything not in the ttbr0 region" */
7700         ttbr_select = 1;
7701     } else {
7702         /* in the gap between the two regions, this is a Translation fault */
7703         fault_type = translation_fault;
7704         goto do_fault;
7705     }
7706
7707     /* Note that QEMU ignores shareability and cacheability attributes,
7708      * so we don't need to do anything with the SH, ORGN, IRGN fields
7709      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
7710      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
7711      * implement any ASID-like capability so we can ignore it (instead
7712      * we will always flush the TLB any time the ASID is changed).
7713      */
7714     if (ttbr_select == 0) {
7715         ttbr = regime_ttbr(env, mmu_idx, 0);
7716         if (el < 2) {
7717             epd = extract32(tcr->raw_tcr, 7, 1);
7718         }
7719         inputsize = addrsize - t0sz;
7720
7721         tg = extract32(tcr->raw_tcr, 14, 2);
7722         if (tg == 1) { /* 64KB pages */
7723             stride = 13;
7724         }
7725         if (tg == 2) { /* 16KB pages */
7726             stride = 11;
7727         }
7728     } else {
7729         /* We should only be here if TTBR1 is valid */
7730         assert(ttbr1_valid);
7731
7732         ttbr = regime_ttbr(env, mmu_idx, 1);
7733         epd = extract32(tcr->raw_tcr, 23, 1);
7734         inputsize = addrsize - t1sz;
7735
7736         tg = extract32(tcr->raw_tcr, 30, 2);
7737         if (tg == 3)  { /* 64KB pages */
7738             stride = 13;
7739         }
7740         if (tg == 1) { /* 16KB pages */
7741             stride = 11;
7742         }
7743     }
7744
7745     /* Here we should have set up all the parameters for the translation:
7746      * inputsize, ttbr, epd, stride, tbi
7747      */
7748
7749     if (epd) {
7750         /* Translation table walk disabled => Translation fault on TLB miss
7751          * Note: This is always 0 on 64-bit EL2 and EL3.
7752          */
7753         goto do_fault;
7754     }
7755
7756     if (mmu_idx != ARMMMUIdx_S2NS) {
7757         /* The starting level depends on the virtual address size (which can
7758          * be up to 48 bits) and the translation granule size. It indicates
7759          * the number of strides (stride bits at a time) needed to
7760          * consume the bits of the input address. In the pseudocode this is:
7761          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
7762          * where their 'inputsize' is our 'inputsize', 'grainsize' is
7763          * our 'stride + 3' and 'stride' is our 'stride'.
7764          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
7765          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
7766          * = 4 - (inputsize - 4) / stride;
7767          */
7768         level = 4 - (inputsize - 4) / stride;
7769     } else {
7770         /* For stage 2 translations the starting level is specified by the
7771          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
7772          */
7773         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
7774         uint32_t startlevel;
7775         bool ok;
7776
7777         if (!aarch64 || stride == 9) {
7778             /* AArch32 or 4KB pages */
7779             startlevel = 2 - sl0;
7780         } else {
7781             /* 16KB or 64KB pages */
7782             startlevel = 3 - sl0;
7783         }
7784
7785         /* Check that the starting level is valid. */
7786         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
7787                                 inputsize, stride);
7788         if (!ok) {
7789             fault_type = translation_fault;
7790             goto do_fault;
7791         }
7792         level = startlevel;
7793     }
7794
7795     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
7796     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
7797
7798     /* Now we can extract the actual base address from the TTBR */
7799     descaddr = extract64(ttbr, 0, 48);
7800     descaddr &= ~indexmask;
7801
7802     /* The address field in the descriptor goes up to bit 39 for ARMv7
7803      * but up to bit 47 for ARMv8, but we use the descaddrmask
7804      * up to bit 39 for AArch32, because we don't need other bits in that case
7805      * to construct next descriptor address (anyway they should be all zeroes).
7806      */
7807     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
7808                    ~indexmask_grainsize;
7809
7810     /* Secure accesses start with the page table in secure memory and
7811      * can be downgraded to non-secure at any step. Non-secure accesses
7812      * remain non-secure. We implement this by just ORing in the NSTable/NS
7813      * bits at each step.
7814      */
7815     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
7816     for (;;) {
7817         uint64_t descriptor;
7818         bool nstable;
7819
7820         descaddr |= (address >> (stride * (4 - level))) & indexmask;
7821         descaddr &= ~7ULL;
7822         nstable = extract32(tableattrs, 4, 1);
7823         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fsr, fi);
7824         if (fi->s1ptw) {
7825             goto do_fault;
7826         }
7827
7828         if (!(descriptor & 1) ||
7829             (!(descriptor & 2) && (level == 3))) {
7830             /* Invalid, or the Reserved level 3 encoding */
7831             goto do_fault;
7832         }
7833         descaddr = descriptor & descaddrmask;
7834
7835         if ((descriptor & 2) && (level < 3)) {
7836             /* Table entry. The top five bits are attributes which  may
7837              * propagate down through lower levels of the table (and
7838              * which are all arranged so that 0 means "no effect", so
7839              * we can gather them up by ORing in the bits at each level).
7840              */
7841             tableattrs |= extract64(descriptor, 59, 5);
7842             level++;
7843             indexmask = indexmask_grainsize;
7844             continue;
7845         }
7846         /* Block entry at level 1 or 2, or page entry at level 3.
7847          * These are basically the same thing, although the number
7848          * of bits we pull in from the vaddr varies.
7849          */
7850         page_size = (1ULL << ((stride * (4 - level)) + 3));
7851         descaddr |= (address & (page_size - 1));
7852         /* Extract attributes from the descriptor */
7853         attrs = extract64(descriptor, 2, 10)
7854             | (extract64(descriptor, 52, 12) << 10);
7855
7856         if (mmu_idx == ARMMMUIdx_S2NS) {
7857             /* Stage 2 table descriptors do not include any attribute fields */
7858             break;
7859         }
7860         /* Merge in attributes from table descriptors */
7861         attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */
7862         attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */
7863         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
7864          * means "force PL1 access only", which means forcing AP[1] to 0.
7865          */
7866         if (extract32(tableattrs, 2, 1)) {
7867             attrs &= ~(1 << 4);
7868         }
7869         attrs |= nstable << 3; /* NS */
7870         break;
7871     }
7872     /* Here descaddr is the final physical address, and attributes
7873      * are all in attrs.
7874      */
7875     fault_type = access_fault;
7876     if ((attrs & (1 << 8)) == 0) {
7877         /* Access flag */
7878         goto do_fault;
7879     }
7880
7881     ap = extract32(attrs, 4, 2);
7882     xn = extract32(attrs, 12, 1);
7883
7884     if (mmu_idx == ARMMMUIdx_S2NS) {
7885         ns = true;
7886         *prot = get_S2prot(env, ap, xn);
7887     } else {
7888         ns = extract32(attrs, 3, 1);
7889         pxn = extract32(attrs, 11, 1);
7890         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
7891     }
7892
7893     fault_type = permission_fault;
7894     if (!(*prot & (1 << access_type))) {
7895         goto do_fault;
7896     }
7897
7898     if (ns) {
7899         /* The NS bit will (as required by the architecture) have no effect if
7900          * the CPU doesn't support TZ or this is a non-secure translation
7901          * regime, because the attribute will already be non-secure.
7902          */
7903         txattrs->secure = false;
7904     }
7905     *phys_ptr = descaddr;
7906     *page_size_ptr = page_size;
7907     return false;
7908
7909 do_fault:
7910     /* Long-descriptor format IFSR/DFSR value */
7911     *fsr = (1 << 9) | (fault_type << 2) | level;
7912     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
7913     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
7914     return true;
7915 }
7916
7917 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
7918                                                 ARMMMUIdx mmu_idx,
7919                                                 int32_t address, int *prot)
7920 {
7921     *prot = PAGE_READ | PAGE_WRITE;
7922     switch (address) {
7923     case 0xF0000000 ... 0xFFFFFFFF:
7924         if (regime_sctlr(env, mmu_idx) & SCTLR_V) { /* hivecs execing is ok */
7925             *prot |= PAGE_EXEC;
7926         }
7927         break;
7928     case 0x00000000 ... 0x7FFFFFFF:
7929         *prot |= PAGE_EXEC;
7930         break;
7931     }
7932
7933 }
7934
7935 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
7936                                  int access_type, ARMMMUIdx mmu_idx,
7937                                  hwaddr *phys_ptr, int *prot, uint32_t *fsr)
7938 {
7939     ARMCPU *cpu = arm_env_get_cpu(env);
7940     int n;
7941     bool is_user = regime_is_user(env, mmu_idx);
7942
7943     *phys_ptr = address;
7944     *prot = 0;
7945
7946     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
7947         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
7948     } else { /* MPU enabled */
7949         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
7950             /* region search */
7951             uint32_t base = env->pmsav7.drbar[n];
7952             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
7953             uint32_t rmask;
7954             bool srdis = false;
7955
7956             if (!(env->pmsav7.drsr[n] & 0x1)) {
7957                 continue;
7958             }
7959
7960             if (!rsize) {
7961                 qemu_log_mask(LOG_GUEST_ERROR, "DRSR.Rsize field can not be 0");
7962                 continue;
7963             }
7964             rsize++;
7965             rmask = (1ull << rsize) - 1;
7966
7967             if (base & rmask) {
7968                 qemu_log_mask(LOG_GUEST_ERROR, "DRBAR %" PRIx32 " misaligned "
7969                               "to DRSR region size, mask = %" PRIx32,
7970                               base, rmask);
7971                 continue;
7972             }
7973
7974             if (address < base || address > base + rmask) {
7975                 continue;
7976             }
7977
7978             /* Region matched */
7979
7980             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
7981                 int i, snd;
7982                 uint32_t srdis_mask;
7983
7984                 rsize -= 3; /* sub region size (power of 2) */
7985                 snd = ((address - base) >> rsize) & 0x7;
7986                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
7987
7988                 srdis_mask = srdis ? 0x3 : 0x0;
7989                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
7990                     /* This will check in groups of 2, 4 and then 8, whether
7991                      * the subregion bits are consistent. rsize is incremented
7992                      * back up to give the region size, considering consistent
7993                      * adjacent subregions as one region. Stop testing if rsize
7994                      * is already big enough for an entire QEMU page.
7995                      */
7996                     int snd_rounded = snd & ~(i - 1);
7997                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
7998                                                      snd_rounded + 8, i);
7999                     if (srdis_mask ^ srdis_multi) {
8000                         break;
8001                     }
8002                     srdis_mask = (srdis_mask << i) | srdis_mask;
8003                     rsize++;
8004                 }
8005             }
8006             if (rsize < TARGET_PAGE_BITS) {
8007                 qemu_log_mask(LOG_UNIMP, "No support for MPU (sub)region"
8008                               "alignment of %" PRIu32 " bits. Minimum is %d\n",
8009                               rsize, TARGET_PAGE_BITS);
8010                 continue;
8011             }
8012             if (srdis) {
8013                 continue;
8014             }
8015             break;
8016         }
8017
8018         if (n == -1) { /* no hits */
8019             if (cpu->pmsav7_dregion &&
8020                 (is_user || !(regime_sctlr(env, mmu_idx) & SCTLR_BR))) {
8021                 /* background fault */
8022                 *fsr = 0;
8023                 return true;
8024             }
8025             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
8026         } else { /* a MPU hit! */
8027             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
8028
8029             if (is_user) { /* User mode AP bit decoding */
8030                 switch (ap) {
8031                 case 0:
8032                 case 1:
8033                 case 5:
8034                     break; /* no access */
8035                 case 3:
8036                     *prot |= PAGE_WRITE;
8037                     /* fall through */
8038                 case 2:
8039                 case 6:
8040                     *prot |= PAGE_READ | PAGE_EXEC;
8041                     break;
8042                 default:
8043                     qemu_log_mask(LOG_GUEST_ERROR,
8044                                   "Bad value for AP bits in DRACR %"
8045                                   PRIx32 "\n", ap);
8046                 }
8047             } else { /* Priv. mode AP bits decoding */
8048                 switch (ap) {
8049                 case 0:
8050                     break; /* no access */
8051                 case 1:
8052                 case 2:
8053                 case 3:
8054                     *prot |= PAGE_WRITE;
8055                     /* fall through */
8056                 case 5:
8057                 case 6:
8058                     *prot |= PAGE_READ | PAGE_EXEC;
8059                     break;
8060                 default:
8061                     qemu_log_mask(LOG_GUEST_ERROR,
8062                                   "Bad value for AP bits in DRACR %"
8063                                   PRIx32 "\n", ap);
8064                 }
8065             }
8066
8067             /* execute never */
8068             if (env->pmsav7.dracr[n] & (1 << 12)) {
8069                 *prot &= ~PAGE_EXEC;
8070             }
8071         }
8072     }
8073
8074     *fsr = 0x00d; /* Permission fault */
8075     return !(*prot & (1 << access_type));
8076 }
8077
8078 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
8079                                  int access_type, ARMMMUIdx mmu_idx,
8080                                  hwaddr *phys_ptr, int *prot, uint32_t *fsr)
8081 {
8082     int n;
8083     uint32_t mask;
8084     uint32_t base;
8085     bool is_user = regime_is_user(env, mmu_idx);
8086
8087     *phys_ptr = address;
8088     for (n = 7; n >= 0; n--) {
8089         base = env->cp15.c6_region[n];
8090         if ((base & 1) == 0) {
8091             continue;
8092         }
8093         mask = 1 << ((base >> 1) & 0x1f);
8094         /* Keep this shift separate from the above to avoid an
8095            (undefined) << 32.  */
8096         mask = (mask << 1) - 1;
8097         if (((base ^ address) & ~mask) == 0) {
8098             break;
8099         }
8100     }
8101     if (n < 0) {
8102         *fsr = 2;
8103         return true;
8104     }
8105
8106     if (access_type == 2) {
8107         mask = env->cp15.pmsav5_insn_ap;
8108     } else {
8109         mask = env->cp15.pmsav5_data_ap;
8110     }
8111     mask = (mask >> (n * 4)) & 0xf;
8112     switch (mask) {
8113     case 0:
8114         *fsr = 1;
8115         return true;
8116     case 1:
8117         if (is_user) {
8118             *fsr = 1;
8119             return true;
8120         }
8121         *prot = PAGE_READ | PAGE_WRITE;
8122         break;
8123     case 2:
8124         *prot = PAGE_READ;
8125         if (!is_user) {
8126             *prot |= PAGE_WRITE;
8127         }
8128         break;
8129     case 3:
8130         *prot = PAGE_READ | PAGE_WRITE;
8131         break;
8132     case 5:
8133         if (is_user) {
8134             *fsr = 1;
8135             return true;
8136         }
8137         *prot = PAGE_READ;
8138         break;
8139     case 6:
8140         *prot = PAGE_READ;
8141         break;
8142     default:
8143         /* Bad permission.  */
8144         *fsr = 1;
8145         return true;
8146     }
8147     *prot |= PAGE_EXEC;
8148     return false;
8149 }
8150
8151 /* get_phys_addr - get the physical address for this virtual address
8152  *
8153  * Find the physical address corresponding to the given virtual address,
8154  * by doing a translation table walk on MMU based systems or using the
8155  * MPU state on MPU based systems.
8156  *
8157  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
8158  * prot and page_size may not be filled in, and the populated fsr value provides
8159  * information on why the translation aborted, in the format of a
8160  * DFSR/IFSR fault register, with the following caveats:
8161  *  * we honour the short vs long DFSR format differences.
8162  *  * the WnR bit is never set (the caller must do this).
8163  *  * for PSMAv5 based systems we don't bother to return a full FSR format
8164  *    value.
8165  *
8166  * @env: CPUARMState
8167  * @address: virtual address to get physical address for
8168  * @access_type: 0 for read, 1 for write, 2 for execute
8169  * @mmu_idx: MMU index indicating required translation regime
8170  * @phys_ptr: set to the physical address corresponding to the virtual address
8171  * @attrs: set to the memory transaction attributes to use
8172  * @prot: set to the permissions for the page containing phys_ptr
8173  * @page_size: set to the size of the page containing phys_ptr
8174  * @fsr: set to the DFSR/IFSR value on failure
8175  */
8176 static bool get_phys_addr(CPUARMState *env, target_ulong address,
8177                           int access_type, ARMMMUIdx mmu_idx,
8178                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
8179                           target_ulong *page_size, uint32_t *fsr,
8180                           ARMMMUFaultInfo *fi)
8181 {
8182     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
8183         /* Call ourselves recursively to do the stage 1 and then stage 2
8184          * translations.
8185          */
8186         if (arm_feature(env, ARM_FEATURE_EL2)) {
8187             hwaddr ipa;
8188             int s2_prot;
8189             int ret;
8190
8191             ret = get_phys_addr(env, address, access_type,
8192                                 mmu_idx + ARMMMUIdx_S1NSE0, &ipa, attrs,
8193                                 prot, page_size, fsr, fi);
8194
8195             /* If S1 fails or S2 is disabled, return early.  */
8196             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
8197                 *phys_ptr = ipa;
8198                 return ret;
8199             }
8200
8201             /* S1 is done. Now do S2 translation.  */
8202             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
8203                                      phys_ptr, attrs, &s2_prot,
8204                                      page_size, fsr, fi);
8205             fi->s2addr = ipa;
8206             /* Combine the S1 and S2 perms.  */
8207             *prot &= s2_prot;
8208             return ret;
8209         } else {
8210             /*
8211              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
8212              */
8213             mmu_idx += ARMMMUIdx_S1NSE0;
8214         }
8215     }
8216
8217     /* The page table entries may downgrade secure to non-secure, but
8218      * cannot upgrade an non-secure translation regime's attributes
8219      * to secure.
8220      */
8221     attrs->secure = regime_is_secure(env, mmu_idx);
8222     attrs->user = regime_is_user(env, mmu_idx);
8223
8224     /* Fast Context Switch Extension. This doesn't exist at all in v8.
8225      * In v7 and earlier it affects all stage 1 translations.
8226      */
8227     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
8228         && !arm_feature(env, ARM_FEATURE_V8)) {
8229         if (regime_el(env, mmu_idx) == 3) {
8230             address += env->cp15.fcseidr_s;
8231         } else {
8232             address += env->cp15.fcseidr_ns;
8233         }
8234     }
8235
8236     /* pmsav7 has special handling for when MPU is disabled so call it before
8237      * the common MMU/MPU disabled check below.
8238      */
8239     if (arm_feature(env, ARM_FEATURE_MPU) &&
8240         arm_feature(env, ARM_FEATURE_V7)) {
8241         *page_size = TARGET_PAGE_SIZE;
8242         return get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
8243                                     phys_ptr, prot, fsr);
8244     }
8245
8246     if (regime_translation_disabled(env, mmu_idx)) {
8247         /* MMU/MPU disabled.  */
8248         *phys_ptr = address;
8249         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
8250         *page_size = TARGET_PAGE_SIZE;
8251         return 0;
8252     }
8253
8254     if (arm_feature(env, ARM_FEATURE_MPU)) {
8255         /* Pre-v7 MPU */
8256         *page_size = TARGET_PAGE_SIZE;
8257         return get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
8258                                     phys_ptr, prot, fsr);
8259     }
8260
8261     if (regime_using_lpae_format(env, mmu_idx)) {
8262         return get_phys_addr_lpae(env, address, access_type, mmu_idx, phys_ptr,
8263                                   attrs, prot, page_size, fsr, fi);
8264     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
8265         return get_phys_addr_v6(env, address, access_type, mmu_idx, phys_ptr,
8266                                 attrs, prot, page_size, fsr, fi);
8267     } else {
8268         return get_phys_addr_v5(env, address, access_type, mmu_idx, phys_ptr,
8269                                 prot, page_size, fsr, fi);
8270     }
8271 }
8272
8273 /* Walk the page table and (if the mapping exists) add the page
8274  * to the TLB. Return false on success, or true on failure. Populate
8275  * fsr with ARM DFSR/IFSR fault register format value on failure.
8276  */
8277 bool arm_tlb_fill(CPUState *cs, vaddr address,
8278                   int access_type, int mmu_idx, uint32_t *fsr,
8279                   ARMMMUFaultInfo *fi)
8280 {
8281     ARMCPU *cpu = ARM_CPU(cs);
8282     CPUARMState *env = &cpu->env;
8283     hwaddr phys_addr;
8284     target_ulong page_size;
8285     int prot;
8286     int ret;
8287     MemTxAttrs attrs = {};
8288
8289     ret = get_phys_addr(env, address, access_type, mmu_idx, &phys_addr,
8290                         &attrs, &prot, &page_size, fsr, fi);
8291     if (!ret) {
8292         /* Map a single [sub]page.  */
8293         phys_addr &= TARGET_PAGE_MASK;
8294         address &= TARGET_PAGE_MASK;
8295         tlb_set_page_with_attrs(cs, address, phys_addr, attrs,
8296                                 prot, mmu_idx, page_size);
8297         return 0;
8298     }
8299
8300     return ret;
8301 }
8302
8303 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
8304                                          MemTxAttrs *attrs)
8305 {
8306     ARMCPU *cpu = ARM_CPU(cs);
8307     CPUARMState *env = &cpu->env;
8308     hwaddr phys_addr;
8309     target_ulong page_size;
8310     int prot;
8311     bool ret;
8312     uint32_t fsr;
8313     ARMMMUFaultInfo fi = {};
8314
8315     *attrs = (MemTxAttrs) {};
8316
8317     ret = get_phys_addr(env, addr, 0, cpu_mmu_index(env, false), &phys_addr,
8318                         attrs, &prot, &page_size, &fsr, &fi);
8319
8320     if (ret) {
8321         return -1;
8322     }
8323     return phys_addr;
8324 }
8325
8326 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
8327 {
8328     uint32_t mask;
8329     unsigned el = arm_current_el(env);
8330
8331     /* First handle registers which unprivileged can read */
8332
8333     switch (reg) {
8334     case 0 ... 7: /* xPSR sub-fields */
8335         mask = 0;
8336         if ((reg & 1) && el) {
8337             mask |= 0x000001ff; /* IPSR (unpriv. reads as zero) */
8338         }
8339         if (!(reg & 4)) {
8340             mask |= 0xf8000000; /* APSR */
8341         }
8342         /* EPSR reads as zero */
8343         return xpsr_read(env) & mask;
8344         break;
8345     case 20: /* CONTROL */
8346         return env->v7m.control;
8347     }
8348
8349     if (el == 0) {
8350         return 0; /* unprivileged reads others as zero */
8351     }
8352
8353     switch (reg) {
8354     case 8: /* MSP */
8355         return (env->v7m.control & R_V7M_CONTROL_SPSEL_MASK) ?
8356             env->v7m.other_sp : env->regs[13];
8357     case 9: /* PSP */
8358         return (env->v7m.control & R_V7M_CONTROL_SPSEL_MASK) ?
8359             env->regs[13] : env->v7m.other_sp;
8360     case 16: /* PRIMASK */
8361         return (env->daif & PSTATE_I) != 0;
8362     case 17: /* BASEPRI */
8363     case 18: /* BASEPRI_MAX */
8364         return env->v7m.basepri;
8365     case 19: /* FAULTMASK */
8366         return (env->daif & PSTATE_F) != 0;
8367     default:
8368         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"
8369                                        " register %d\n", reg);
8370         return 0;
8371     }
8372 }
8373
8374 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
8375 {
8376     if (arm_current_el(env) == 0 && reg > 7) {
8377         /* only xPSR sub-fields may be written by unprivileged */
8378         return;
8379     }
8380
8381     switch (reg) {
8382     case 0 ... 7: /* xPSR sub-fields */
8383         /* only APSR is actually writable */
8384         if (reg & 4) {
8385             xpsr_write(env, val, 0xf8000000); /* APSR */
8386         }
8387         break;
8388     case 8: /* MSP */
8389         if (env->v7m.control & R_V7M_CONTROL_SPSEL_MASK) {
8390             env->v7m.other_sp = val;
8391         } else {
8392             env->regs[13] = val;
8393         }
8394         break;
8395     case 9: /* PSP */
8396         if (env->v7m.control & R_V7M_CONTROL_SPSEL_MASK) {
8397             env->regs[13] = val;
8398         } else {
8399             env->v7m.other_sp = val;
8400         }
8401         break;
8402     case 16: /* PRIMASK */
8403         if (val & 1) {
8404             env->daif |= PSTATE_I;
8405         } else {
8406             env->daif &= ~PSTATE_I;
8407         }
8408         break;
8409     case 17: /* BASEPRI */
8410         env->v7m.basepri = val & 0xff;
8411         break;
8412     case 18: /* BASEPRI_MAX */
8413         val &= 0xff;
8414         if (val != 0 && (val < env->v7m.basepri || env->v7m.basepri == 0))
8415             env->v7m.basepri = val;
8416         break;
8417     case 19: /* FAULTMASK */
8418         if (val & 1) {
8419             env->daif |= PSTATE_F;
8420         } else {
8421             env->daif &= ~PSTATE_F;
8422         }
8423         break;
8424     case 20: /* CONTROL */
8425         switch_v7m_sp(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);
8426         env->v7m.control = val & (R_V7M_CONTROL_SPSEL_MASK |
8427                                   R_V7M_CONTROL_NPRIV_MASK);
8428         break;
8429     default:
8430         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"
8431                                        " register %d\n", reg);
8432         return;
8433     }
8434 }
8435
8436 #endif
8437
8438 void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)
8439 {
8440     /* Implement DC ZVA, which zeroes a fixed-length block of memory.
8441      * Note that we do not implement the (architecturally mandated)
8442      * alignment fault for attempts to use this on Device memory
8443      * (which matches the usual QEMU behaviour of not implementing either
8444      * alignment faults or any memory attribute handling).
8445      */
8446
8447     ARMCPU *cpu = arm_env_get_cpu(env);
8448     uint64_t blocklen = 4 << cpu->dcz_blocksize;
8449     uint64_t vaddr = vaddr_in & ~(blocklen - 1);
8450
8451 #ifndef CONFIG_USER_ONLY
8452     {
8453         /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than
8454          * the block size so we might have to do more than one TLB lookup.
8455          * We know that in fact for any v8 CPU the page size is at least 4K
8456          * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only
8457          * 1K as an artefact of legacy v5 subpage support being present in the
8458          * same QEMU executable.
8459          */
8460         int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);
8461         void *hostaddr[maxidx];
8462         int try, i;
8463         unsigned mmu_idx = cpu_mmu_index(env, false);
8464         TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);
8465
8466         for (try = 0; try < 2; try++) {
8467
8468             for (i = 0; i < maxidx; i++) {
8469                 hostaddr[i] = tlb_vaddr_to_host(env,
8470                                                 vaddr + TARGET_PAGE_SIZE * i,
8471                                                 1, mmu_idx);
8472                 if (!hostaddr[i]) {
8473                     break;
8474                 }
8475             }
8476             if (i == maxidx) {
8477                 /* If it's all in the TLB it's fair game for just writing to;
8478                  * we know we don't need to update dirty status, etc.
8479                  */
8480                 for (i = 0; i < maxidx - 1; i++) {
8481                     memset(hostaddr[i], 0, TARGET_PAGE_SIZE);
8482                 }
8483                 memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));
8484                 return;
8485             }
8486             /* OK, try a store and see if we can populate the tlb. This
8487              * might cause an exception if the memory isn't writable,
8488              * in which case we will longjmp out of here. We must for
8489              * this purpose use the actual register value passed to us
8490              * so that we get the fault address right.
8491              */
8492             helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETPC());
8493             /* Now we can populate the other TLB entries, if any */
8494             for (i = 0; i < maxidx; i++) {
8495                 uint64_t va = vaddr + TARGET_PAGE_SIZE * i;
8496                 if (va != (vaddr_in & TARGET_PAGE_MASK)) {
8497                     helper_ret_stb_mmu(env, va, 0, oi, GETPC());
8498                 }
8499             }
8500         }
8501
8502         /* Slow path (probably attempt to do this to an I/O device or
8503          * similar, or clearing of a block of code we have translations
8504          * cached for). Just do a series of byte writes as the architecture
8505          * demands. It's not worth trying to use a cpu_physical_memory_map(),
8506          * memset(), unmap() sequence here because:
8507          *  + we'd need to account for the blocksize being larger than a page
8508          *  + the direct-RAM access case is almost always going to be dealt
8509          *    with in the fastpath code above, so there's no speed benefit
8510          *  + we would have to deal with the map returning NULL because the
8511          *    bounce buffer was in use
8512          */
8513         for (i = 0; i < blocklen; i++) {
8514             helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETPC());
8515         }
8516     }
8517 #else
8518     memset(g2h(vaddr), 0, blocklen);
8519 #endif
8520 }
8521
8522 /* Note that signed overflow is undefined in C.  The following routines are
8523    careful to use unsigned types where modulo arithmetic is required.
8524    Failure to do so _will_ break on newer gcc.  */
8525
8526 /* Signed saturating arithmetic.  */
8527
8528 /* Perform 16-bit signed saturating addition.  */
8529 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
8530 {
8531     uint16_t res;
8532
8533     res = a + b;
8534     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
8535         if (a & 0x8000)
8536             res = 0x8000;
8537         else
8538             res = 0x7fff;
8539     }
8540     return res;
8541 }
8542
8543 /* Perform 8-bit signed saturating addition.  */
8544 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
8545 {
8546     uint8_t res;
8547
8548     res = a + b;
8549     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
8550         if (a & 0x80)
8551             res = 0x80;
8552         else
8553             res = 0x7f;
8554     }
8555     return res;
8556 }
8557
8558 /* Perform 16-bit signed saturating subtraction.  */
8559 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
8560 {
8561     uint16_t res;
8562
8563     res = a - b;
8564     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
8565         if (a & 0x8000)
8566             res = 0x8000;
8567         else
8568             res = 0x7fff;
8569     }
8570     return res;
8571 }
8572
8573 /* Perform 8-bit signed saturating subtraction.  */
8574 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
8575 {
8576     uint8_t res;
8577
8578     res = a - b;
8579     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
8580         if (a & 0x80)
8581             res = 0x80;
8582         else
8583             res = 0x7f;
8584     }
8585     return res;
8586 }
8587
8588 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
8589 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
8590 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
8591 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
8592 #define PFX q
8593
8594 #include "op_addsub.h"
8595
8596 /* Unsigned saturating arithmetic.  */
8597 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
8598 {
8599     uint16_t res;
8600     res = a + b;
8601     if (res < a)
8602         res = 0xffff;
8603     return res;
8604 }
8605
8606 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
8607 {
8608     if (a > b)
8609         return a - b;
8610     else
8611         return 0;
8612 }
8613
8614 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
8615 {
8616     uint8_t res;
8617     res = a + b;
8618     if (res < a)
8619         res = 0xff;
8620     return res;
8621 }
8622
8623 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
8624 {
8625     if (a > b)
8626         return a - b;
8627     else
8628         return 0;
8629 }
8630
8631 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
8632 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
8633 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
8634 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
8635 #define PFX uq
8636
8637 #include "op_addsub.h"
8638
8639 /* Signed modulo arithmetic.  */
8640 #define SARITH16(a, b, n, op) do { \
8641     int32_t sum; \
8642     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
8643     RESULT(sum, n, 16); \
8644     if (sum >= 0) \
8645         ge |= 3 << (n * 2); \
8646     } while(0)
8647
8648 #define SARITH8(a, b, n, op) do { \
8649     int32_t sum; \
8650     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
8651     RESULT(sum, n, 8); \
8652     if (sum >= 0) \
8653         ge |= 1 << n; \
8654     } while(0)
8655
8656
8657 #define ADD16(a, b, n) SARITH16(a, b, n, +)
8658 #define SUB16(a, b, n) SARITH16(a, b, n, -)
8659 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
8660 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
8661 #define PFX s
8662 #define ARITH_GE
8663
8664 #include "op_addsub.h"
8665
8666 /* Unsigned modulo arithmetic.  */
8667 #define ADD16(a, b, n) do { \
8668     uint32_t sum; \
8669     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
8670     RESULT(sum, n, 16); \
8671     if ((sum >> 16) == 1) \
8672         ge |= 3 << (n * 2); \
8673     } while(0)
8674
8675 #define ADD8(a, b, n) do { \
8676     uint32_t sum; \
8677     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
8678     RESULT(sum, n, 8); \
8679     if ((sum >> 8) == 1) \
8680         ge |= 1 << n; \
8681     } while(0)
8682
8683 #define SUB16(a, b, n) do { \
8684     uint32_t sum; \
8685     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
8686     RESULT(sum, n, 16); \
8687     if ((sum >> 16) == 0) \
8688         ge |= 3 << (n * 2); \
8689     } while(0)
8690
8691 #define SUB8(a, b, n) do { \
8692     uint32_t sum; \
8693     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
8694     RESULT(sum, n, 8); \
8695     if ((sum >> 8) == 0) \
8696         ge |= 1 << n; \
8697     } while(0)
8698
8699 #define PFX u
8700 #define ARITH_GE
8701
8702 #include "op_addsub.h"
8703
8704 /* Halved signed arithmetic.  */
8705 #define ADD16(a, b, n) \
8706   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
8707 #define SUB16(a, b, n) \
8708   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
8709 #define ADD8(a, b, n) \
8710   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
8711 #define SUB8(a, b, n) \
8712   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
8713 #define PFX sh
8714
8715 #include "op_addsub.h"
8716
8717 /* Halved unsigned arithmetic.  */
8718 #define ADD16(a, b, n) \
8719   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
8720 #define SUB16(a, b, n) \
8721   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
8722 #define ADD8(a, b, n) \
8723   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
8724 #define SUB8(a, b, n) \
8725   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
8726 #define PFX uh
8727
8728 #include "op_addsub.h"
8729
8730 static inline uint8_t do_usad(uint8_t a, uint8_t b)
8731 {
8732     if (a > b)
8733         return a - b;
8734     else
8735         return b - a;
8736 }
8737
8738 /* Unsigned sum of absolute byte differences.  */
8739 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
8740 {
8741     uint32_t sum;
8742     sum = do_usad(a, b);
8743     sum += do_usad(a >> 8, b >> 8);
8744     sum += do_usad(a >> 16, b >>16);
8745     sum += do_usad(a >> 24, b >> 24);
8746     return sum;
8747 }
8748
8749 /* For ARMv6 SEL instruction.  */
8750 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
8751 {
8752     uint32_t mask;
8753
8754     mask = 0;
8755     if (flags & 1)
8756         mask |= 0xff;
8757     if (flags & 2)
8758         mask |= 0xff00;
8759     if (flags & 4)
8760         mask |= 0xff0000;
8761     if (flags & 8)
8762         mask |= 0xff000000;
8763     return (a & mask) | (b & ~mask);
8764 }
8765
8766 /* VFP support.  We follow the convention used for VFP instructions:
8767    Single precision routines have a "s" suffix, double precision a
8768    "d" suffix.  */
8769
8770 /* Convert host exception flags to vfp form.  */
8771 static inline int vfp_exceptbits_from_host(int host_bits)
8772 {
8773     int target_bits = 0;
8774
8775     if (host_bits & float_flag_invalid)
8776         target_bits |= 1;
8777     if (host_bits & float_flag_divbyzero)
8778         target_bits |= 2;
8779     if (host_bits & float_flag_overflow)
8780         target_bits |= 4;
8781     if (host_bits & (float_flag_underflow | float_flag_output_denormal))
8782         target_bits |= 8;
8783     if (host_bits & float_flag_inexact)
8784         target_bits |= 0x10;
8785     if (host_bits & float_flag_input_denormal)
8786         target_bits |= 0x80;
8787     return target_bits;
8788 }
8789
8790 uint32_t HELPER(vfp_get_fpscr)(CPUARMState *env)
8791 {
8792     int i;
8793     uint32_t fpscr;
8794
8795     fpscr = (env->vfp.xregs[ARM_VFP_FPSCR] & 0xffc8ffff)
8796             | (env->vfp.vec_len << 16)
8797             | (env->vfp.vec_stride << 20);
8798     i = get_float_exception_flags(&env->vfp.fp_status);
8799     i |= get_float_exception_flags(&env->vfp.standard_fp_status);
8800     fpscr |= vfp_exceptbits_from_host(i);
8801     return fpscr;
8802 }
8803
8804 uint32_t vfp_get_fpscr(CPUARMState *env)
8805 {
8806     return HELPER(vfp_get_fpscr)(env);
8807 }
8808
8809 /* Convert vfp exception flags to target form.  */
8810 static inline int vfp_exceptbits_to_host(int target_bits)
8811 {
8812     int host_bits = 0;
8813
8814     if (target_bits & 1)
8815         host_bits |= float_flag_invalid;
8816     if (target_bits & 2)
8817         host_bits |= float_flag_divbyzero;
8818     if (target_bits & 4)
8819         host_bits |= float_flag_overflow;
8820     if (target_bits & 8)
8821         host_bits |= float_flag_underflow;
8822     if (target_bits & 0x10)
8823         host_bits |= float_flag_inexact;
8824     if (target_bits & 0x80)
8825         host_bits |= float_flag_input_denormal;
8826     return host_bits;
8827 }
8828
8829 void HELPER(vfp_set_fpscr)(CPUARMState *env, uint32_t val)
8830 {
8831     int i;
8832     uint32_t changed;
8833
8834     changed = env->vfp.xregs[ARM_VFP_FPSCR];
8835     env->vfp.xregs[ARM_VFP_FPSCR] = (val & 0xffc8ffff);
8836     env->vfp.vec_len = (val >> 16) & 7;
8837     env->vfp.vec_stride = (val >> 20) & 3;
8838
8839     changed ^= val;
8840     if (changed & (3 << 22)) {
8841         i = (val >> 22) & 3;
8842         switch (i) {
8843         case FPROUNDING_TIEEVEN:
8844             i = float_round_nearest_even;
8845             break;
8846         case FPROUNDING_POSINF:
8847             i = float_round_up;
8848             break;
8849         case FPROUNDING_NEGINF:
8850             i = float_round_down;
8851             break;
8852         case FPROUNDING_ZERO:
8853             i = float_round_to_zero;
8854             break;
8855         }
8856         set_float_rounding_mode(i, &env->vfp.fp_status);
8857     }
8858     if (changed & (1 << 24)) {
8859         set_flush_to_zero((val & (1 << 24)) != 0, &env->vfp.fp_status);
8860         set_flush_inputs_to_zero((val & (1 << 24)) != 0, &env->vfp.fp_status);
8861     }
8862     if (changed & (1 << 25))
8863         set_default_nan_mode((val & (1 << 25)) != 0, &env->vfp.fp_status);
8864
8865     i = vfp_exceptbits_to_host(val);
8866     set_float_exception_flags(i, &env->vfp.fp_status);
8867     set_float_exception_flags(0, &env->vfp.standard_fp_status);
8868 }
8869
8870 void vfp_set_fpscr(CPUARMState *env, uint32_t val)
8871 {
8872     HELPER(vfp_set_fpscr)(env, val);
8873 }
8874
8875 #define VFP_HELPER(name, p) HELPER(glue(glue(vfp_,name),p))
8876
8877 #define VFP_BINOP(name) \
8878 float32 VFP_HELPER(name, s)(float32 a, float32 b, void *fpstp) \
8879 { \
8880     float_status *fpst = fpstp; \
8881     return float32_ ## name(a, b, fpst); \
8882 } \
8883 float64 VFP_HELPER(name, d)(float64 a, float64 b, void *fpstp) \
8884 { \
8885     float_status *fpst = fpstp; \
8886     return float64_ ## name(a, b, fpst); \
8887 }
8888 VFP_BINOP(add)
8889 VFP_BINOP(sub)
8890 VFP_BINOP(mul)
8891 VFP_BINOP(div)
8892 VFP_BINOP(min)
8893 VFP_BINOP(max)
8894 VFP_BINOP(minnum)
8895 VFP_BINOP(maxnum)
8896 #undef VFP_BINOP
8897
8898 float32 VFP_HELPER(neg, s)(float32 a)
8899 {
8900     return float32_chs(a);
8901 }
8902
8903 float64 VFP_HELPER(neg, d)(float64 a)
8904 {
8905     return float64_chs(a);
8906 }
8907
8908 float32 VFP_HELPER(abs, s)(float32 a)
8909 {
8910     return float32_abs(a);
8911 }
8912
8913 float64 VFP_HELPER(abs, d)(float64 a)
8914 {
8915     return float64_abs(a);
8916 }
8917
8918 float32 VFP_HELPER(sqrt, s)(float32 a, CPUARMState *env)
8919 {
8920     return float32_sqrt(a, &env->vfp.fp_status);
8921 }
8922
8923 float64 VFP_HELPER(sqrt, d)(float64 a, CPUARMState *env)
8924 {
8925     return float64_sqrt(a, &env->vfp.fp_status);
8926 }
8927
8928 /* XXX: check quiet/signaling case */
8929 #define DO_VFP_cmp(p, type) \
8930 void VFP_HELPER(cmp, p)(type a, type b, CPUARMState *env)  \
8931 { \
8932     uint32_t flags; \
8933     switch(type ## _compare_quiet(a, b, &env->vfp.fp_status)) { \
8934     case 0: flags = 0x6; break; \
8935     case -1: flags = 0x8; break; \
8936     case 1: flags = 0x2; break; \
8937     default: case 2: flags = 0x3; break; \
8938     } \
8939     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
8940         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
8941 } \
8942 void VFP_HELPER(cmpe, p)(type a, type b, CPUARMState *env) \
8943 { \
8944     uint32_t flags; \
8945     switch(type ## _compare(a, b, &env->vfp.fp_status)) { \
8946     case 0: flags = 0x6; break; \
8947     case -1: flags = 0x8; break; \
8948     case 1: flags = 0x2; break; \
8949     default: case 2: flags = 0x3; break; \
8950     } \
8951     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
8952         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
8953 }
8954 DO_VFP_cmp(s, float32)
8955 DO_VFP_cmp(d, float64)
8956 #undef DO_VFP_cmp
8957
8958 /* Integer to float and float to integer conversions */
8959
8960 #define CONV_ITOF(name, fsz, sign) \
8961     float##fsz HELPER(name)(uint32_t x, void *fpstp) \
8962 { \
8963     float_status *fpst = fpstp; \
8964     return sign##int32_to_##float##fsz((sign##int32_t)x, fpst); \
8965 }
8966
8967 #define CONV_FTOI(name, fsz, sign, round) \
8968 uint32_t HELPER(name)(float##fsz x, void *fpstp) \
8969 { \
8970     float_status *fpst = fpstp; \
8971     if (float##fsz##_is_any_nan(x)) { \
8972         float_raise(float_flag_invalid, fpst); \
8973         return 0; \
8974     } \
8975     return float##fsz##_to_##sign##int32##round(x, fpst); \
8976 }
8977
8978 #define FLOAT_CONVS(name, p, fsz, sign) \
8979 CONV_ITOF(vfp_##name##to##p, fsz, sign) \
8980 CONV_FTOI(vfp_to##name##p, fsz, sign, ) \
8981 CONV_FTOI(vfp_to##name##z##p, fsz, sign, _round_to_zero)
8982
8983 FLOAT_CONVS(si, s, 32, )
8984 FLOAT_CONVS(si, d, 64, )
8985 FLOAT_CONVS(ui, s, 32, u)
8986 FLOAT_CONVS(ui, d, 64, u)
8987
8988 #undef CONV_ITOF
8989 #undef CONV_FTOI
8990 #undef FLOAT_CONVS
8991
8992 /* floating point conversion */
8993 float64 VFP_HELPER(fcvtd, s)(float32 x, CPUARMState *env)
8994 {
8995     float64 r = float32_to_float64(x, &env->vfp.fp_status);
8996     /* ARM requires that S<->D conversion of any kind of NaN generates
8997      * a quiet NaN by forcing the most significant frac bit to 1.
8998      */
8999     return float64_maybe_silence_nan(r, &env->vfp.fp_status);
9000 }
9001
9002 float32 VFP_HELPER(fcvts, d)(float64 x, CPUARMState *env)
9003 {
9004     float32 r =  float64_to_float32(x, &env->vfp.fp_status);
9005     /* ARM requires that S<->D conversion of any kind of NaN generates
9006      * a quiet NaN by forcing the most significant frac bit to 1.
9007      */
9008     return float32_maybe_silence_nan(r, &env->vfp.fp_status);
9009 }
9010
9011 /* VFP3 fixed point conversion.  */
9012 #define VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype) \
9013 float##fsz HELPER(vfp_##name##to##p)(uint##isz##_t  x, uint32_t shift, \
9014                                      void *fpstp) \
9015 { \
9016     float_status *fpst = fpstp; \
9017     float##fsz tmp; \
9018     tmp = itype##_to_##float##fsz(x, fpst); \
9019     return float##fsz##_scalbn(tmp, -(int)shift, fpst); \
9020 }
9021
9022 /* Notice that we want only input-denormal exception flags from the
9023  * scalbn operation: the other possible flags (overflow+inexact if
9024  * we overflow to infinity, output-denormal) aren't correct for the
9025  * complete scale-and-convert operation.
9026  */
9027 #define VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, round) \
9028 uint##isz##_t HELPER(vfp_to##name##p##round)(float##fsz x, \
9029                                              uint32_t shift, \
9030                                              void *fpstp) \
9031 { \
9032     float_status *fpst = fpstp; \
9033     int old_exc_flags = get_float_exception_flags(fpst); \
9034     float##fsz tmp; \
9035     if (float##fsz##_is_any_nan(x)) { \
9036         float_raise(float_flag_invalid, fpst); \
9037         return 0; \
9038     } \
9039     tmp = float##fsz##_scalbn(x, shift, fpst); \
9040     old_exc_flags |= get_float_exception_flags(fpst) \
9041         & float_flag_input_denormal; \
9042     set_float_exception_flags(old_exc_flags, fpst); \
9043     return float##fsz##_to_##itype##round(tmp, fpst); \
9044 }
9045
9046 #define VFP_CONV_FIX(name, p, fsz, isz, itype)                   \
9047 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
9048 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, _round_to_zero) \
9049 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
9050
9051 #define VFP_CONV_FIX_A64(name, p, fsz, isz, itype)               \
9052 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
9053 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
9054
9055 VFP_CONV_FIX(sh, d, 64, 64, int16)
9056 VFP_CONV_FIX(sl, d, 64, 64, int32)
9057 VFP_CONV_FIX_A64(sq, d, 64, 64, int64)
9058 VFP_CONV_FIX(uh, d, 64, 64, uint16)
9059 VFP_CONV_FIX(ul, d, 64, 64, uint32)
9060 VFP_CONV_FIX_A64(uq, d, 64, 64, uint64)
9061 VFP_CONV_FIX(sh, s, 32, 32, int16)
9062 VFP_CONV_FIX(sl, s, 32, 32, int32)
9063 VFP_CONV_FIX_A64(sq, s, 32, 64, int64)
9064 VFP_CONV_FIX(uh, s, 32, 32, uint16)
9065 VFP_CONV_FIX(ul, s, 32, 32, uint32)
9066 VFP_CONV_FIX_A64(uq, s, 32, 64, uint64)
9067 #undef VFP_CONV_FIX
9068 #undef VFP_CONV_FIX_FLOAT
9069 #undef VFP_CONV_FLOAT_FIX_ROUND
9070
9071 /* Set the current fp rounding mode and return the old one.
9072  * The argument is a softfloat float_round_ value.
9073  */
9074 uint32_t HELPER(set_rmode)(uint32_t rmode, CPUARMState *env)
9075 {
9076     float_status *fp_status = &env->vfp.fp_status;
9077
9078     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
9079     set_float_rounding_mode(rmode, fp_status);
9080
9081     return prev_rmode;
9082 }
9083
9084 /* Set the current fp rounding mode in the standard fp status and return
9085  * the old one. This is for NEON instructions that need to change the
9086  * rounding mode but wish to use the standard FPSCR values for everything
9087  * else. Always set the rounding mode back to the correct value after
9088  * modifying it.
9089  * The argument is a softfloat float_round_ value.
9090  */
9091 uint32_t HELPER(set_neon_rmode)(uint32_t rmode, CPUARMState *env)
9092 {
9093     float_status *fp_status = &env->vfp.standard_fp_status;
9094
9095     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
9096     set_float_rounding_mode(rmode, fp_status);
9097
9098     return prev_rmode;
9099 }
9100
9101 /* Half precision conversions.  */
9102 static float32 do_fcvt_f16_to_f32(uint32_t a, CPUARMState *env, float_status *s)
9103 {
9104     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
9105     float32 r = float16_to_float32(make_float16(a), ieee, s);
9106     if (ieee) {
9107         return float32_maybe_silence_nan(r, s);
9108     }
9109     return r;
9110 }
9111
9112 static uint32_t do_fcvt_f32_to_f16(float32 a, CPUARMState *env, float_status *s)
9113 {
9114     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
9115     float16 r = float32_to_float16(a, ieee, s);
9116     if (ieee) {
9117         r = float16_maybe_silence_nan(r, s);
9118     }
9119     return float16_val(r);
9120 }
9121
9122 float32 HELPER(neon_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
9123 {
9124     return do_fcvt_f16_to_f32(a, env, &env->vfp.standard_fp_status);
9125 }
9126
9127 uint32_t HELPER(neon_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
9128 {
9129     return do_fcvt_f32_to_f16(a, env, &env->vfp.standard_fp_status);
9130 }
9131
9132 float32 HELPER(vfp_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
9133 {
9134     return do_fcvt_f16_to_f32(a, env, &env->vfp.fp_status);
9135 }
9136
9137 uint32_t HELPER(vfp_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
9138 {
9139     return do_fcvt_f32_to_f16(a, env, &env->vfp.fp_status);
9140 }
9141
9142 float64 HELPER(vfp_fcvt_f16_to_f64)(uint32_t a, CPUARMState *env)
9143 {
9144     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
9145     float64 r = float16_to_float64(make_float16(a), ieee, &env->vfp.fp_status);
9146     if (ieee) {
9147         return float64_maybe_silence_nan(r, &env->vfp.fp_status);
9148     }
9149     return r;
9150 }
9151
9152 uint32_t HELPER(vfp_fcvt_f64_to_f16)(float64 a, CPUARMState *env)
9153 {
9154     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
9155     float16 r = float64_to_float16(a, ieee, &env->vfp.fp_status);
9156     if (ieee) {
9157         r = float16_maybe_silence_nan(r, &env->vfp.fp_status);
9158     }
9159     return float16_val(r);
9160 }
9161
9162 #define float32_two make_float32(0x40000000)
9163 #define float32_three make_float32(0x40400000)
9164 #define float32_one_point_five make_float32(0x3fc00000)
9165
9166 float32 HELPER(recps_f32)(float32 a, float32 b, CPUARMState *env)
9167 {
9168     float_status *s = &env->vfp.standard_fp_status;
9169     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
9170         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
9171         if (!(float32_is_zero(a) || float32_is_zero(b))) {
9172             float_raise(float_flag_input_denormal, s);
9173         }
9174         return float32_two;
9175     }
9176     return float32_sub(float32_two, float32_mul(a, b, s), s);
9177 }
9178
9179 float32 HELPER(rsqrts_f32)(float32 a, float32 b, CPUARMState *env)
9180 {
9181     float_status *s = &env->vfp.standard_fp_status;
9182     float32 product;
9183     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
9184         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
9185         if (!(float32_is_zero(a) || float32_is_zero(b))) {
9186             float_raise(float_flag_input_denormal, s);
9187         }
9188         return float32_one_point_five;
9189     }
9190     product = float32_mul(a, b, s);
9191     return float32_div(float32_sub(float32_three, product, s), float32_two, s);
9192 }
9193
9194 /* NEON helpers.  */
9195
9196 /* Constants 256 and 512 are used in some helpers; we avoid relying on
9197  * int->float conversions at run-time.  */
9198 #define float64_256 make_float64(0x4070000000000000LL)
9199 #define float64_512 make_float64(0x4080000000000000LL)
9200 #define float32_maxnorm make_float32(0x7f7fffff)
9201 #define float64_maxnorm make_float64(0x7fefffffffffffffLL)
9202
9203 /* Reciprocal functions
9204  *
9205  * The algorithm that must be used to calculate the estimate
9206  * is specified by the ARM ARM, see FPRecipEstimate()
9207  */
9208
9209 static float64 recip_estimate(float64 a, float_status *real_fp_status)
9210 {
9211     /* These calculations mustn't set any fp exception flags,
9212      * so we use a local copy of the fp_status.
9213      */
9214     float_status dummy_status = *real_fp_status;
9215     float_status *s = &dummy_status;
9216     /* q = (int)(a * 512.0) */
9217     float64 q = float64_mul(float64_512, a, s);
9218     int64_t q_int = float64_to_int64_round_to_zero(q, s);
9219
9220     /* r = 1.0 / (((double)q + 0.5) / 512.0) */
9221     q = int64_to_float64(q_int, s);
9222     q = float64_add(q, float64_half, s);
9223     q = float64_div(q, float64_512, s);
9224     q = float64_div(float64_one, q, s);
9225
9226     /* s = (int)(256.0 * r + 0.5) */
9227     q = float64_mul(q, float64_256, s);
9228     q = float64_add(q, float64_half, s);
9229     q_int = float64_to_int64_round_to_zero(q, s);
9230
9231     /* return (double)s / 256.0 */
9232     return float64_div(int64_to_float64(q_int, s), float64_256, s);
9233 }
9234
9235 /* Common wrapper to call recip_estimate */
9236 static float64 call_recip_estimate(float64 num, int off, float_status *fpst)
9237 {
9238     uint64_t val64 = float64_val(num);
9239     uint64_t frac = extract64(val64, 0, 52);
9240     int64_t exp = extract64(val64, 52, 11);
9241     uint64_t sbit;
9242     float64 scaled, estimate;
9243
9244     /* Generate the scaled number for the estimate function */
9245     if (exp == 0) {
9246         if (extract64(frac, 51, 1) == 0) {
9247             exp = -1;
9248             frac = extract64(frac, 0, 50) << 2;
9249         } else {
9250             frac = extract64(frac, 0, 51) << 1;
9251         }
9252     }
9253
9254     /* scaled = '0' : '01111111110' : fraction<51:44> : Zeros(44); */
9255     scaled = make_float64((0x3feULL << 52)
9256                           | extract64(frac, 44, 8) << 44);
9257
9258     estimate = recip_estimate(scaled, fpst);
9259
9260     /* Build new result */
9261     val64 = float64_val(estimate);
9262     sbit = 0x8000000000000000ULL & val64;
9263     exp = off - exp;
9264     frac = extract64(val64, 0, 52);
9265
9266     if (exp == 0) {
9267         frac = 1ULL << 51 | extract64(frac, 1, 51);
9268     } else if (exp == -1) {
9269         frac = 1ULL << 50 | extract64(frac, 2, 50);
9270         exp = 0;
9271     }
9272
9273     return make_float64(sbit | (exp << 52) | frac);
9274 }
9275
9276 static bool round_to_inf(float_status *fpst, bool sign_bit)
9277 {
9278     switch (fpst->float_rounding_mode) {
9279     case float_round_nearest_even: /* Round to Nearest */
9280         return true;
9281     case float_round_up: /* Round to +Inf */
9282         return !sign_bit;
9283     case float_round_down: /* Round to -Inf */
9284         return sign_bit;
9285     case float_round_to_zero: /* Round to Zero */
9286         return false;
9287     }
9288
9289     g_assert_not_reached();
9290 }
9291
9292 float32 HELPER(recpe_f32)(float32 input, void *fpstp)
9293 {
9294     float_status *fpst = fpstp;
9295     float32 f32 = float32_squash_input_denormal(input, fpst);
9296     uint32_t f32_val = float32_val(f32);
9297     uint32_t f32_sbit = 0x80000000ULL & f32_val;
9298     int32_t f32_exp = extract32(f32_val, 23, 8);
9299     uint32_t f32_frac = extract32(f32_val, 0, 23);
9300     float64 f64, r64;
9301     uint64_t r64_val;
9302     int64_t r64_exp;
9303     uint64_t r64_frac;
9304
9305     if (float32_is_any_nan(f32)) {
9306         float32 nan = f32;
9307         if (float32_is_signaling_nan(f32, fpst)) {
9308             float_raise(float_flag_invalid, fpst);
9309             nan = float32_maybe_silence_nan(f32, fpst);
9310         }
9311         if (fpst->default_nan_mode) {
9312             nan =  float32_default_nan(fpst);
9313         }
9314         return nan;
9315     } else if (float32_is_infinity(f32)) {
9316         return float32_set_sign(float32_zero, float32_is_neg(f32));
9317     } else if (float32_is_zero(f32)) {
9318         float_raise(float_flag_divbyzero, fpst);
9319         return float32_set_sign(float32_infinity, float32_is_neg(f32));
9320     } else if ((f32_val & ~(1ULL << 31)) < (1ULL << 21)) {
9321         /* Abs(value) < 2.0^-128 */
9322         float_raise(float_flag_overflow | float_flag_inexact, fpst);
9323         if (round_to_inf(fpst, f32_sbit)) {
9324             return float32_set_sign(float32_infinity, float32_is_neg(f32));
9325         } else {
9326             return float32_set_sign(float32_maxnorm, float32_is_neg(f32));
9327         }
9328     } else if (f32_exp >= 253 && fpst->flush_to_zero) {
9329         float_raise(float_flag_underflow, fpst);
9330         return float32_set_sign(float32_zero, float32_is_neg(f32));
9331     }
9332
9333
9334     f64 = make_float64(((int64_t)(f32_exp) << 52) | (int64_t)(f32_frac) << 29);
9335     r64 = call_recip_estimate(f64, 253, fpst);
9336     r64_val = float64_val(r64);
9337     r64_exp = extract64(r64_val, 52, 11);
9338     r64_frac = extract64(r64_val, 0, 52);
9339
9340     /* result = sign : result_exp<7:0> : fraction<51:29>; */
9341     return make_float32(f32_sbit |
9342                         (r64_exp & 0xff) << 23 |
9343                         extract64(r64_frac, 29, 24));
9344 }
9345
9346 float64 HELPER(recpe_f64)(float64 input, void *fpstp)
9347 {
9348     float_status *fpst = fpstp;
9349     float64 f64 = float64_squash_input_denormal(input, fpst);
9350     uint64_t f64_val = float64_val(f64);
9351     uint64_t f64_sbit = 0x8000000000000000ULL & f64_val;
9352     int64_t f64_exp = extract64(f64_val, 52, 11);
9353     float64 r64;
9354     uint64_t r64_val;
9355     int64_t r64_exp;
9356     uint64_t r64_frac;
9357
9358     /* Deal with any special cases */
9359     if (float64_is_any_nan(f64)) {
9360         float64 nan = f64;
9361         if (float64_is_signaling_nan(f64, fpst)) {
9362             float_raise(float_flag_invalid, fpst);
9363             nan = float64_maybe_silence_nan(f64, fpst);
9364         }
9365         if (fpst->default_nan_mode) {
9366             nan =  float64_default_nan(fpst);
9367         }
9368         return nan;
9369     } else if (float64_is_infinity(f64)) {
9370         return float64_set_sign(float64_zero, float64_is_neg(f64));
9371     } else if (float64_is_zero(f64)) {
9372         float_raise(float_flag_divbyzero, fpst);
9373         return float64_set_sign(float64_infinity, float64_is_neg(f64));
9374     } else if ((f64_val & ~(1ULL << 63)) < (1ULL << 50)) {
9375         /* Abs(value) < 2.0^-1024 */
9376         float_raise(float_flag_overflow | float_flag_inexact, fpst);
9377         if (round_to_inf(fpst, f64_sbit)) {
9378             return float64_set_sign(float64_infinity, float64_is_neg(f64));
9379         } else {
9380             return float64_set_sign(float64_maxnorm, float64_is_neg(f64));
9381         }
9382     } else if (f64_exp >= 2045 && fpst->flush_to_zero) {
9383         float_raise(float_flag_underflow, fpst);
9384         return float64_set_sign(float64_zero, float64_is_neg(f64));
9385     }
9386
9387     r64 = call_recip_estimate(f64, 2045, fpst);
9388     r64_val = float64_val(r64);
9389     r64_exp = extract64(r64_val, 52, 11);
9390     r64_frac = extract64(r64_val, 0, 52);
9391
9392     /* result = sign : result_exp<10:0> : fraction<51:0> */
9393     return make_float64(f64_sbit |
9394                         ((r64_exp & 0x7ff) << 52) |
9395                         r64_frac);
9396 }
9397
9398 /* The algorithm that must be used to calculate the estimate
9399  * is specified by the ARM ARM.
9400  */
9401 static float64 recip_sqrt_estimate(float64 a, float_status *real_fp_status)
9402 {
9403     /* These calculations mustn't set any fp exception flags,
9404      * so we use a local copy of the fp_status.
9405      */
9406     float_status dummy_status = *real_fp_status;
9407     float_status *s = &dummy_status;
9408     float64 q;
9409     int64_t q_int;
9410
9411     if (float64_lt(a, float64_half, s)) {
9412         /* range 0.25 <= a < 0.5 */
9413
9414         /* a in units of 1/512 rounded down */
9415         /* q0 = (int)(a * 512.0);  */
9416         q = float64_mul(float64_512, a, s);
9417         q_int = float64_to_int64_round_to_zero(q, s);
9418
9419         /* reciprocal root r */
9420         /* r = 1.0 / sqrt(((double)q0 + 0.5) / 512.0);  */
9421         q = int64_to_float64(q_int, s);
9422         q = float64_add(q, float64_half, s);
9423         q = float64_div(q, float64_512, s);
9424         q = float64_sqrt(q, s);
9425         q = float64_div(float64_one, q, s);
9426     } else {
9427         /* range 0.5 <= a < 1.0 */
9428
9429         /* a in units of 1/256 rounded down */
9430         /* q1 = (int)(a * 256.0); */
9431         q = float64_mul(float64_256, a, s);
9432         int64_t q_int = float64_to_int64_round_to_zero(q, s);
9433
9434         /* reciprocal root r */
9435         /* r = 1.0 /sqrt(((double)q1 + 0.5) / 256); */
9436         q = int64_to_float64(q_int, s);
9437         q = float64_add(q, float64_half, s);
9438         q = float64_div(q, float64_256, s);
9439         q = float64_sqrt(q, s);
9440         q = float64_div(float64_one, q, s);
9441     }
9442     /* r in units of 1/256 rounded to nearest */
9443     /* s = (int)(256.0 * r + 0.5); */
9444
9445     q = float64_mul(q, float64_256,s );
9446     q = float64_add(q, float64_half, s);
9447     q_int = float64_to_int64_round_to_zero(q, s);
9448
9449     /* return (double)s / 256.0;*/
9450     return float64_div(int64_to_float64(q_int, s), float64_256, s);
9451 }
9452
9453 float32 HELPER(rsqrte_f32)(float32 input, void *fpstp)
9454 {
9455     float_status *s = fpstp;
9456     float32 f32 = float32_squash_input_denormal(input, s);
9457     uint32_t val = float32_val(f32);
9458     uint32_t f32_sbit = 0x80000000 & val;
9459     int32_t f32_exp = extract32(val, 23, 8);
9460     uint32_t f32_frac = extract32(val, 0, 23);
9461     uint64_t f64_frac;
9462     uint64_t val64;
9463     int result_exp;
9464     float64 f64;
9465
9466     if (float32_is_any_nan(f32)) {
9467         float32 nan = f32;
9468         if (float32_is_signaling_nan(f32, s)) {
9469             float_raise(float_flag_invalid, s);
9470             nan = float32_maybe_silence_nan(f32, s);
9471         }
9472         if (s->default_nan_mode) {
9473             nan =  float32_default_nan(s);
9474         }
9475         return nan;
9476     } else if (float32_is_zero(f32)) {
9477         float_raise(float_flag_divbyzero, s);
9478         return float32_set_sign(float32_infinity, float32_is_neg(f32));
9479     } else if (float32_is_neg(f32)) {
9480         float_raise(float_flag_invalid, s);
9481         return float32_default_nan(s);
9482     } else if (float32_is_infinity(f32)) {
9483         return float32_zero;
9484     }
9485
9486     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
9487      * preserving the parity of the exponent.  */
9488
9489     f64_frac = ((uint64_t) f32_frac) << 29;
9490     if (f32_exp == 0) {
9491         while (extract64(f64_frac, 51, 1) == 0) {
9492             f64_frac = f64_frac << 1;
9493             f32_exp = f32_exp-1;
9494         }
9495         f64_frac = extract64(f64_frac, 0, 51) << 1;
9496     }
9497
9498     if (extract64(f32_exp, 0, 1) == 0) {
9499         f64 = make_float64(((uint64_t) f32_sbit) << 32
9500                            | (0x3feULL << 52)
9501                            | f64_frac);
9502     } else {
9503         f64 = make_float64(((uint64_t) f32_sbit) << 32
9504                            | (0x3fdULL << 52)
9505                            | f64_frac);
9506     }
9507
9508     result_exp = (380 - f32_exp) / 2;
9509
9510     f64 = recip_sqrt_estimate(f64, s);
9511
9512     val64 = float64_val(f64);
9513
9514     val = ((result_exp & 0xff) << 23)
9515         | ((val64 >> 29)  & 0x7fffff);
9516     return make_float32(val);
9517 }
9518
9519 float64 HELPER(rsqrte_f64)(float64 input, void *fpstp)
9520 {
9521     float_status *s = fpstp;
9522     float64 f64 = float64_squash_input_denormal(input, s);
9523     uint64_t val = float64_val(f64);
9524     uint64_t f64_sbit = 0x8000000000000000ULL & val;
9525     int64_t f64_exp = extract64(val, 52, 11);
9526     uint64_t f64_frac = extract64(val, 0, 52);
9527     int64_t result_exp;
9528     uint64_t result_frac;
9529
9530     if (float64_is_any_nan(f64)) {
9531         float64 nan = f64;
9532         if (float64_is_signaling_nan(f64, s)) {
9533             float_raise(float_flag_invalid, s);
9534             nan = float64_maybe_silence_nan(f64, s);
9535         }
9536         if (s->default_nan_mode) {
9537             nan =  float64_default_nan(s);
9538         }
9539         return nan;
9540     } else if (float64_is_zero(f64)) {
9541         float_raise(float_flag_divbyzero, s);
9542         return float64_set_sign(float64_infinity, float64_is_neg(f64));
9543     } else if (float64_is_neg(f64)) {
9544         float_raise(float_flag_invalid, s);
9545         return float64_default_nan(s);
9546     } else if (float64_is_infinity(f64)) {
9547         return float64_zero;
9548     }
9549
9550     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
9551      * preserving the parity of the exponent.  */
9552
9553     if (f64_exp == 0) {
9554         while (extract64(f64_frac, 51, 1) == 0) {
9555             f64_frac = f64_frac << 1;
9556             f64_exp = f64_exp - 1;
9557         }
9558         f64_frac = extract64(f64_frac, 0, 51) << 1;
9559     }
9560
9561     if (extract64(f64_exp, 0, 1) == 0) {
9562         f64 = make_float64(f64_sbit
9563                            | (0x3feULL << 52)
9564                            | f64_frac);
9565     } else {
9566         f64 = make_float64(f64_sbit
9567                            | (0x3fdULL << 52)
9568                            | f64_frac);
9569     }
9570
9571     result_exp = (3068 - f64_exp) / 2;
9572
9573     f64 = recip_sqrt_estimate(f64, s);
9574
9575     result_frac = extract64(float64_val(f64), 0, 52);
9576
9577     return make_float64(f64_sbit |
9578                         ((result_exp & 0x7ff) << 52) |
9579                         result_frac);
9580 }
9581
9582 uint32_t HELPER(recpe_u32)(uint32_t a, void *fpstp)
9583 {
9584     float_status *s = fpstp;
9585     float64 f64;
9586
9587     if ((a & 0x80000000) == 0) {
9588         return 0xffffffff;
9589     }
9590
9591     f64 = make_float64((0x3feULL << 52)
9592                        | ((int64_t)(a & 0x7fffffff) << 21));
9593
9594     f64 = recip_estimate(f64, s);
9595
9596     return 0x80000000 | ((float64_val(f64) >> 21) & 0x7fffffff);
9597 }
9598
9599 uint32_t HELPER(rsqrte_u32)(uint32_t a, void *fpstp)
9600 {
9601     float_status *fpst = fpstp;
9602     float64 f64;
9603
9604     if ((a & 0xc0000000) == 0) {
9605         return 0xffffffff;
9606     }
9607
9608     if (a & 0x80000000) {
9609         f64 = make_float64((0x3feULL << 52)
9610                            | ((uint64_t)(a & 0x7fffffff) << 21));
9611     } else { /* bits 31-30 == '01' */
9612         f64 = make_float64((0x3fdULL << 52)
9613                            | ((uint64_t)(a & 0x3fffffff) << 22));
9614     }
9615
9616     f64 = recip_sqrt_estimate(f64, fpst);
9617
9618     return 0x80000000 | ((float64_val(f64) >> 21) & 0x7fffffff);
9619 }
9620
9621 /* VFPv4 fused multiply-accumulate */
9622 float32 VFP_HELPER(muladd, s)(float32 a, float32 b, float32 c, void *fpstp)
9623 {
9624     float_status *fpst = fpstp;
9625     return float32_muladd(a, b, c, 0, fpst);
9626 }
9627
9628 float64 VFP_HELPER(muladd, d)(float64 a, float64 b, float64 c, void *fpstp)
9629 {
9630     float_status *fpst = fpstp;
9631     return float64_muladd(a, b, c, 0, fpst);
9632 }
9633
9634 /* ARMv8 round to integral */
9635 float32 HELPER(rints_exact)(float32 x, void *fp_status)
9636 {
9637     return float32_round_to_int(x, fp_status);
9638 }
9639
9640 float64 HELPER(rintd_exact)(float64 x, void *fp_status)
9641 {
9642     return float64_round_to_int(x, fp_status);
9643 }
9644
9645 float32 HELPER(rints)(float32 x, void *fp_status)
9646 {
9647     int old_flags = get_float_exception_flags(fp_status), new_flags;
9648     float32 ret;
9649
9650     ret = float32_round_to_int(x, fp_status);
9651
9652     /* Suppress any inexact exceptions the conversion produced */
9653     if (!(old_flags & float_flag_inexact)) {
9654         new_flags = get_float_exception_flags(fp_status);
9655         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
9656     }
9657
9658     return ret;
9659 }
9660
9661 float64 HELPER(rintd)(float64 x, void *fp_status)
9662 {
9663     int old_flags = get_float_exception_flags(fp_status), new_flags;
9664     float64 ret;
9665
9666     ret = float64_round_to_int(x, fp_status);
9667
9668     new_flags = get_float_exception_flags(fp_status);
9669
9670     /* Suppress any inexact exceptions the conversion produced */
9671     if (!(old_flags & float_flag_inexact)) {
9672         new_flags = get_float_exception_flags(fp_status);
9673         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
9674     }
9675
9676     return ret;
9677 }
9678
9679 /* Convert ARM rounding mode to softfloat */
9680 int arm_rmode_to_sf(int rmode)
9681 {
9682     switch (rmode) {
9683     case FPROUNDING_TIEAWAY:
9684         rmode = float_round_ties_away;
9685         break;
9686     case FPROUNDING_ODD:
9687         /* FIXME: add support for TIEAWAY and ODD */
9688         qemu_log_mask(LOG_UNIMP, "arm: unimplemented rounding mode: %d\n",
9689                       rmode);
9690     case FPROUNDING_TIEEVEN:
9691     default:
9692         rmode = float_round_nearest_even;
9693         break;
9694     case FPROUNDING_POSINF:
9695         rmode = float_round_up;
9696         break;
9697     case FPROUNDING_NEGINF:
9698         rmode = float_round_down;
9699         break;
9700     case FPROUNDING_ZERO:
9701         rmode = float_round_to_zero;
9702         break;
9703     }
9704     return rmode;
9705 }
9706
9707 /* CRC helpers.
9708  * The upper bytes of val (above the number specified by 'bytes') must have
9709  * been zeroed out by the caller.
9710  */
9711 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
9712 {
9713     uint8_t buf[4];
9714
9715     stl_le_p(buf, val);
9716
9717     /* zlib crc32 converts the accumulator and output to one's complement.  */
9718     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
9719 }
9720
9721 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
9722 {
9723     uint8_t buf[4];
9724
9725     stl_le_p(buf, val);
9726
9727     /* Linux crc32c converts the output to one's complement.  */
9728     return crc32c(acc, buf, bytes) ^ 0xffffffff;
9729 }
This page took 0.555944 seconds and 4 git commands to generate.