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