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