Make vfio MSI interrupt be non-threaded.
[kvmfornfv.git] / qemu / 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_is_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       .type = ARM_CP_ALIAS, /* reset handled by AArch32 view */
2756       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
2757       .access = PL3_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
2758       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]) },
2759     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
2760       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
2761       .access = PL3_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2762       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
2763     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
2764       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
2765       .access = PL3_RW, .writefn = vmsa_tcr_el1_write,
2766       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
2767       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
2768     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
2769       .type = ARM_CP_ALIAS,
2770       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
2771       .access = PL3_RW,
2772       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
2773     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
2774       .type = ARM_CP_ALIAS,
2775       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
2776       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
2777     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
2778       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
2779       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
2780     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
2781       .type = ARM_CP_ALIAS,
2782       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
2783       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, banked_spsr[7]) },
2784     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
2785       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
2786       .access = PL3_RW, .writefn = vbar_write,
2787       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
2788       .resetvalue = 0 },
2789     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
2790       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
2791       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
2792       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
2793     REGINFO_SENTINEL
2794 };
2795
2796 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri)
2797 {
2798     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
2799      * but the AArch32 CTR has its own reginfo struct)
2800      */
2801     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
2802         return CP_ACCESS_TRAP;
2803     }
2804     return CP_ACCESS_OK;
2805 }
2806
2807 static const ARMCPRegInfo debug_cp_reginfo[] = {
2808     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
2809      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
2810      * unlike DBGDRAR it is never accessible from EL0.
2811      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
2812      * accessor.
2813      */
2814     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
2815       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2816     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
2817       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
2818       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2819     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
2820       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2821     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
2822     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
2823       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
2824       .access = PL1_RW,
2825       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
2826       .resetvalue = 0 },
2827     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
2828      * We don't implement the configurable EL0 access.
2829      */
2830     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
2831       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
2832       .type = ARM_CP_ALIAS,
2833       .access = PL1_R,
2834       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
2835     /* We define a dummy WI OSLAR_EL1, because Linux writes to it. */
2836     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
2837       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
2838       .access = PL1_W, .type = ARM_CP_NOP },
2839     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
2840     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
2841       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
2842       .access = PL1_RW, .type = ARM_CP_NOP },
2843     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
2844      * implement vector catch debug events yet.
2845      */
2846     { .name = "DBGVCR",
2847       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
2848       .access = PL1_RW, .type = ARM_CP_NOP },
2849     REGINFO_SENTINEL
2850 };
2851
2852 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
2853     /* 64 bit access versions of the (dummy) debug registers */
2854     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
2855       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
2856     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
2857       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
2858     REGINFO_SENTINEL
2859 };
2860
2861 void hw_watchpoint_update(ARMCPU *cpu, int n)
2862 {
2863     CPUARMState *env = &cpu->env;
2864     vaddr len = 0;
2865     vaddr wvr = env->cp15.dbgwvr[n];
2866     uint64_t wcr = env->cp15.dbgwcr[n];
2867     int mask;
2868     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
2869
2870     if (env->cpu_watchpoint[n]) {
2871         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
2872         env->cpu_watchpoint[n] = NULL;
2873     }
2874
2875     if (!extract64(wcr, 0, 1)) {
2876         /* E bit clear : watchpoint disabled */
2877         return;
2878     }
2879
2880     switch (extract64(wcr, 3, 2)) {
2881     case 0:
2882         /* LSC 00 is reserved and must behave as if the wp is disabled */
2883         return;
2884     case 1:
2885         flags |= BP_MEM_READ;
2886         break;
2887     case 2:
2888         flags |= BP_MEM_WRITE;
2889         break;
2890     case 3:
2891         flags |= BP_MEM_ACCESS;
2892         break;
2893     }
2894
2895     /* Attempts to use both MASK and BAS fields simultaneously are
2896      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
2897      * thus generating a watchpoint for every byte in the masked region.
2898      */
2899     mask = extract64(wcr, 24, 4);
2900     if (mask == 1 || mask == 2) {
2901         /* Reserved values of MASK; we must act as if the mask value was
2902          * some non-reserved value, or as if the watchpoint were disabled.
2903          * We choose the latter.
2904          */
2905         return;
2906     } else if (mask) {
2907         /* Watchpoint covers an aligned area up to 2GB in size */
2908         len = 1ULL << mask;
2909         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
2910          * whether the watchpoint fires when the unmasked bits match; we opt
2911          * to generate the exceptions.
2912          */
2913         wvr &= ~(len - 1);
2914     } else {
2915         /* Watchpoint covers bytes defined by the byte address select bits */
2916         int bas = extract64(wcr, 5, 8);
2917         int basstart;
2918
2919         if (bas == 0) {
2920             /* This must act as if the watchpoint is disabled */
2921             return;
2922         }
2923
2924         if (extract64(wvr, 2, 1)) {
2925             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
2926              * ignored, and BAS[3:0] define which bytes to watch.
2927              */
2928             bas &= 0xf;
2929         }
2930         /* The BAS bits are supposed to be programmed to indicate a contiguous
2931          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
2932          * we fire for each byte in the word/doubleword addressed by the WVR.
2933          * We choose to ignore any non-zero bits after the first range of 1s.
2934          */
2935         basstart = ctz32(bas);
2936         len = cto32(bas >> basstart);
2937         wvr += basstart;
2938     }
2939
2940     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
2941                           &env->cpu_watchpoint[n]);
2942 }
2943
2944 void hw_watchpoint_update_all(ARMCPU *cpu)
2945 {
2946     int i;
2947     CPUARMState *env = &cpu->env;
2948
2949     /* Completely clear out existing QEMU watchpoints and our array, to
2950      * avoid possible stale entries following migration load.
2951      */
2952     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
2953     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
2954
2955     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
2956         hw_watchpoint_update(cpu, i);
2957     }
2958 }
2959
2960 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2961                          uint64_t value)
2962 {
2963     ARMCPU *cpu = arm_env_get_cpu(env);
2964     int i = ri->crm;
2965
2966     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
2967      * register reads and behaves as if values written are sign extended.
2968      * Bits [1:0] are RES0.
2969      */
2970     value = sextract64(value, 0, 49) & ~3ULL;
2971
2972     raw_write(env, ri, value);
2973     hw_watchpoint_update(cpu, i);
2974 }
2975
2976 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2977                          uint64_t value)
2978 {
2979     ARMCPU *cpu = arm_env_get_cpu(env);
2980     int i = ri->crm;
2981
2982     raw_write(env, ri, value);
2983     hw_watchpoint_update(cpu, i);
2984 }
2985
2986 void hw_breakpoint_update(ARMCPU *cpu, int n)
2987 {
2988     CPUARMState *env = &cpu->env;
2989     uint64_t bvr = env->cp15.dbgbvr[n];
2990     uint64_t bcr = env->cp15.dbgbcr[n];
2991     vaddr addr;
2992     int bt;
2993     int flags = BP_CPU;
2994
2995     if (env->cpu_breakpoint[n]) {
2996         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
2997         env->cpu_breakpoint[n] = NULL;
2998     }
2999
3000     if (!extract64(bcr, 0, 1)) {
3001         /* E bit clear : watchpoint disabled */
3002         return;
3003     }
3004
3005     bt = extract64(bcr, 20, 4);
3006
3007     switch (bt) {
3008     case 4: /* unlinked address mismatch (reserved if AArch64) */
3009     case 5: /* linked address mismatch (reserved if AArch64) */
3010         qemu_log_mask(LOG_UNIMP,
3011                       "arm: address mismatch breakpoint types not implemented");
3012         return;
3013     case 0: /* unlinked address match */
3014     case 1: /* linked address match */
3015     {
3016         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
3017          * we behave as if the register was sign extended. Bits [1:0] are
3018          * RES0. The BAS field is used to allow setting breakpoints on 16
3019          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
3020          * a bp will fire if the addresses covered by the bp and the addresses
3021          * covered by the insn overlap but the insn doesn't start at the
3022          * start of the bp address range. We choose to require the insn and
3023          * the bp to have the same address. The constraints on writing to
3024          * BAS enforced in dbgbcr_write mean we have only four cases:
3025          *  0b0000  => no breakpoint
3026          *  0b0011  => breakpoint on addr
3027          *  0b1100  => breakpoint on addr + 2
3028          *  0b1111  => breakpoint on addr
3029          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
3030          */
3031         int bas = extract64(bcr, 5, 4);
3032         addr = sextract64(bvr, 0, 49) & ~3ULL;
3033         if (bas == 0) {
3034             return;
3035         }
3036         if (bas == 0xc) {
3037             addr += 2;
3038         }
3039         break;
3040     }
3041     case 2: /* unlinked context ID match */
3042     case 8: /* unlinked VMID match (reserved if no EL2) */
3043     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
3044         qemu_log_mask(LOG_UNIMP,
3045                       "arm: unlinked context breakpoint types not implemented");
3046         return;
3047     case 9: /* linked VMID match (reserved if no EL2) */
3048     case 11: /* linked context ID and VMID match (reserved if no EL2) */
3049     case 3: /* linked context ID match */
3050     default:
3051         /* We must generate no events for Linked context matches (unless
3052          * they are linked to by some other bp/wp, which is handled in
3053          * updates for the linking bp/wp). We choose to also generate no events
3054          * for reserved values.
3055          */
3056         return;
3057     }
3058
3059     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
3060 }
3061
3062 void hw_breakpoint_update_all(ARMCPU *cpu)
3063 {
3064     int i;
3065     CPUARMState *env = &cpu->env;
3066
3067     /* Completely clear out existing QEMU breakpoints and our array, to
3068      * avoid possible stale entries following migration load.
3069      */
3070     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
3071     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
3072
3073     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
3074         hw_breakpoint_update(cpu, i);
3075     }
3076 }
3077
3078 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3079                          uint64_t value)
3080 {
3081     ARMCPU *cpu = arm_env_get_cpu(env);
3082     int i = ri->crm;
3083
3084     raw_write(env, ri, value);
3085     hw_breakpoint_update(cpu, i);
3086 }
3087
3088 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3089                          uint64_t value)
3090 {
3091     ARMCPU *cpu = arm_env_get_cpu(env);
3092     int i = ri->crm;
3093
3094     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
3095      * copy of BAS[0].
3096      */
3097     value = deposit64(value, 6, 1, extract64(value, 5, 1));
3098     value = deposit64(value, 8, 1, extract64(value, 7, 1));
3099
3100     raw_write(env, ri, value);
3101     hw_breakpoint_update(cpu, i);
3102 }
3103
3104 static void define_debug_regs(ARMCPU *cpu)
3105 {
3106     /* Define v7 and v8 architectural debug registers.
3107      * These are just dummy implementations for now.
3108      */
3109     int i;
3110     int wrps, brps, ctx_cmps;
3111     ARMCPRegInfo dbgdidr = {
3112         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
3113         .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
3114     };
3115
3116     /* Note that all these register fields hold "number of Xs minus 1". */
3117     brps = extract32(cpu->dbgdidr, 24, 4);
3118     wrps = extract32(cpu->dbgdidr, 28, 4);
3119     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
3120
3121     assert(ctx_cmps <= brps);
3122
3123     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
3124      * of the debug registers such as number of breakpoints;
3125      * check that if they both exist then they agree.
3126      */
3127     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
3128         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
3129         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
3130         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
3131     }
3132
3133     define_one_arm_cp_reg(cpu, &dbgdidr);
3134     define_arm_cp_regs(cpu, debug_cp_reginfo);
3135
3136     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
3137         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
3138     }
3139
3140     for (i = 0; i < brps + 1; i++) {
3141         ARMCPRegInfo dbgregs[] = {
3142             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
3143               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
3144               .access = PL1_RW,
3145               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
3146               .writefn = dbgbvr_write, .raw_writefn = raw_write
3147             },
3148             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
3149               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
3150               .access = PL1_RW,
3151               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
3152               .writefn = dbgbcr_write, .raw_writefn = raw_write
3153             },
3154             REGINFO_SENTINEL
3155         };
3156         define_arm_cp_regs(cpu, dbgregs);
3157     }
3158
3159     for (i = 0; i < wrps + 1; i++) {
3160         ARMCPRegInfo dbgregs[] = {
3161             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
3162               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
3163               .access = PL1_RW,
3164               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
3165               .writefn = dbgwvr_write, .raw_writefn = raw_write
3166             },
3167             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
3168               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
3169               .access = PL1_RW,
3170               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
3171               .writefn = dbgwcr_write, .raw_writefn = raw_write
3172             },
3173             REGINFO_SENTINEL
3174         };
3175         define_arm_cp_regs(cpu, dbgregs);
3176     }
3177 }
3178
3179 void register_cp_regs_for_features(ARMCPU *cpu)
3180 {
3181     /* Register all the coprocessor registers based on feature bits */
3182     CPUARMState *env = &cpu->env;
3183     if (arm_feature(env, ARM_FEATURE_M)) {
3184         /* M profile has no coprocessor registers */
3185         return;
3186     }
3187
3188     define_arm_cp_regs(cpu, cp_reginfo);
3189     if (!arm_feature(env, ARM_FEATURE_V8)) {
3190         /* Must go early as it is full of wildcards that may be
3191          * overridden by later definitions.
3192          */
3193         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
3194     }
3195
3196     if (arm_feature(env, ARM_FEATURE_V6)) {
3197         /* The ID registers all have impdef reset values */
3198         ARMCPRegInfo v6_idregs[] = {
3199             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
3200               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
3201               .access = PL1_R, .type = ARM_CP_CONST,
3202               .resetvalue = cpu->id_pfr0 },
3203             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
3204               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
3205               .access = PL1_R, .type = ARM_CP_CONST,
3206               .resetvalue = cpu->id_pfr1 },
3207             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
3208               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
3209               .access = PL1_R, .type = ARM_CP_CONST,
3210               .resetvalue = cpu->id_dfr0 },
3211             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
3212               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
3213               .access = PL1_R, .type = ARM_CP_CONST,
3214               .resetvalue = cpu->id_afr0 },
3215             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
3216               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
3217               .access = PL1_R, .type = ARM_CP_CONST,
3218               .resetvalue = cpu->id_mmfr0 },
3219             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
3220               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
3221               .access = PL1_R, .type = ARM_CP_CONST,
3222               .resetvalue = cpu->id_mmfr1 },
3223             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
3224               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
3225               .access = PL1_R, .type = ARM_CP_CONST,
3226               .resetvalue = cpu->id_mmfr2 },
3227             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
3228               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
3229               .access = PL1_R, .type = ARM_CP_CONST,
3230               .resetvalue = cpu->id_mmfr3 },
3231             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
3232               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
3233               .access = PL1_R, .type = ARM_CP_CONST,
3234               .resetvalue = cpu->id_isar0 },
3235             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
3236               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
3237               .access = PL1_R, .type = ARM_CP_CONST,
3238               .resetvalue = cpu->id_isar1 },
3239             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
3240               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
3241               .access = PL1_R, .type = ARM_CP_CONST,
3242               .resetvalue = cpu->id_isar2 },
3243             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
3244               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
3245               .access = PL1_R, .type = ARM_CP_CONST,
3246               .resetvalue = cpu->id_isar3 },
3247             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
3248               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
3249               .access = PL1_R, .type = ARM_CP_CONST,
3250               .resetvalue = cpu->id_isar4 },
3251             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
3252               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
3253               .access = PL1_R, .type = ARM_CP_CONST,
3254               .resetvalue = cpu->id_isar5 },
3255             /* 6..7 are as yet unallocated and must RAZ */
3256             { .name = "ID_ISAR6", .cp = 15, .crn = 0, .crm = 2,
3257               .opc1 = 0, .opc2 = 6, .access = PL1_R, .type = ARM_CP_CONST,
3258               .resetvalue = 0 },
3259             { .name = "ID_ISAR7", .cp = 15, .crn = 0, .crm = 2,
3260               .opc1 = 0, .opc2 = 7, .access = PL1_R, .type = ARM_CP_CONST,
3261               .resetvalue = 0 },
3262             REGINFO_SENTINEL
3263         };
3264         define_arm_cp_regs(cpu, v6_idregs);
3265         define_arm_cp_regs(cpu, v6_cp_reginfo);
3266     } else {
3267         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
3268     }
3269     if (arm_feature(env, ARM_FEATURE_V6K)) {
3270         define_arm_cp_regs(cpu, v6k_cp_reginfo);
3271     }
3272     if (arm_feature(env, ARM_FEATURE_V7MP) &&
3273         !arm_feature(env, ARM_FEATURE_MPU)) {
3274         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
3275     }
3276     if (arm_feature(env, ARM_FEATURE_V7)) {
3277         /* v7 performance monitor control register: same implementor
3278          * field as main ID register, and we implement only the cycle
3279          * count register.
3280          */
3281 #ifndef CONFIG_USER_ONLY
3282         ARMCPRegInfo pmcr = {
3283             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
3284             .access = PL0_RW,
3285             .type = ARM_CP_IO | ARM_CP_ALIAS,
3286             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
3287             .accessfn = pmreg_access, .writefn = pmcr_write,
3288             .raw_writefn = raw_write,
3289         };
3290         ARMCPRegInfo pmcr64 = {
3291             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
3292             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
3293             .access = PL0_RW, .accessfn = pmreg_access,
3294             .type = ARM_CP_IO,
3295             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
3296             .resetvalue = cpu->midr & 0xff000000,
3297             .writefn = pmcr_write, .raw_writefn = raw_write,
3298         };
3299         define_one_arm_cp_reg(cpu, &pmcr);
3300         define_one_arm_cp_reg(cpu, &pmcr64);
3301 #endif
3302         ARMCPRegInfo clidr = {
3303             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
3304             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
3305             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
3306         };
3307         define_one_arm_cp_reg(cpu, &clidr);
3308         define_arm_cp_regs(cpu, v7_cp_reginfo);
3309         define_debug_regs(cpu);
3310     } else {
3311         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
3312     }
3313     if (arm_feature(env, ARM_FEATURE_V8)) {
3314         /* AArch64 ID registers, which all have impdef reset values */
3315         ARMCPRegInfo v8_idregs[] = {
3316             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
3317               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
3318               .access = PL1_R, .type = ARM_CP_CONST,
3319               .resetvalue = cpu->id_aa64pfr0 },
3320             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
3321               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
3322               .access = PL1_R, .type = ARM_CP_CONST,
3323               .resetvalue = cpu->id_aa64pfr1},
3324             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
3325               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
3326               .access = PL1_R, .type = ARM_CP_CONST,
3327               /* We mask out the PMUVer field, because we don't currently
3328                * implement the PMU. Not advertising it prevents the guest
3329                * from trying to use it and getting UNDEFs on registers we
3330                * don't implement.
3331                */
3332               .resetvalue = cpu->id_aa64dfr0 & ~0xf00 },
3333             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
3334               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
3335               .access = PL1_R, .type = ARM_CP_CONST,
3336               .resetvalue = cpu->id_aa64dfr1 },
3337             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
3338               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
3339               .access = PL1_R, .type = ARM_CP_CONST,
3340               .resetvalue = cpu->id_aa64afr0 },
3341             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
3342               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
3343               .access = PL1_R, .type = ARM_CP_CONST,
3344               .resetvalue = cpu->id_aa64afr1 },
3345             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
3346               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
3347               .access = PL1_R, .type = ARM_CP_CONST,
3348               .resetvalue = cpu->id_aa64isar0 },
3349             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
3350               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
3351               .access = PL1_R, .type = ARM_CP_CONST,
3352               .resetvalue = cpu->id_aa64isar1 },
3353             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
3354               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
3355               .access = PL1_R, .type = ARM_CP_CONST,
3356               .resetvalue = cpu->id_aa64mmfr0 },
3357             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
3358               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
3359               .access = PL1_R, .type = ARM_CP_CONST,
3360               .resetvalue = cpu->id_aa64mmfr1 },
3361             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
3362               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
3363               .access = PL1_R, .type = ARM_CP_CONST,
3364               .resetvalue = cpu->mvfr0 },
3365             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
3366               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
3367               .access = PL1_R, .type = ARM_CP_CONST,
3368               .resetvalue = cpu->mvfr1 },
3369             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
3370               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
3371               .access = PL1_R, .type = ARM_CP_CONST,
3372               .resetvalue = cpu->mvfr2 },
3373             REGINFO_SENTINEL
3374         };
3375         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
3376         if (!arm_feature(env, ARM_FEATURE_EL3) &&
3377             !arm_feature(env, ARM_FEATURE_EL2)) {
3378             ARMCPRegInfo rvbar = {
3379                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
3380                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
3381                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
3382             };
3383             define_one_arm_cp_reg(cpu, &rvbar);
3384         }
3385         define_arm_cp_regs(cpu, v8_idregs);
3386         define_arm_cp_regs(cpu, v8_cp_reginfo);
3387     }
3388     if (arm_feature(env, ARM_FEATURE_EL2)) {
3389         define_arm_cp_regs(cpu, el2_cp_reginfo);
3390         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
3391         if (!arm_feature(env, ARM_FEATURE_EL3)) {
3392             ARMCPRegInfo rvbar = {
3393                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
3394                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
3395                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
3396             };
3397             define_one_arm_cp_reg(cpu, &rvbar);
3398         }
3399     } else {
3400         /* If EL2 is missing but higher ELs are enabled, we need to
3401          * register the no_el2 reginfos.
3402          */
3403         if (arm_feature(env, ARM_FEATURE_EL3)) {
3404             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
3405         }
3406     }
3407     if (arm_feature(env, ARM_FEATURE_EL3)) {
3408         define_arm_cp_regs(cpu, el3_cp_reginfo);
3409         ARMCPRegInfo rvbar = {
3410             .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
3411             .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
3412             .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar
3413         };
3414         define_one_arm_cp_reg(cpu, &rvbar);
3415     }
3416     if (arm_feature(env, ARM_FEATURE_MPU)) {
3417         if (arm_feature(env, ARM_FEATURE_V6)) {
3418             /* PMSAv6 not implemented */
3419             assert(arm_feature(env, ARM_FEATURE_V7));
3420             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
3421             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
3422         } else {
3423             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
3424         }
3425     } else {
3426         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
3427         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
3428     }
3429     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
3430         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
3431     }
3432     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
3433         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
3434     }
3435     if (arm_feature(env, ARM_FEATURE_VAPA)) {
3436         define_arm_cp_regs(cpu, vapa_cp_reginfo);
3437     }
3438     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
3439         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
3440     }
3441     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
3442         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
3443     }
3444     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
3445         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
3446     }
3447     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
3448         define_arm_cp_regs(cpu, omap_cp_reginfo);
3449     }
3450     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
3451         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
3452     }
3453     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
3454         define_arm_cp_regs(cpu, xscale_cp_reginfo);
3455     }
3456     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
3457         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
3458     }
3459     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3460         define_arm_cp_regs(cpu, lpae_cp_reginfo);
3461     }
3462     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
3463      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
3464      * be read-only (ie write causes UNDEF exception).
3465      */
3466     {
3467         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
3468             /* Pre-v8 MIDR space.
3469              * Note that the MIDR isn't a simple constant register because
3470              * of the TI925 behaviour where writes to another register can
3471              * cause the MIDR value to change.
3472              *
3473              * Unimplemented registers in the c15 0 0 0 space default to
3474              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
3475              * and friends override accordingly.
3476              */
3477             { .name = "MIDR",
3478               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
3479               .access = PL1_R, .resetvalue = cpu->midr,
3480               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
3481               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
3482               .type = ARM_CP_OVERRIDE },
3483             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
3484             { .name = "DUMMY",
3485               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
3486               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
3487             { .name = "DUMMY",
3488               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
3489               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
3490             { .name = "DUMMY",
3491               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
3492               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
3493             { .name = "DUMMY",
3494               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
3495               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
3496             { .name = "DUMMY",
3497               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
3498               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
3499             REGINFO_SENTINEL
3500         };
3501         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
3502             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
3503               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
3504               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->midr },
3505             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
3506             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
3507               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
3508               .access = PL1_R, .resetvalue = cpu->midr },
3509             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
3510               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
3511               .access = PL1_R, .resetvalue = cpu->midr },
3512             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
3513               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
3514               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
3515             REGINFO_SENTINEL
3516         };
3517         ARMCPRegInfo id_cp_reginfo[] = {
3518             /* These are common to v8 and pre-v8 */
3519             { .name = "CTR",
3520               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
3521               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
3522             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
3523               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
3524               .access = PL0_R, .accessfn = ctr_el0_access,
3525               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
3526             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
3527             { .name = "TCMTR",
3528               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
3529               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
3530             REGINFO_SENTINEL
3531         };
3532         /* TLBTR is specific to VMSA */
3533         ARMCPRegInfo id_tlbtr_reginfo = {
3534               .name = "TLBTR",
3535               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
3536               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
3537         };
3538         /* MPUIR is specific to PMSA V6+ */
3539         ARMCPRegInfo id_mpuir_reginfo = {
3540               .name = "MPUIR",
3541               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
3542               .access = PL1_R, .type = ARM_CP_CONST,
3543               .resetvalue = cpu->pmsav7_dregion << 8
3544         };
3545         ARMCPRegInfo crn0_wi_reginfo = {
3546             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
3547             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
3548             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
3549         };
3550         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
3551             arm_feature(env, ARM_FEATURE_STRONGARM)) {
3552             ARMCPRegInfo *r;
3553             /* Register the blanket "writes ignored" value first to cover the
3554              * whole space. Then update the specific ID registers to allow write
3555              * access, so that they ignore writes rather than causing them to
3556              * UNDEF.
3557              */
3558             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
3559             for (r = id_pre_v8_midr_cp_reginfo;
3560                  r->type != ARM_CP_SENTINEL; r++) {
3561                 r->access = PL1_RW;
3562             }
3563             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
3564                 r->access = PL1_RW;
3565             }
3566             id_tlbtr_reginfo.access = PL1_RW;
3567             id_tlbtr_reginfo.access = PL1_RW;
3568         }
3569         if (arm_feature(env, ARM_FEATURE_V8)) {
3570             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
3571         } else {
3572             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
3573         }
3574         define_arm_cp_regs(cpu, id_cp_reginfo);
3575         if (!arm_feature(env, ARM_FEATURE_MPU)) {
3576             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
3577         } else if (arm_feature(env, ARM_FEATURE_V7)) {
3578             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
3579         }
3580     }
3581
3582     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
3583         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
3584     }
3585
3586     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
3587         ARMCPRegInfo auxcr = {
3588             .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
3589             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
3590             .access = PL1_RW, .type = ARM_CP_CONST,
3591             .resetvalue = cpu->reset_auxcr
3592         };
3593         define_one_arm_cp_reg(cpu, &auxcr);
3594     }
3595
3596     if (arm_feature(env, ARM_FEATURE_CBAR)) {
3597         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
3598             /* 32 bit view is [31:18] 0...0 [43:32]. */
3599             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
3600                 | extract64(cpu->reset_cbar, 32, 12);
3601             ARMCPRegInfo cbar_reginfo[] = {
3602                 { .name = "CBAR",
3603                   .type = ARM_CP_CONST,
3604                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
3605                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
3606                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
3607                   .type = ARM_CP_CONST,
3608                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
3609                   .access = PL1_R, .resetvalue = cbar32 },
3610                 REGINFO_SENTINEL
3611             };
3612             /* We don't implement a r/w 64 bit CBAR currently */
3613             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
3614             define_arm_cp_regs(cpu, cbar_reginfo);
3615         } else {
3616             ARMCPRegInfo cbar = {
3617                 .name = "CBAR",
3618                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
3619                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
3620                 .fieldoffset = offsetof(CPUARMState,
3621                                         cp15.c15_config_base_address)
3622             };
3623             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
3624                 cbar.access = PL1_R;
3625                 cbar.fieldoffset = 0;
3626                 cbar.type = ARM_CP_CONST;
3627             }
3628             define_one_arm_cp_reg(cpu, &cbar);
3629         }
3630     }
3631
3632     /* Generic registers whose values depend on the implementation */
3633     {
3634         ARMCPRegInfo sctlr = {
3635             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
3636             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
3637             .access = PL1_RW,
3638             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
3639                                    offsetof(CPUARMState, cp15.sctlr_ns) },
3640             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
3641             .raw_writefn = raw_write,
3642         };
3643         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
3644             /* Normally we would always end the TB on an SCTLR write, but Linux
3645              * arch/arm/mach-pxa/sleep.S expects two instructions following
3646              * an MMU enable to execute from cache.  Imitate this behaviour.
3647              */
3648             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
3649         }
3650         define_one_arm_cp_reg(cpu, &sctlr);
3651     }
3652 }
3653
3654 ARMCPU *cpu_arm_init(const char *cpu_model)
3655 {
3656     return ARM_CPU(cpu_generic_init(TYPE_ARM_CPU, cpu_model));
3657 }
3658
3659 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
3660 {
3661     CPUState *cs = CPU(cpu);
3662     CPUARMState *env = &cpu->env;
3663
3664     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
3665         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
3666                                  aarch64_fpu_gdb_set_reg,
3667                                  34, "aarch64-fpu.xml", 0);
3668     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
3669         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
3670                                  51, "arm-neon.xml", 0);
3671     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
3672         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
3673                                  35, "arm-vfp3.xml", 0);
3674     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
3675         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
3676                                  19, "arm-vfp.xml", 0);
3677     }
3678 }
3679
3680 /* Sort alphabetically by type name, except for "any". */
3681 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
3682 {
3683     ObjectClass *class_a = (ObjectClass *)a;
3684     ObjectClass *class_b = (ObjectClass *)b;
3685     const char *name_a, *name_b;
3686
3687     name_a = object_class_get_name(class_a);
3688     name_b = object_class_get_name(class_b);
3689     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
3690         return 1;
3691     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
3692         return -1;
3693     } else {
3694         return strcmp(name_a, name_b);
3695     }
3696 }
3697
3698 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
3699 {
3700     ObjectClass *oc = data;
3701     CPUListState *s = user_data;
3702     const char *typename;
3703     char *name;
3704
3705     typename = object_class_get_name(oc);
3706     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
3707     (*s->cpu_fprintf)(s->file, "  %s\n",
3708                       name);
3709     g_free(name);
3710 }
3711
3712 void arm_cpu_list(FILE *f, fprintf_function cpu_fprintf)
3713 {
3714     CPUListState s = {
3715         .file = f,
3716         .cpu_fprintf = cpu_fprintf,
3717     };
3718     GSList *list;
3719
3720     list = object_class_get_list(TYPE_ARM_CPU, false);
3721     list = g_slist_sort(list, arm_cpu_list_compare);
3722     (*cpu_fprintf)(f, "Available CPUs:\n");
3723     g_slist_foreach(list, arm_cpu_list_entry, &s);
3724     g_slist_free(list);
3725 #ifdef CONFIG_KVM
3726     /* The 'host' CPU type is dynamically registered only if KVM is
3727      * enabled, so we have to special-case it here:
3728      */
3729     (*cpu_fprintf)(f, "  host (only available in KVM mode)\n");
3730 #endif
3731 }
3732
3733 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
3734 {
3735     ObjectClass *oc = data;
3736     CpuDefinitionInfoList **cpu_list = user_data;
3737     CpuDefinitionInfoList *entry;
3738     CpuDefinitionInfo *info;
3739     const char *typename;
3740
3741     typename = object_class_get_name(oc);
3742     info = g_malloc0(sizeof(*info));
3743     info->name = g_strndup(typename,
3744                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
3745
3746     entry = g_malloc0(sizeof(*entry));
3747     entry->value = info;
3748     entry->next = *cpu_list;
3749     *cpu_list = entry;
3750 }
3751
3752 CpuDefinitionInfoList *arch_query_cpu_definitions(Error **errp)
3753 {
3754     CpuDefinitionInfoList *cpu_list = NULL;
3755     GSList *list;
3756
3757     list = object_class_get_list(TYPE_ARM_CPU, false);
3758     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
3759     g_slist_free(list);
3760
3761     return cpu_list;
3762 }
3763
3764 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
3765                                    void *opaque, int state, int secstate,
3766                                    int crm, int opc1, int opc2)
3767 {
3768     /* Private utility function for define_one_arm_cp_reg_with_opaque():
3769      * add a single reginfo struct to the hash table.
3770      */
3771     uint32_t *key = g_new(uint32_t, 1);
3772     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
3773     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
3774     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
3775
3776     /* Reset the secure state to the specific incoming state.  This is
3777      * necessary as the register may have been defined with both states.
3778      */
3779     r2->secure = secstate;
3780
3781     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
3782         /* Register is banked (using both entries in array).
3783          * Overwriting fieldoffset as the array is only used to define
3784          * banked registers but later only fieldoffset is used.
3785          */
3786         r2->fieldoffset = r->bank_fieldoffsets[ns];
3787     }
3788
3789     if (state == ARM_CP_STATE_AA32) {
3790         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
3791             /* If the register is banked then we don't need to migrate or
3792              * reset the 32-bit instance in certain cases:
3793              *
3794              * 1) If the register has both 32-bit and 64-bit instances then we
3795              *    can count on the 64-bit instance taking care of the
3796              *    non-secure bank.
3797              * 2) If ARMv8 is enabled then we can count on a 64-bit version
3798              *    taking care of the secure bank.  This requires that separate
3799              *    32 and 64-bit definitions are provided.
3800              */
3801             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
3802                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
3803                 r2->type |= ARM_CP_ALIAS;
3804             }
3805         } else if ((secstate != r->secure) && !ns) {
3806             /* The register is not banked so we only want to allow migration of
3807              * the non-secure instance.
3808              */
3809             r2->type |= ARM_CP_ALIAS;
3810         }
3811
3812         if (r->state == ARM_CP_STATE_BOTH) {
3813             /* We assume it is a cp15 register if the .cp field is left unset.
3814              */
3815             if (r2->cp == 0) {
3816                 r2->cp = 15;
3817             }
3818
3819 #ifdef HOST_WORDS_BIGENDIAN
3820             if (r2->fieldoffset) {
3821                 r2->fieldoffset += sizeof(uint32_t);
3822             }
3823 #endif
3824         }
3825     }
3826     if (state == ARM_CP_STATE_AA64) {
3827         /* To allow abbreviation of ARMCPRegInfo
3828          * definitions, we treat cp == 0 as equivalent to
3829          * the value for "standard guest-visible sysreg".
3830          * STATE_BOTH definitions are also always "standard
3831          * sysreg" in their AArch64 view (the .cp value may
3832          * be non-zero for the benefit of the AArch32 view).
3833          */
3834         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
3835             r2->cp = CP_REG_ARM64_SYSREG_CP;
3836         }
3837         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
3838                                   r2->opc0, opc1, opc2);
3839     } else {
3840         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
3841     }
3842     if (opaque) {
3843         r2->opaque = opaque;
3844     }
3845     /* reginfo passed to helpers is correct for the actual access,
3846      * and is never ARM_CP_STATE_BOTH:
3847      */
3848     r2->state = state;
3849     /* Make sure reginfo passed to helpers for wildcarded regs
3850      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
3851      */
3852     r2->crm = crm;
3853     r2->opc1 = opc1;
3854     r2->opc2 = opc2;
3855     /* By convention, for wildcarded registers only the first
3856      * entry is used for migration; the others are marked as
3857      * ALIAS so we don't try to transfer the register
3858      * multiple times. Special registers (ie NOP/WFI) are
3859      * never migratable and not even raw-accessible.
3860      */
3861     if ((r->type & ARM_CP_SPECIAL)) {
3862         r2->type |= ARM_CP_NO_RAW;
3863     }
3864     if (((r->crm == CP_ANY) && crm != 0) ||
3865         ((r->opc1 == CP_ANY) && opc1 != 0) ||
3866         ((r->opc2 == CP_ANY) && opc2 != 0)) {
3867         r2->type |= ARM_CP_ALIAS;
3868     }
3869
3870     /* Check that raw accesses are either forbidden or handled. Note that
3871      * we can't assert this earlier because the setup of fieldoffset for
3872      * banked registers has to be done first.
3873      */
3874     if (!(r2->type & ARM_CP_NO_RAW)) {
3875         assert(!raw_accessors_invalid(r2));
3876     }
3877
3878     /* Overriding of an existing definition must be explicitly
3879      * requested.
3880      */
3881     if (!(r->type & ARM_CP_OVERRIDE)) {
3882         ARMCPRegInfo *oldreg;
3883         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
3884         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
3885             fprintf(stderr, "Register redefined: cp=%d %d bit "
3886                     "crn=%d crm=%d opc1=%d opc2=%d, "
3887                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
3888                     r2->crn, r2->crm, r2->opc1, r2->opc2,
3889                     oldreg->name, r2->name);
3890             g_assert_not_reached();
3891         }
3892     }
3893     g_hash_table_insert(cpu->cp_regs, key, r2);
3894 }
3895
3896
3897 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
3898                                        const ARMCPRegInfo *r, void *opaque)
3899 {
3900     /* Define implementations of coprocessor registers.
3901      * We store these in a hashtable because typically
3902      * there are less than 150 registers in a space which
3903      * is 16*16*16*8*8 = 262144 in size.
3904      * Wildcarding is supported for the crm, opc1 and opc2 fields.
3905      * If a register is defined twice then the second definition is
3906      * used, so this can be used to define some generic registers and
3907      * then override them with implementation specific variations.
3908      * At least one of the original and the second definition should
3909      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
3910      * against accidental use.
3911      *
3912      * The state field defines whether the register is to be
3913      * visible in the AArch32 or AArch64 execution state. If the
3914      * state is set to ARM_CP_STATE_BOTH then we synthesise a
3915      * reginfo structure for the AArch32 view, which sees the lower
3916      * 32 bits of the 64 bit register.
3917      *
3918      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
3919      * be wildcarded. AArch64 registers are always considered to be 64
3920      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
3921      * the register, if any.
3922      */
3923     int crm, opc1, opc2, state;
3924     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
3925     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
3926     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
3927     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
3928     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
3929     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
3930     /* 64 bit registers have only CRm and Opc1 fields */
3931     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
3932     /* op0 only exists in the AArch64 encodings */
3933     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
3934     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
3935     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
3936     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
3937      * encodes a minimum access level for the register. We roll this
3938      * runtime check into our general permission check code, so check
3939      * here that the reginfo's specified permissions are strict enough
3940      * to encompass the generic architectural permission check.
3941      */
3942     if (r->state != ARM_CP_STATE_AA32) {
3943         int mask = 0;
3944         switch (r->opc1) {
3945         case 0: case 1: case 2:
3946             /* min_EL EL1 */
3947             mask = PL1_RW;
3948             break;
3949         case 3:
3950             /* min_EL EL0 */
3951             mask = PL0_RW;
3952             break;
3953         case 4:
3954             /* min_EL EL2 */
3955             mask = PL2_RW;
3956             break;
3957         case 5:
3958             /* unallocated encoding, so not possible */
3959             assert(false);
3960             break;
3961         case 6:
3962             /* min_EL EL3 */
3963             mask = PL3_RW;
3964             break;
3965         case 7:
3966             /* min_EL EL1, secure mode only (we don't check the latter) */
3967             mask = PL1_RW;
3968             break;
3969         default:
3970             /* broken reginfo with out-of-range opc1 */
3971             assert(false);
3972             break;
3973         }
3974         /* assert our permissions are not too lax (stricter is fine) */
3975         assert((r->access & ~mask) == 0);
3976     }
3977
3978     /* Check that the register definition has enough info to handle
3979      * reads and writes if they are permitted.
3980      */
3981     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
3982         if (r->access & PL3_R) {
3983             assert((r->fieldoffset ||
3984                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
3985                    r->readfn);
3986         }
3987         if (r->access & PL3_W) {
3988             assert((r->fieldoffset ||
3989                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
3990                    r->writefn);
3991         }
3992     }
3993     /* Bad type field probably means missing sentinel at end of reg list */
3994     assert(cptype_valid(r->type));
3995     for (crm = crmmin; crm <= crmmax; crm++) {
3996         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
3997             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
3998                 for (state = ARM_CP_STATE_AA32;
3999                      state <= ARM_CP_STATE_AA64; state++) {
4000                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
4001                         continue;
4002                     }
4003                     if (state == ARM_CP_STATE_AA32) {
4004                         /* Under AArch32 CP registers can be common
4005                          * (same for secure and non-secure world) or banked.
4006                          */
4007                         switch (r->secure) {
4008                         case ARM_CP_SECSTATE_S:
4009                         case ARM_CP_SECSTATE_NS:
4010                             add_cpreg_to_hashtable(cpu, r, opaque, state,
4011                                                    r->secure, crm, opc1, opc2);
4012                             break;
4013                         default:
4014                             add_cpreg_to_hashtable(cpu, r, opaque, state,
4015                                                    ARM_CP_SECSTATE_S,
4016                                                    crm, opc1, opc2);
4017                             add_cpreg_to_hashtable(cpu, r, opaque, state,
4018                                                    ARM_CP_SECSTATE_NS,
4019                                                    crm, opc1, opc2);
4020                             break;
4021                         }
4022                     } else {
4023                         /* AArch64 registers get mapped to non-secure instance
4024                          * of AArch32 */
4025                         add_cpreg_to_hashtable(cpu, r, opaque, state,
4026                                                ARM_CP_SECSTATE_NS,
4027                                                crm, opc1, opc2);
4028                     }
4029                 }
4030             }
4031         }
4032     }
4033 }
4034
4035 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
4036                                     const ARMCPRegInfo *regs, void *opaque)
4037 {
4038     /* Define a whole list of registers */
4039     const ARMCPRegInfo *r;
4040     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
4041         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
4042     }
4043 }
4044
4045 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
4046 {
4047     return g_hash_table_lookup(cpregs, &encoded_cp);
4048 }
4049
4050 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
4051                          uint64_t value)
4052 {
4053     /* Helper coprocessor write function for write-ignore registers */
4054 }
4055
4056 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
4057 {
4058     /* Helper coprocessor write function for read-as-zero registers */
4059     return 0;
4060 }
4061
4062 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
4063 {
4064     /* Helper coprocessor reset function for do-nothing-on-reset registers */
4065 }
4066
4067 static int bad_mode_switch(CPUARMState *env, int mode)
4068 {
4069     /* Return true if it is not valid for us to switch to
4070      * this CPU mode (ie all the UNPREDICTABLE cases in
4071      * the ARM ARM CPSRWriteByInstr pseudocode).
4072      */
4073     switch (mode) {
4074     case ARM_CPU_MODE_USR:
4075     case ARM_CPU_MODE_SYS:
4076     case ARM_CPU_MODE_SVC:
4077     case ARM_CPU_MODE_ABT:
4078     case ARM_CPU_MODE_UND:
4079     case ARM_CPU_MODE_IRQ:
4080     case ARM_CPU_MODE_FIQ:
4081         return 0;
4082     case ARM_CPU_MODE_MON:
4083         return !arm_is_secure(env);
4084     default:
4085         return 1;
4086     }
4087 }
4088
4089 uint32_t cpsr_read(CPUARMState *env)
4090 {
4091     int ZF;
4092     ZF = (env->ZF == 0);
4093     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
4094         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
4095         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
4096         | ((env->condexec_bits & 0xfc) << 8)
4097         | (env->GE << 16) | (env->daif & CPSR_AIF);
4098 }
4099
4100 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask)
4101 {
4102     uint32_t changed_daif;
4103
4104     if (mask & CPSR_NZCV) {
4105         env->ZF = (~val) & CPSR_Z;
4106         env->NF = val;
4107         env->CF = (val >> 29) & 1;
4108         env->VF = (val << 3) & 0x80000000;
4109     }
4110     if (mask & CPSR_Q)
4111         env->QF = ((val & CPSR_Q) != 0);
4112     if (mask & CPSR_T)
4113         env->thumb = ((val & CPSR_T) != 0);
4114     if (mask & CPSR_IT_0_1) {
4115         env->condexec_bits &= ~3;
4116         env->condexec_bits |= (val >> 25) & 3;
4117     }
4118     if (mask & CPSR_IT_2_7) {
4119         env->condexec_bits &= 3;
4120         env->condexec_bits |= (val >> 8) & 0xfc;
4121     }
4122     if (mask & CPSR_GE) {
4123         env->GE = (val >> 16) & 0xf;
4124     }
4125
4126     /* In a V7 implementation that includes the security extensions but does
4127      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
4128      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
4129      * bits respectively.
4130      *
4131      * In a V8 implementation, it is permitted for privileged software to
4132      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
4133      */
4134     if (!arm_feature(env, ARM_FEATURE_V8) &&
4135         arm_feature(env, ARM_FEATURE_EL3) &&
4136         !arm_feature(env, ARM_FEATURE_EL2) &&
4137         !arm_is_secure(env)) {
4138
4139         changed_daif = (env->daif ^ val) & mask;
4140
4141         if (changed_daif & CPSR_A) {
4142             /* Check to see if we are allowed to change the masking of async
4143              * abort exceptions from a non-secure state.
4144              */
4145             if (!(env->cp15.scr_el3 & SCR_AW)) {
4146                 qemu_log_mask(LOG_GUEST_ERROR,
4147                               "Ignoring attempt to switch CPSR_A flag from "
4148                               "non-secure world with SCR.AW bit clear\n");
4149                 mask &= ~CPSR_A;
4150             }
4151         }
4152
4153         if (changed_daif & CPSR_F) {
4154             /* Check to see if we are allowed to change the masking of FIQ
4155              * exceptions from a non-secure state.
4156              */
4157             if (!(env->cp15.scr_el3 & SCR_FW)) {
4158                 qemu_log_mask(LOG_GUEST_ERROR,
4159                               "Ignoring attempt to switch CPSR_F flag from "
4160                               "non-secure world with SCR.FW bit clear\n");
4161                 mask &= ~CPSR_F;
4162             }
4163
4164             /* Check whether non-maskable FIQ (NMFI) support is enabled.
4165              * If this bit is set software is not allowed to mask
4166              * FIQs, but is allowed to set CPSR_F to 0.
4167              */
4168             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
4169                 (val & CPSR_F)) {
4170                 qemu_log_mask(LOG_GUEST_ERROR,
4171                               "Ignoring attempt to enable CPSR_F flag "
4172                               "(non-maskable FIQ [NMFI] support enabled)\n");
4173                 mask &= ~CPSR_F;
4174             }
4175         }
4176     }
4177
4178     env->daif &= ~(CPSR_AIF & mask);
4179     env->daif |= val & CPSR_AIF & mask;
4180
4181     if ((env->uncached_cpsr ^ val) & mask & CPSR_M) {
4182         if (bad_mode_switch(env, val & CPSR_M)) {
4183             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE.
4184              * We choose to ignore the attempt and leave the CPSR M field
4185              * untouched.
4186              */
4187             mask &= ~CPSR_M;
4188         } else {
4189             switch_mode(env, val & CPSR_M);
4190         }
4191     }
4192     mask &= ~CACHED_CPSR_BITS;
4193     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
4194 }
4195
4196 /* Sign/zero extend */
4197 uint32_t HELPER(sxtb16)(uint32_t x)
4198 {
4199     uint32_t res;
4200     res = (uint16_t)(int8_t)x;
4201     res |= (uint32_t)(int8_t)(x >> 16) << 16;
4202     return res;
4203 }
4204
4205 uint32_t HELPER(uxtb16)(uint32_t x)
4206 {
4207     uint32_t res;
4208     res = (uint16_t)(uint8_t)x;
4209     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
4210     return res;
4211 }
4212
4213 uint32_t HELPER(clz)(uint32_t x)
4214 {
4215     return clz32(x);
4216 }
4217
4218 int32_t HELPER(sdiv)(int32_t num, int32_t den)
4219 {
4220     if (den == 0)
4221       return 0;
4222     if (num == INT_MIN && den == -1)
4223       return INT_MIN;
4224     return num / den;
4225 }
4226
4227 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
4228 {
4229     if (den == 0)
4230       return 0;
4231     return num / den;
4232 }
4233
4234 uint32_t HELPER(rbit)(uint32_t x)
4235 {
4236     x =  ((x & 0xff000000) >> 24)
4237        | ((x & 0x00ff0000) >> 8)
4238        | ((x & 0x0000ff00) << 8)
4239        | ((x & 0x000000ff) << 24);
4240     x =  ((x & 0xf0f0f0f0) >> 4)
4241        | ((x & 0x0f0f0f0f) << 4);
4242     x =  ((x & 0x88888888) >> 3)
4243        | ((x & 0x44444444) >> 1)
4244        | ((x & 0x22222222) << 1)
4245        | ((x & 0x11111111) << 3);
4246     return x;
4247 }
4248
4249 #if defined(CONFIG_USER_ONLY)
4250
4251 /* These should probably raise undefined insn exceptions.  */
4252 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
4253 {
4254     ARMCPU *cpu = arm_env_get_cpu(env);
4255
4256     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
4257 }
4258
4259 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
4260 {
4261     ARMCPU *cpu = arm_env_get_cpu(env);
4262
4263     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
4264     return 0;
4265 }
4266
4267 void switch_mode(CPUARMState *env, int mode)
4268 {
4269     ARMCPU *cpu = arm_env_get_cpu(env);
4270
4271     if (mode != ARM_CPU_MODE_USR) {
4272         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
4273     }
4274 }
4275
4276 void HELPER(set_r13_banked)(CPUARMState *env, uint32_t mode, uint32_t val)
4277 {
4278     ARMCPU *cpu = arm_env_get_cpu(env);
4279
4280     cpu_abort(CPU(cpu), "banked r13 write\n");
4281 }
4282
4283 uint32_t HELPER(get_r13_banked)(CPUARMState *env, uint32_t mode)
4284 {
4285     ARMCPU *cpu = arm_env_get_cpu(env);
4286
4287     cpu_abort(CPU(cpu), "banked r13 read\n");
4288     return 0;
4289 }
4290
4291 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
4292                                  uint32_t cur_el, bool secure)
4293 {
4294     return 1;
4295 }
4296
4297 void aarch64_sync_64_to_32(CPUARMState *env)
4298 {
4299     g_assert_not_reached();
4300 }
4301
4302 #else
4303
4304 /* Map CPU modes onto saved register banks.  */
4305 int bank_number(int mode)
4306 {
4307     switch (mode) {
4308     case ARM_CPU_MODE_USR:
4309     case ARM_CPU_MODE_SYS:
4310         return 0;
4311     case ARM_CPU_MODE_SVC:
4312         return 1;
4313     case ARM_CPU_MODE_ABT:
4314         return 2;
4315     case ARM_CPU_MODE_UND:
4316         return 3;
4317     case ARM_CPU_MODE_IRQ:
4318         return 4;
4319     case ARM_CPU_MODE_FIQ:
4320         return 5;
4321     case ARM_CPU_MODE_HYP:
4322         return 6;
4323     case ARM_CPU_MODE_MON:
4324         return 7;
4325     }
4326     hw_error("bank number requested for bad CPSR mode value 0x%x\n", mode);
4327 }
4328
4329 void switch_mode(CPUARMState *env, int mode)
4330 {
4331     int old_mode;
4332     int i;
4333
4334     old_mode = env->uncached_cpsr & CPSR_M;
4335     if (mode == old_mode)
4336         return;
4337
4338     if (old_mode == ARM_CPU_MODE_FIQ) {
4339         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
4340         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
4341     } else if (mode == ARM_CPU_MODE_FIQ) {
4342         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
4343         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
4344     }
4345
4346     i = bank_number(old_mode);
4347     env->banked_r13[i] = env->regs[13];
4348     env->banked_r14[i] = env->regs[14];
4349     env->banked_spsr[i] = env->spsr;
4350
4351     i = bank_number(mode);
4352     env->regs[13] = env->banked_r13[i];
4353     env->regs[14] = env->banked_r14[i];
4354     env->spsr = env->banked_spsr[i];
4355 }
4356
4357 /* Physical Interrupt Target EL Lookup Table
4358  *
4359  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
4360  *
4361  * The below multi-dimensional table is used for looking up the target
4362  * exception level given numerous condition criteria.  Specifically, the
4363  * target EL is based on SCR and HCR routing controls as well as the
4364  * currently executing EL and secure state.
4365  *
4366  *    Dimensions:
4367  *    target_el_table[2][2][2][2][2][4]
4368  *                    |  |  |  |  |  +--- Current EL
4369  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
4370  *                    |  |  |  +--------- HCR mask override
4371  *                    |  |  +------------ SCR exec state control
4372  *                    |  +--------------- SCR mask override
4373  *                    +------------------ 32-bit(0)/64-bit(1) EL3
4374  *
4375  *    The table values are as such:
4376  *    0-3 = EL0-EL3
4377  *     -1 = Cannot occur
4378  *
4379  * The ARM ARM target EL table includes entries indicating that an "exception
4380  * is not taken".  The two cases where this is applicable are:
4381  *    1) An exception is taken from EL3 but the SCR does not have the exception
4382  *    routed to EL3.
4383  *    2) An exception is taken from EL2 but the HCR does not have the exception
4384  *    routed to EL2.
4385  * In these two cases, the below table contain a target of EL1.  This value is
4386  * returned as it is expected that the consumer of the table data will check
4387  * for "target EL >= current EL" to ensure the exception is not taken.
4388  *
4389  *            SCR     HCR
4390  *         64  EA     AMO                 From
4391  *        BIT IRQ     IMO      Non-secure         Secure
4392  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
4393  */
4394 const int8_t target_el_table[2][2][2][2][2][4] = {
4395     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
4396        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
4397       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
4398        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
4399      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
4400        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
4401       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
4402        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
4403     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
4404        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
4405       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
4406        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
4407      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
4408        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
4409       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
4410        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
4411 };
4412
4413 /*
4414  * Determine the target EL for physical exceptions
4415  */
4416 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
4417                                  uint32_t cur_el, bool secure)
4418 {
4419     CPUARMState *env = cs->env_ptr;
4420     int rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
4421     int scr;
4422     int hcr;
4423     int target_el;
4424     int is64 = arm_el_is_aa64(env, 3);
4425
4426     switch (excp_idx) {
4427     case EXCP_IRQ:
4428         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
4429         hcr = ((env->cp15.hcr_el2 & HCR_IMO) == HCR_IMO);
4430         break;
4431     case EXCP_FIQ:
4432         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
4433         hcr = ((env->cp15.hcr_el2 & HCR_FMO) == HCR_FMO);
4434         break;
4435     default:
4436         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
4437         hcr = ((env->cp15.hcr_el2 & HCR_AMO) == HCR_AMO);
4438         break;
4439     };
4440
4441     /* If HCR.TGE is set then HCR is treated as being 1 */
4442     hcr |= ((env->cp15.hcr_el2 & HCR_TGE) == HCR_TGE);
4443
4444     /* Perform a table-lookup for the target EL given the current state */
4445     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
4446
4447     assert(target_el > 0);
4448
4449     return target_el;
4450 }
4451
4452 static void v7m_push(CPUARMState *env, uint32_t val)
4453 {
4454     CPUState *cs = CPU(arm_env_get_cpu(env));
4455
4456     env->regs[13] -= 4;
4457     stl_phys(cs->as, env->regs[13], val);
4458 }
4459
4460 static uint32_t v7m_pop(CPUARMState *env)
4461 {
4462     CPUState *cs = CPU(arm_env_get_cpu(env));
4463     uint32_t val;
4464
4465     val = ldl_phys(cs->as, env->regs[13]);
4466     env->regs[13] += 4;
4467     return val;
4468 }
4469
4470 /* Switch to V7M main or process stack pointer.  */
4471 static void switch_v7m_sp(CPUARMState *env, int process)
4472 {
4473     uint32_t tmp;
4474     if (env->v7m.current_sp != process) {
4475         tmp = env->v7m.other_sp;
4476         env->v7m.other_sp = env->regs[13];
4477         env->regs[13] = tmp;
4478         env->v7m.current_sp = process;
4479     }
4480 }
4481
4482 static void do_v7m_exception_exit(CPUARMState *env)
4483 {
4484     uint32_t type;
4485     uint32_t xpsr;
4486
4487     type = env->regs[15];
4488     if (env->v7m.exception != 0)
4489         armv7m_nvic_complete_irq(env->nvic, env->v7m.exception);
4490
4491     /* Switch to the target stack.  */
4492     switch_v7m_sp(env, (type & 4) != 0);
4493     /* Pop registers.  */
4494     env->regs[0] = v7m_pop(env);
4495     env->regs[1] = v7m_pop(env);
4496     env->regs[2] = v7m_pop(env);
4497     env->regs[3] = v7m_pop(env);
4498     env->regs[12] = v7m_pop(env);
4499     env->regs[14] = v7m_pop(env);
4500     env->regs[15] = v7m_pop(env);
4501     if (env->regs[15] & 1) {
4502         qemu_log_mask(LOG_GUEST_ERROR,
4503                       "M profile return from interrupt with misaligned "
4504                       "PC is UNPREDICTABLE\n");
4505         /* Actual hardware seems to ignore the lsbit, and there are several
4506          * RTOSes out there which incorrectly assume the r15 in the stack
4507          * frame should be a Thumb-style "lsbit indicates ARM/Thumb" value.
4508          */
4509         env->regs[15] &= ~1U;
4510     }
4511     xpsr = v7m_pop(env);
4512     xpsr_write(env, xpsr, 0xfffffdff);
4513     /* Undo stack alignment.  */
4514     if (xpsr & 0x200)
4515         env->regs[13] |= 4;
4516     /* ??? The exception return type specifies Thread/Handler mode.  However
4517        this is also implied by the xPSR value. Not sure what to do
4518        if there is a mismatch.  */
4519     /* ??? Likewise for mismatches between the CONTROL register and the stack
4520        pointer.  */
4521 }
4522
4523 void arm_v7m_cpu_do_interrupt(CPUState *cs)
4524 {
4525     ARMCPU *cpu = ARM_CPU(cs);
4526     CPUARMState *env = &cpu->env;
4527     uint32_t xpsr = xpsr_read(env);
4528     uint32_t lr;
4529     uint32_t addr;
4530
4531     arm_log_exception(cs->exception_index);
4532
4533     lr = 0xfffffff1;
4534     if (env->v7m.current_sp)
4535         lr |= 4;
4536     if (env->v7m.exception == 0)
4537         lr |= 8;
4538
4539     /* For exceptions we just mark as pending on the NVIC, and let that
4540        handle it.  */
4541     /* TODO: Need to escalate if the current priority is higher than the
4542        one we're raising.  */
4543     switch (cs->exception_index) {
4544     case EXCP_UDEF:
4545         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE);
4546         return;
4547     case EXCP_SWI:
4548         /* The PC already points to the next instruction.  */
4549         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC);
4550         return;
4551     case EXCP_PREFETCH_ABORT:
4552     case EXCP_DATA_ABORT:
4553         /* TODO: if we implemented the MPU registers, this is where we
4554          * should set the MMFAR, etc from exception.fsr and exception.vaddress.
4555          */
4556         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM);
4557         return;
4558     case EXCP_BKPT:
4559         if (semihosting_enabled()) {
4560             int nr;
4561             nr = arm_lduw_code(env, env->regs[15], env->bswap_code) & 0xff;
4562             if (nr == 0xab) {
4563                 env->regs[15] += 2;
4564                 env->regs[0] = do_arm_semihosting(env);
4565                 qemu_log_mask(CPU_LOG_INT, "...handled as semihosting call\n");
4566                 return;
4567             }
4568         }
4569         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG);
4570         return;
4571     case EXCP_IRQ:
4572         env->v7m.exception = armv7m_nvic_acknowledge_irq(env->nvic);
4573         break;
4574     case EXCP_EXCEPTION_EXIT:
4575         do_v7m_exception_exit(env);
4576         return;
4577     default:
4578         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
4579         return; /* Never happens.  Keep compiler happy.  */
4580     }
4581
4582     /* Align stack pointer.  */
4583     /* ??? Should only do this if Configuration Control Register
4584        STACKALIGN bit is set.  */
4585     if (env->regs[13] & 4) {
4586         env->regs[13] -= 4;
4587         xpsr |= 0x200;
4588     }
4589     /* Switch to the handler mode.  */
4590     v7m_push(env, xpsr);
4591     v7m_push(env, env->regs[15]);
4592     v7m_push(env, env->regs[14]);
4593     v7m_push(env, env->regs[12]);
4594     v7m_push(env, env->regs[3]);
4595     v7m_push(env, env->regs[2]);
4596     v7m_push(env, env->regs[1]);
4597     v7m_push(env, env->regs[0]);
4598     switch_v7m_sp(env, 0);
4599     /* Clear IT bits */
4600     env->condexec_bits = 0;
4601     env->regs[14] = lr;
4602     addr = ldl_phys(cs->as, env->v7m.vecbase + env->v7m.exception * 4);
4603     env->regs[15] = addr & 0xfffffffe;
4604     env->thumb = addr & 1;
4605 }
4606
4607 /* Function used to synchronize QEMU's AArch64 register set with AArch32
4608  * register set.  This is necessary when switching between AArch32 and AArch64
4609  * execution state.
4610  */
4611 void aarch64_sync_32_to_64(CPUARMState *env)
4612 {
4613     int i;
4614     uint32_t mode = env->uncached_cpsr & CPSR_M;
4615
4616     /* We can blanket copy R[0:7] to X[0:7] */
4617     for (i = 0; i < 8; i++) {
4618         env->xregs[i] = env->regs[i];
4619     }
4620
4621     /* Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
4622      * Otherwise, they come from the banked user regs.
4623      */
4624     if (mode == ARM_CPU_MODE_FIQ) {
4625         for (i = 8; i < 13; i++) {
4626             env->xregs[i] = env->usr_regs[i - 8];
4627         }
4628     } else {
4629         for (i = 8; i < 13; i++) {
4630             env->xregs[i] = env->regs[i];
4631         }
4632     }
4633
4634     /* Registers x13-x23 are the various mode SP and FP registers. Registers
4635      * r13 and r14 are only copied if we are in that mode, otherwise we copy
4636      * from the mode banked register.
4637      */
4638     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
4639         env->xregs[13] = env->regs[13];
4640         env->xregs[14] = env->regs[14];
4641     } else {
4642         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
4643         /* HYP is an exception in that it is copied from r14 */
4644         if (mode == ARM_CPU_MODE_HYP) {
4645             env->xregs[14] = env->regs[14];
4646         } else {
4647             env->xregs[14] = env->banked_r14[bank_number(ARM_CPU_MODE_USR)];
4648         }
4649     }
4650
4651     if (mode == ARM_CPU_MODE_HYP) {
4652         env->xregs[15] = env->regs[13];
4653     } else {
4654         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
4655     }
4656
4657     if (mode == ARM_CPU_MODE_IRQ) {
4658         env->xregs[16] = env->regs[13];
4659         env->xregs[17] = env->regs[14];
4660     } else {
4661         env->xregs[16] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
4662         env->xregs[17] = env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)];
4663     }
4664
4665     if (mode == ARM_CPU_MODE_SVC) {
4666         env->xregs[18] = env->regs[13];
4667         env->xregs[19] = env->regs[14];
4668     } else {
4669         env->xregs[18] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
4670         env->xregs[19] = env->banked_r14[bank_number(ARM_CPU_MODE_SVC)];
4671     }
4672
4673     if (mode == ARM_CPU_MODE_ABT) {
4674         env->xregs[20] = env->regs[13];
4675         env->xregs[21] = env->regs[14];
4676     } else {
4677         env->xregs[20] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
4678         env->xregs[21] = env->banked_r14[bank_number(ARM_CPU_MODE_ABT)];
4679     }
4680
4681     if (mode == ARM_CPU_MODE_UND) {
4682         env->xregs[22] = env->regs[13];
4683         env->xregs[23] = env->regs[14];
4684     } else {
4685         env->xregs[22] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
4686         env->xregs[23] = env->banked_r14[bank_number(ARM_CPU_MODE_UND)];
4687     }
4688
4689     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
4690      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
4691      * FIQ bank for r8-r14.
4692      */
4693     if (mode == ARM_CPU_MODE_FIQ) {
4694         for (i = 24; i < 31; i++) {
4695             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
4696         }
4697     } else {
4698         for (i = 24; i < 29; i++) {
4699             env->xregs[i] = env->fiq_regs[i - 24];
4700         }
4701         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
4702         env->xregs[30] = env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)];
4703     }
4704
4705     env->pc = env->regs[15];
4706 }
4707
4708 /* Function used to synchronize QEMU's AArch32 register set with AArch64
4709  * register set.  This is necessary when switching between AArch32 and AArch64
4710  * execution state.
4711  */
4712 void aarch64_sync_64_to_32(CPUARMState *env)
4713 {
4714     int i;
4715     uint32_t mode = env->uncached_cpsr & CPSR_M;
4716
4717     /* We can blanket copy X[0:7] to R[0:7] */
4718     for (i = 0; i < 8; i++) {
4719         env->regs[i] = env->xregs[i];
4720     }
4721
4722     /* Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
4723      * Otherwise, we copy x8-x12 into the banked user regs.
4724      */
4725     if (mode == ARM_CPU_MODE_FIQ) {
4726         for (i = 8; i < 13; i++) {
4727             env->usr_regs[i - 8] = env->xregs[i];
4728         }
4729     } else {
4730         for (i = 8; i < 13; i++) {
4731             env->regs[i] = env->xregs[i];
4732         }
4733     }
4734
4735     /* Registers r13 & r14 depend on the current mode.
4736      * If we are in a given mode, we copy the corresponding x registers to r13
4737      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
4738      * for the mode.
4739      */
4740     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
4741         env->regs[13] = env->xregs[13];
4742         env->regs[14] = env->xregs[14];
4743     } else {
4744         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
4745
4746         /* HYP is an exception in that it does not have its own banked r14 but
4747          * shares the USR r14
4748          */
4749         if (mode == ARM_CPU_MODE_HYP) {
4750             env->regs[14] = env->xregs[14];
4751         } else {
4752             env->banked_r14[bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
4753         }
4754     }
4755
4756     if (mode == ARM_CPU_MODE_HYP) {
4757         env->regs[13] = env->xregs[15];
4758     } else {
4759         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
4760     }
4761
4762     if (mode == ARM_CPU_MODE_IRQ) {
4763         env->regs[13] = env->xregs[16];
4764         env->regs[14] = env->xregs[17];
4765     } else {
4766         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
4767         env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
4768     }
4769
4770     if (mode == ARM_CPU_MODE_SVC) {
4771         env->regs[13] = env->xregs[18];
4772         env->regs[14] = env->xregs[19];
4773     } else {
4774         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
4775         env->banked_r14[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
4776     }
4777
4778     if (mode == ARM_CPU_MODE_ABT) {
4779         env->regs[13] = env->xregs[20];
4780         env->regs[14] = env->xregs[21];
4781     } else {
4782         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
4783         env->banked_r14[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
4784     }
4785
4786     if (mode == ARM_CPU_MODE_UND) {
4787         env->regs[13] = env->xregs[22];
4788         env->regs[14] = env->xregs[23];
4789     } else {
4790         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
4791         env->banked_r14[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
4792     }
4793
4794     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
4795      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
4796      * FIQ bank for r8-r14.
4797      */
4798     if (mode == ARM_CPU_MODE_FIQ) {
4799         for (i = 24; i < 31; i++) {
4800             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
4801         }
4802     } else {
4803         for (i = 24; i < 29; i++) {
4804             env->fiq_regs[i - 24] = env->xregs[i];
4805         }
4806         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
4807         env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
4808     }
4809
4810     env->regs[15] = env->pc;
4811 }
4812
4813 /* Handle a CPU exception.  */
4814 void arm_cpu_do_interrupt(CPUState *cs)
4815 {
4816     ARMCPU *cpu = ARM_CPU(cs);
4817     CPUARMState *env = &cpu->env;
4818     uint32_t addr;
4819     uint32_t mask;
4820     int new_mode;
4821     uint32_t offset;
4822     uint32_t moe;
4823
4824     assert(!IS_M(env));
4825
4826     arm_log_exception(cs->exception_index);
4827
4828     if (arm_is_psci_call(cpu, cs->exception_index)) {
4829         arm_handle_psci_call(cpu);
4830         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
4831         return;
4832     }
4833
4834     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
4835     switch (env->exception.syndrome >> ARM_EL_EC_SHIFT) {
4836     case EC_BREAKPOINT:
4837     case EC_BREAKPOINT_SAME_EL:
4838         moe = 1;
4839         break;
4840     case EC_WATCHPOINT:
4841     case EC_WATCHPOINT_SAME_EL:
4842         moe = 10;
4843         break;
4844     case EC_AA32_BKPT:
4845         moe = 3;
4846         break;
4847     case EC_VECTORCATCH:
4848         moe = 5;
4849         break;
4850     default:
4851         moe = 0;
4852         break;
4853     }
4854
4855     if (moe) {
4856         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
4857     }
4858
4859     /* TODO: Vectored interrupt controller.  */
4860     switch (cs->exception_index) {
4861     case EXCP_UDEF:
4862         new_mode = ARM_CPU_MODE_UND;
4863         addr = 0x04;
4864         mask = CPSR_I;
4865         if (env->thumb)
4866             offset = 2;
4867         else
4868             offset = 4;
4869         break;
4870     case EXCP_SWI:
4871         if (semihosting_enabled()) {
4872             /* Check for semihosting interrupt.  */
4873             if (env->thumb) {
4874                 mask = arm_lduw_code(env, env->regs[15] - 2, env->bswap_code)
4875                     & 0xff;
4876             } else {
4877                 mask = arm_ldl_code(env, env->regs[15] - 4, env->bswap_code)
4878                     & 0xffffff;
4879             }
4880             /* Only intercept calls from privileged modes, to provide some
4881                semblance of security.  */
4882             if (((mask == 0x123456 && !env->thumb)
4883                     || (mask == 0xab && env->thumb))
4884                   && (env->uncached_cpsr & CPSR_M) != ARM_CPU_MODE_USR) {
4885                 env->regs[0] = do_arm_semihosting(env);
4886                 qemu_log_mask(CPU_LOG_INT, "...handled as semihosting call\n");
4887                 return;
4888             }
4889         }
4890         new_mode = ARM_CPU_MODE_SVC;
4891         addr = 0x08;
4892         mask = CPSR_I;
4893         /* The PC already points to the next instruction.  */
4894         offset = 0;
4895         break;
4896     case EXCP_BKPT:
4897         /* See if this is a semihosting syscall.  */
4898         if (env->thumb && semihosting_enabled()) {
4899             mask = arm_lduw_code(env, env->regs[15], env->bswap_code) & 0xff;
4900             if (mask == 0xab
4901                   && (env->uncached_cpsr & CPSR_M) != ARM_CPU_MODE_USR) {
4902                 env->regs[15] += 2;
4903                 env->regs[0] = do_arm_semihosting(env);
4904                 qemu_log_mask(CPU_LOG_INT, "...handled as semihosting call\n");
4905                 return;
4906             }
4907         }
4908         env->exception.fsr = 2;
4909         /* Fall through to prefetch abort.  */
4910     case EXCP_PREFETCH_ABORT:
4911         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
4912         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
4913         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
4914                       env->exception.fsr, (uint32_t)env->exception.vaddress);
4915         new_mode = ARM_CPU_MODE_ABT;
4916         addr = 0x0c;
4917         mask = CPSR_A | CPSR_I;
4918         offset = 4;
4919         break;
4920     case EXCP_DATA_ABORT:
4921         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
4922         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
4923         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
4924                       env->exception.fsr,
4925                       (uint32_t)env->exception.vaddress);
4926         new_mode = ARM_CPU_MODE_ABT;
4927         addr = 0x10;
4928         mask = CPSR_A | CPSR_I;
4929         offset = 8;
4930         break;
4931     case EXCP_IRQ:
4932         new_mode = ARM_CPU_MODE_IRQ;
4933         addr = 0x18;
4934         /* Disable IRQ and imprecise data aborts.  */
4935         mask = CPSR_A | CPSR_I;
4936         offset = 4;
4937         if (env->cp15.scr_el3 & SCR_IRQ) {
4938             /* IRQ routed to monitor mode */
4939             new_mode = ARM_CPU_MODE_MON;
4940             mask |= CPSR_F;
4941         }
4942         break;
4943     case EXCP_FIQ:
4944         new_mode = ARM_CPU_MODE_FIQ;
4945         addr = 0x1c;
4946         /* Disable FIQ, IRQ and imprecise data aborts.  */
4947         mask = CPSR_A | CPSR_I | CPSR_F;
4948         if (env->cp15.scr_el3 & SCR_FIQ) {
4949             /* FIQ routed to monitor mode */
4950             new_mode = ARM_CPU_MODE_MON;
4951         }
4952         offset = 4;
4953         break;
4954     case EXCP_SMC:
4955         new_mode = ARM_CPU_MODE_MON;
4956         addr = 0x08;
4957         mask = CPSR_A | CPSR_I | CPSR_F;
4958         offset = 0;
4959         break;
4960     default:
4961         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
4962         return; /* Never happens.  Keep compiler happy.  */
4963     }
4964
4965     if (new_mode == ARM_CPU_MODE_MON) {
4966         addr += env->cp15.mvbar;
4967     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
4968         /* High vectors. When enabled, base address cannot be remapped. */
4969         addr += 0xffff0000;
4970     } else {
4971         /* ARM v7 architectures provide a vector base address register to remap
4972          * the interrupt vector table.
4973          * This register is only followed in non-monitor mode, and is banked.
4974          * Note: only bits 31:5 are valid.
4975          */
4976         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
4977     }
4978
4979     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
4980         env->cp15.scr_el3 &= ~SCR_NS;
4981     }
4982
4983     switch_mode (env, new_mode);
4984     /* For exceptions taken to AArch32 we must clear the SS bit in both
4985      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
4986      */
4987     env->uncached_cpsr &= ~PSTATE_SS;
4988     env->spsr = cpsr_read(env);
4989     /* Clear IT bits.  */
4990     env->condexec_bits = 0;
4991     /* Switch to the new mode, and to the correct instruction set.  */
4992     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
4993     env->daif |= mask;
4994     /* this is a lie, as the was no c1_sys on V4T/V5, but who cares
4995      * and we should just guard the thumb mode on V4 */
4996     if (arm_feature(env, ARM_FEATURE_V4T)) {
4997         env->thumb = (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
4998     }
4999     env->regs[14] = env->regs[15] + offset;
5000     env->regs[15] = addr;
5001     cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
5002 }
5003
5004
5005 /* Return the exception level which controls this address translation regime */
5006 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
5007 {
5008     switch (mmu_idx) {
5009     case ARMMMUIdx_S2NS:
5010     case ARMMMUIdx_S1E2:
5011         return 2;
5012     case ARMMMUIdx_S1E3:
5013         return 3;
5014     case ARMMMUIdx_S1SE0:
5015         return arm_el_is_aa64(env, 3) ? 1 : 3;
5016     case ARMMMUIdx_S1SE1:
5017     case ARMMMUIdx_S1NSE0:
5018     case ARMMMUIdx_S1NSE1:
5019         return 1;
5020     default:
5021         g_assert_not_reached();
5022     }
5023 }
5024
5025 /* Return true if this address translation regime is secure */
5026 static inline bool regime_is_secure(CPUARMState *env, ARMMMUIdx mmu_idx)
5027 {
5028     switch (mmu_idx) {
5029     case ARMMMUIdx_S12NSE0:
5030     case ARMMMUIdx_S12NSE1:
5031     case ARMMMUIdx_S1NSE0:
5032     case ARMMMUIdx_S1NSE1:
5033     case ARMMMUIdx_S1E2:
5034     case ARMMMUIdx_S2NS:
5035         return false;
5036     case ARMMMUIdx_S1E3:
5037     case ARMMMUIdx_S1SE0:
5038     case ARMMMUIdx_S1SE1:
5039         return true;
5040     default:
5041         g_assert_not_reached();
5042     }
5043 }
5044
5045 /* Return the SCTLR value which controls this address translation regime */
5046 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
5047 {
5048     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
5049 }
5050
5051 /* Return true if the specified stage of address translation is disabled */
5052 static inline bool regime_translation_disabled(CPUARMState *env,
5053                                                ARMMMUIdx mmu_idx)
5054 {
5055     if (mmu_idx == ARMMMUIdx_S2NS) {
5056         return (env->cp15.hcr_el2 & HCR_VM) == 0;
5057     }
5058     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
5059 }
5060
5061 /* Return the TCR controlling this translation regime */
5062 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
5063 {
5064     if (mmu_idx == ARMMMUIdx_S2NS) {
5065         /* TODO: return VTCR_EL2 */
5066         g_assert_not_reached();
5067     }
5068     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
5069 }
5070
5071 /* Return the TTBR associated with this translation regime */
5072 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
5073                                    int ttbrn)
5074 {
5075     if (mmu_idx == ARMMMUIdx_S2NS) {
5076         /* TODO: return VTTBR_EL2 */
5077         g_assert_not_reached();
5078     }
5079     if (ttbrn == 0) {
5080         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
5081     } else {
5082         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
5083     }
5084 }
5085
5086 /* Return true if the translation regime is using LPAE format page tables */
5087 static inline bool regime_using_lpae_format(CPUARMState *env,
5088                                             ARMMMUIdx mmu_idx)
5089 {
5090     int el = regime_el(env, mmu_idx);
5091     if (el == 2 || arm_el_is_aa64(env, el)) {
5092         return true;
5093     }
5094     if (arm_feature(env, ARM_FEATURE_LPAE)
5095         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
5096         return true;
5097     }
5098     return false;
5099 }
5100
5101 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
5102 {
5103     switch (mmu_idx) {
5104     case ARMMMUIdx_S1SE0:
5105     case ARMMMUIdx_S1NSE0:
5106         return true;
5107     default:
5108         return false;
5109     case ARMMMUIdx_S12NSE0:
5110     case ARMMMUIdx_S12NSE1:
5111         g_assert_not_reached();
5112     }
5113 }
5114
5115 /* Translate section/page access permissions to page
5116  * R/W protection flags
5117  *
5118  * @env:         CPUARMState
5119  * @mmu_idx:     MMU index indicating required translation regime
5120  * @ap:          The 3-bit access permissions (AP[2:0])
5121  * @domain_prot: The 2-bit domain access permissions
5122  */
5123 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
5124                                 int ap, int domain_prot)
5125 {
5126     bool is_user = regime_is_user(env, mmu_idx);
5127
5128     if (domain_prot == 3) {
5129         return PAGE_READ | PAGE_WRITE;
5130     }
5131
5132     switch (ap) {
5133     case 0:
5134         if (arm_feature(env, ARM_FEATURE_V7)) {
5135             return 0;
5136         }
5137         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
5138         case SCTLR_S:
5139             return is_user ? 0 : PAGE_READ;
5140         case SCTLR_R:
5141             return PAGE_READ;
5142         default:
5143             return 0;
5144         }
5145     case 1:
5146         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
5147     case 2:
5148         if (is_user) {
5149             return PAGE_READ;
5150         } else {
5151             return PAGE_READ | PAGE_WRITE;
5152         }
5153     case 3:
5154         return PAGE_READ | PAGE_WRITE;
5155     case 4: /* Reserved.  */
5156         return 0;
5157     case 5:
5158         return is_user ? 0 : PAGE_READ;
5159     case 6:
5160         return PAGE_READ;
5161     case 7:
5162         if (!arm_feature(env, ARM_FEATURE_V6K)) {
5163             return 0;
5164         }
5165         return PAGE_READ;
5166     default:
5167         g_assert_not_reached();
5168     }
5169 }
5170
5171 /* Translate section/page access permissions to page
5172  * R/W protection flags.
5173  *
5174  * @ap:      The 2-bit simple AP (AP[2:1])
5175  * @is_user: TRUE if accessing from PL0
5176  */
5177 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
5178 {
5179     switch (ap) {
5180     case 0:
5181         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
5182     case 1:
5183         return PAGE_READ | PAGE_WRITE;
5184     case 2:
5185         return is_user ? 0 : PAGE_READ;
5186     case 3:
5187         return PAGE_READ;
5188     default:
5189         g_assert_not_reached();
5190     }
5191 }
5192
5193 static inline int
5194 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
5195 {
5196     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
5197 }
5198
5199 /* Translate section/page access permissions to protection flags
5200  *
5201  * @env:     CPUARMState
5202  * @mmu_idx: MMU index indicating required translation regime
5203  * @is_aa64: TRUE if AArch64
5204  * @ap:      The 2-bit simple AP (AP[2:1])
5205  * @ns:      NS (non-secure) bit
5206  * @xn:      XN (execute-never) bit
5207  * @pxn:     PXN (privileged execute-never) bit
5208  */
5209 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
5210                       int ap, int ns, int xn, int pxn)
5211 {
5212     bool is_user = regime_is_user(env, mmu_idx);
5213     int prot_rw, user_rw;
5214     bool have_wxn;
5215     int wxn = 0;
5216
5217     assert(mmu_idx != ARMMMUIdx_S2NS);
5218
5219     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
5220     if (is_user) {
5221         prot_rw = user_rw;
5222     } else {
5223         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
5224     }
5225
5226     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
5227         return prot_rw;
5228     }
5229
5230     /* TODO have_wxn should be replaced with
5231      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
5232      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
5233      * compatible processors have EL2, which is required for [U]WXN.
5234      */
5235     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
5236
5237     if (have_wxn) {
5238         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
5239     }
5240
5241     if (is_aa64) {
5242         switch (regime_el(env, mmu_idx)) {
5243         case 1:
5244             if (!is_user) {
5245                 xn = pxn || (user_rw & PAGE_WRITE);
5246             }
5247             break;
5248         case 2:
5249         case 3:
5250             break;
5251         }
5252     } else if (arm_feature(env, ARM_FEATURE_V7)) {
5253         switch (regime_el(env, mmu_idx)) {
5254         case 1:
5255         case 3:
5256             if (is_user) {
5257                 xn = xn || !(user_rw & PAGE_READ);
5258             } else {
5259                 int uwxn = 0;
5260                 if (have_wxn) {
5261                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
5262                 }
5263                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
5264                      (uwxn && (user_rw & PAGE_WRITE));
5265             }
5266             break;
5267         case 2:
5268             break;
5269         }
5270     } else {
5271         xn = wxn = 0;
5272     }
5273
5274     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
5275         return prot_rw;
5276     }
5277     return prot_rw | PAGE_EXEC;
5278 }
5279
5280 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
5281                                      uint32_t *table, uint32_t address)
5282 {
5283     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
5284     TCR *tcr = regime_tcr(env, mmu_idx);
5285
5286     if (address & tcr->mask) {
5287         if (tcr->raw_tcr & TTBCR_PD1) {
5288             /* Translation table walk disabled for TTBR1 */
5289             return false;
5290         }
5291         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
5292     } else {
5293         if (tcr->raw_tcr & TTBCR_PD0) {
5294             /* Translation table walk disabled for TTBR0 */
5295             return false;
5296         }
5297         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
5298     }
5299     *table |= (address >> 18) & 0x3ffc;
5300     return true;
5301 }
5302
5303 /* All loads done in the course of a page table walk go through here.
5304  * TODO: rather than ignoring errors from physical memory reads (which
5305  * are external aborts in ARM terminology) we should propagate this
5306  * error out so that we can turn it into a Data Abort if this walk
5307  * was being done for a CPU load/store or an address translation instruction
5308  * (but not if it was for a debug access).
5309  */
5310 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure)
5311 {
5312     MemTxAttrs attrs = {};
5313
5314     attrs.secure = is_secure;
5315     return address_space_ldl(cs->as, addr, attrs, NULL);
5316 }
5317
5318 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure)
5319 {
5320     MemTxAttrs attrs = {};
5321
5322     attrs.secure = is_secure;
5323     return address_space_ldq(cs->as, addr, attrs, NULL);
5324 }
5325
5326 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
5327                              int access_type, ARMMMUIdx mmu_idx,
5328                              hwaddr *phys_ptr, int *prot,
5329                              target_ulong *page_size, uint32_t *fsr)
5330 {
5331     CPUState *cs = CPU(arm_env_get_cpu(env));
5332     int code;
5333     uint32_t table;
5334     uint32_t desc;
5335     int type;
5336     int ap;
5337     int domain = 0;
5338     int domain_prot;
5339     hwaddr phys_addr;
5340     uint32_t dacr;
5341
5342     /* Pagetable walk.  */
5343     /* Lookup l1 descriptor.  */
5344     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
5345         /* Section translation fault if page walk is disabled by PD0 or PD1 */
5346         code = 5;
5347         goto do_fault;
5348     }
5349     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx));
5350     type = (desc & 3);
5351     domain = (desc >> 5) & 0x0f;
5352     if (regime_el(env, mmu_idx) == 1) {
5353         dacr = env->cp15.dacr_ns;
5354     } else {
5355         dacr = env->cp15.dacr_s;
5356     }
5357     domain_prot = (dacr >> (domain * 2)) & 3;
5358     if (type == 0) {
5359         /* Section translation fault.  */
5360         code = 5;
5361         goto do_fault;
5362     }
5363     if (domain_prot == 0 || domain_prot == 2) {
5364         if (type == 2)
5365             code = 9; /* Section domain fault.  */
5366         else
5367             code = 11; /* Page domain fault.  */
5368         goto do_fault;
5369     }
5370     if (type == 2) {
5371         /* 1Mb section.  */
5372         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
5373         ap = (desc >> 10) & 3;
5374         code = 13;
5375         *page_size = 1024 * 1024;
5376     } else {
5377         /* Lookup l2 entry.  */
5378         if (type == 1) {
5379             /* Coarse pagetable.  */
5380             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
5381         } else {
5382             /* Fine pagetable.  */
5383             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
5384         }
5385         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx));
5386         switch (desc & 3) {
5387         case 0: /* Page translation fault.  */
5388             code = 7;
5389             goto do_fault;
5390         case 1: /* 64k page.  */
5391             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
5392             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
5393             *page_size = 0x10000;
5394             break;
5395         case 2: /* 4k page.  */
5396             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
5397             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
5398             *page_size = 0x1000;
5399             break;
5400         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
5401             if (type == 1) {
5402                 /* ARMv6/XScale extended small page format */
5403                 if (arm_feature(env, ARM_FEATURE_XSCALE)
5404                     || arm_feature(env, ARM_FEATURE_V6)) {
5405                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
5406                     *page_size = 0x1000;
5407                 } else {
5408                     /* UNPREDICTABLE in ARMv5; we choose to take a
5409                      * page translation fault.
5410                      */
5411                     code = 7;
5412                     goto do_fault;
5413                 }
5414             } else {
5415                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
5416                 *page_size = 0x400;
5417             }
5418             ap = (desc >> 4) & 3;
5419             break;
5420         default:
5421             /* Never happens, but compiler isn't smart enough to tell.  */
5422             abort();
5423         }
5424         code = 15;
5425     }
5426     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
5427     *prot |= *prot ? PAGE_EXEC : 0;
5428     if (!(*prot & (1 << access_type))) {
5429         /* Access permission fault.  */
5430         goto do_fault;
5431     }
5432     *phys_ptr = phys_addr;
5433     return false;
5434 do_fault:
5435     *fsr = code | (domain << 4);
5436     return true;
5437 }
5438
5439 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
5440                              int access_type, ARMMMUIdx mmu_idx,
5441                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
5442                              target_ulong *page_size, uint32_t *fsr)
5443 {
5444     CPUState *cs = CPU(arm_env_get_cpu(env));
5445     int code;
5446     uint32_t table;
5447     uint32_t desc;
5448     uint32_t xn;
5449     uint32_t pxn = 0;
5450     int type;
5451     int ap;
5452     int domain = 0;
5453     int domain_prot;
5454     hwaddr phys_addr;
5455     uint32_t dacr;
5456     bool ns;
5457
5458     /* Pagetable walk.  */
5459     /* Lookup l1 descriptor.  */
5460     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
5461         /* Section translation fault if page walk is disabled by PD0 or PD1 */
5462         code = 5;
5463         goto do_fault;
5464     }
5465     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx));
5466     type = (desc & 3);
5467     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
5468         /* Section translation fault, or attempt to use the encoding
5469          * which is Reserved on implementations without PXN.
5470          */
5471         code = 5;
5472         goto do_fault;
5473     }
5474     if ((type == 1) || !(desc & (1 << 18))) {
5475         /* Page or Section.  */
5476         domain = (desc >> 5) & 0x0f;
5477     }
5478     if (regime_el(env, mmu_idx) == 1) {
5479         dacr = env->cp15.dacr_ns;
5480     } else {
5481         dacr = env->cp15.dacr_s;
5482     }
5483     domain_prot = (dacr >> (domain * 2)) & 3;
5484     if (domain_prot == 0 || domain_prot == 2) {
5485         if (type != 1) {
5486             code = 9; /* Section domain fault.  */
5487         } else {
5488             code = 11; /* Page domain fault.  */
5489         }
5490         goto do_fault;
5491     }
5492     if (type != 1) {
5493         if (desc & (1 << 18)) {
5494             /* Supersection.  */
5495             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
5496             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
5497             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
5498             *page_size = 0x1000000;
5499         } else {
5500             /* Section.  */
5501             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
5502             *page_size = 0x100000;
5503         }
5504         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
5505         xn = desc & (1 << 4);
5506         pxn = desc & 1;
5507         code = 13;
5508         ns = extract32(desc, 19, 1);
5509     } else {
5510         if (arm_feature(env, ARM_FEATURE_PXN)) {
5511             pxn = (desc >> 2) & 1;
5512         }
5513         ns = extract32(desc, 3, 1);
5514         /* Lookup l2 entry.  */
5515         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
5516         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx));
5517         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
5518         switch (desc & 3) {
5519         case 0: /* Page translation fault.  */
5520             code = 7;
5521             goto do_fault;
5522         case 1: /* 64k page.  */
5523             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
5524             xn = desc & (1 << 15);
5525             *page_size = 0x10000;
5526             break;
5527         case 2: case 3: /* 4k page.  */
5528             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
5529             xn = desc & 1;
5530             *page_size = 0x1000;
5531             break;
5532         default:
5533             /* Never happens, but compiler isn't smart enough to tell.  */
5534             abort();
5535         }
5536         code = 15;
5537     }
5538     if (domain_prot == 3) {
5539         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
5540     } else {
5541         if (pxn && !regime_is_user(env, mmu_idx)) {
5542             xn = 1;
5543         }
5544         if (xn && access_type == 2)
5545             goto do_fault;
5546
5547         if (arm_feature(env, ARM_FEATURE_V6K) &&
5548                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
5549             /* The simplified model uses AP[0] as an access control bit.  */
5550             if ((ap & 1) == 0) {
5551                 /* Access flag fault.  */
5552                 code = (code == 15) ? 6 : 3;
5553                 goto do_fault;
5554             }
5555             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
5556         } else {
5557             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
5558         }
5559         if (*prot && !xn) {
5560             *prot |= PAGE_EXEC;
5561         }
5562         if (!(*prot & (1 << access_type))) {
5563             /* Access permission fault.  */
5564             goto do_fault;
5565         }
5566     }
5567     if (ns) {
5568         /* The NS bit will (as required by the architecture) have no effect if
5569          * the CPU doesn't support TZ or this is a non-secure translation
5570          * regime, because the attribute will already be non-secure.
5571          */
5572         attrs->secure = false;
5573     }
5574     *phys_ptr = phys_addr;
5575     return false;
5576 do_fault:
5577     *fsr = code | (domain << 4);
5578     return true;
5579 }
5580
5581 /* Fault type for long-descriptor MMU fault reporting; this corresponds
5582  * to bits [5..2] in the STATUS field in long-format DFSR/IFSR.
5583  */
5584 typedef enum {
5585     translation_fault = 1,
5586     access_fault = 2,
5587     permission_fault = 3,
5588 } MMUFaultType;
5589
5590 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
5591                                int access_type, ARMMMUIdx mmu_idx,
5592                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
5593                                target_ulong *page_size_ptr, uint32_t *fsr)
5594 {
5595     CPUState *cs = CPU(arm_env_get_cpu(env));
5596     /* Read an LPAE long-descriptor translation table. */
5597     MMUFaultType fault_type = translation_fault;
5598     uint32_t level = 1;
5599     uint32_t epd;
5600     int32_t tsz;
5601     uint32_t tg;
5602     uint64_t ttbr;
5603     int ttbr_select;
5604     hwaddr descaddr, descmask;
5605     uint32_t tableattrs;
5606     target_ulong page_size;
5607     uint32_t attrs;
5608     int32_t granule_sz = 9;
5609     int32_t va_size = 32;
5610     int32_t tbi = 0;
5611     TCR *tcr = regime_tcr(env, mmu_idx);
5612     int ap, ns, xn, pxn;
5613     uint32_t el = regime_el(env, mmu_idx);
5614     bool ttbr1_valid = true;
5615
5616     /* TODO:
5617      * This code does not handle the different format TCR for VTCR_EL2.
5618      * This code also does not support shareability levels.
5619      * Attribute and permission bit handling should also be checked when adding
5620      * support for those page table walks.
5621      */
5622     if (arm_el_is_aa64(env, el)) {
5623         va_size = 64;
5624         if (el > 1) {
5625             tbi = extract64(tcr->raw_tcr, 20, 1);
5626         } else {
5627             if (extract64(address, 55, 1)) {
5628                 tbi = extract64(tcr->raw_tcr, 38, 1);
5629             } else {
5630                 tbi = extract64(tcr->raw_tcr, 37, 1);
5631             }
5632         }
5633         tbi *= 8;
5634
5635         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
5636          * invalid.
5637          */
5638         if (el > 1) {
5639             ttbr1_valid = false;
5640         }
5641     }
5642
5643     /* Determine whether this address is in the region controlled by
5644      * TTBR0 or TTBR1 (or if it is in neither region and should fault).
5645      * This is a Non-secure PL0/1 stage 1 translation, so controlled by
5646      * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:
5647      */
5648     uint32_t t0sz = extract32(tcr->raw_tcr, 0, 6);
5649     if (va_size == 64) {
5650         t0sz = MIN(t0sz, 39);
5651         t0sz = MAX(t0sz, 16);
5652     }
5653     uint32_t t1sz = extract32(tcr->raw_tcr, 16, 6);
5654     if (va_size == 64) {
5655         t1sz = MIN(t1sz, 39);
5656         t1sz = MAX(t1sz, 16);
5657     }
5658     if (t0sz && !extract64(address, va_size - t0sz, t0sz - tbi)) {
5659         /* there is a ttbr0 region and we are in it (high bits all zero) */
5660         ttbr_select = 0;
5661     } else if (ttbr1_valid && t1sz &&
5662                !extract64(~address, va_size - t1sz, t1sz - tbi)) {
5663         /* there is a ttbr1 region and we are in it (high bits all one) */
5664         ttbr_select = 1;
5665     } else if (!t0sz) {
5666         /* ttbr0 region is "everything not in the ttbr1 region" */
5667         ttbr_select = 0;
5668     } else if (!t1sz && ttbr1_valid) {
5669         /* ttbr1 region is "everything not in the ttbr0 region" */
5670         ttbr_select = 1;
5671     } else {
5672         /* in the gap between the two regions, this is a Translation fault */
5673         fault_type = translation_fault;
5674         goto do_fault;
5675     }
5676
5677     /* Note that QEMU ignores shareability and cacheability attributes,
5678      * so we don't need to do anything with the SH, ORGN, IRGN fields
5679      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
5680      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
5681      * implement any ASID-like capability so we can ignore it (instead
5682      * we will always flush the TLB any time the ASID is changed).
5683      */
5684     if (ttbr_select == 0) {
5685         ttbr = regime_ttbr(env, mmu_idx, 0);
5686         epd = extract32(tcr->raw_tcr, 7, 1);
5687         tsz = t0sz;
5688
5689         tg = extract32(tcr->raw_tcr, 14, 2);
5690         if (tg == 1) { /* 64KB pages */
5691             granule_sz = 13;
5692         }
5693         if (tg == 2) { /* 16KB pages */
5694             granule_sz = 11;
5695         }
5696     } else {
5697         /* We should only be here if TTBR1 is valid */
5698         assert(ttbr1_valid);
5699
5700         ttbr = regime_ttbr(env, mmu_idx, 1);
5701         epd = extract32(tcr->raw_tcr, 23, 1);
5702         tsz = t1sz;
5703
5704         tg = extract32(tcr->raw_tcr, 30, 2);
5705         if (tg == 3)  { /* 64KB pages */
5706             granule_sz = 13;
5707         }
5708         if (tg == 1) { /* 16KB pages */
5709             granule_sz = 11;
5710         }
5711     }
5712
5713     /* Here we should have set up all the parameters for the translation:
5714      * va_size, ttbr, epd, tsz, granule_sz, tbi
5715      */
5716
5717     if (epd) {
5718         /* Translation table walk disabled => Translation fault on TLB miss
5719          * Note: This is always 0 on 64-bit EL2 and EL3.
5720          */
5721         goto do_fault;
5722     }
5723
5724     /* The starting level depends on the virtual address size (which can be
5725      * up to 48 bits) and the translation granule size. It indicates the number
5726      * of strides (granule_sz bits at a time) needed to consume the bits
5727      * of the input address. In the pseudocode this is:
5728      *  level = 4 - RoundUp((inputsize - grainsize) / stride)
5729      * where their 'inputsize' is our 'va_size - tsz', 'grainsize' is
5730      * our 'granule_sz + 3' and 'stride' is our 'granule_sz'.
5731      * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
5732      *     = 4 - (va_size - tsz - granule_sz - 3 + granule_sz - 1) / granule_sz
5733      *     = 4 - (va_size - tsz - 4) / granule_sz;
5734      */
5735     level = 4 - (va_size - tsz - 4) / granule_sz;
5736
5737     /* Clear the vaddr bits which aren't part of the within-region address,
5738      * so that we don't have to special case things when calculating the
5739      * first descriptor address.
5740      */
5741     if (tsz) {
5742         address &= (1ULL << (va_size - tsz)) - 1;
5743     }
5744
5745     descmask = (1ULL << (granule_sz + 3)) - 1;
5746
5747     /* Now we can extract the actual base address from the TTBR */
5748     descaddr = extract64(ttbr, 0, 48);
5749     descaddr &= ~((1ULL << (va_size - tsz - (granule_sz * (4 - level)))) - 1);
5750
5751     /* Secure accesses start with the page table in secure memory and
5752      * can be downgraded to non-secure at any step. Non-secure accesses
5753      * remain non-secure. We implement this by just ORing in the NSTable/NS
5754      * bits at each step.
5755      */
5756     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
5757     for (;;) {
5758         uint64_t descriptor;
5759         bool nstable;
5760
5761         descaddr |= (address >> (granule_sz * (4 - level))) & descmask;
5762         descaddr &= ~7ULL;
5763         nstable = extract32(tableattrs, 4, 1);
5764         descriptor = arm_ldq_ptw(cs, descaddr, !nstable);
5765         if (!(descriptor & 1) ||
5766             (!(descriptor & 2) && (level == 3))) {
5767             /* Invalid, or the Reserved level 3 encoding */
5768             goto do_fault;
5769         }
5770         descaddr = descriptor & 0xfffffff000ULL;
5771
5772         if ((descriptor & 2) && (level < 3)) {
5773             /* Table entry. The top five bits are attributes which  may
5774              * propagate down through lower levels of the table (and
5775              * which are all arranged so that 0 means "no effect", so
5776              * we can gather them up by ORing in the bits at each level).
5777              */
5778             tableattrs |= extract64(descriptor, 59, 5);
5779             level++;
5780             continue;
5781         }
5782         /* Block entry at level 1 or 2, or page entry at level 3.
5783          * These are basically the same thing, although the number
5784          * of bits we pull in from the vaddr varies.
5785          */
5786         page_size = (1ULL << ((granule_sz * (4 - level)) + 3));
5787         descaddr |= (address & (page_size - 1));
5788         /* Extract attributes from the descriptor and merge with table attrs */
5789         attrs = extract64(descriptor, 2, 10)
5790             | (extract64(descriptor, 52, 12) << 10);
5791         attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */
5792         attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */
5793         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
5794          * means "force PL1 access only", which means forcing AP[1] to 0.
5795          */
5796         if (extract32(tableattrs, 2, 1)) {
5797             attrs &= ~(1 << 4);
5798         }
5799         attrs |= nstable << 3; /* NS */
5800         break;
5801     }
5802     /* Here descaddr is the final physical address, and attributes
5803      * are all in attrs.
5804      */
5805     fault_type = access_fault;
5806     if ((attrs & (1 << 8)) == 0) {
5807         /* Access flag */
5808         goto do_fault;
5809     }
5810
5811     ap = extract32(attrs, 4, 2);
5812     ns = extract32(attrs, 3, 1);
5813     xn = extract32(attrs, 12, 1);
5814     pxn = extract32(attrs, 11, 1);
5815
5816     *prot = get_S1prot(env, mmu_idx, va_size == 64, ap, ns, xn, pxn);
5817
5818     fault_type = permission_fault;
5819     if (!(*prot & (1 << access_type))) {
5820         goto do_fault;
5821     }
5822
5823     if (ns) {
5824         /* The NS bit will (as required by the architecture) have no effect if
5825          * the CPU doesn't support TZ or this is a non-secure translation
5826          * regime, because the attribute will already be non-secure.
5827          */
5828         txattrs->secure = false;
5829     }
5830     *phys_ptr = descaddr;
5831     *page_size_ptr = page_size;
5832     return false;
5833
5834 do_fault:
5835     /* Long-descriptor format IFSR/DFSR value */
5836     *fsr = (1 << 9) | (fault_type << 2) | level;
5837     return true;
5838 }
5839
5840 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
5841                                                 ARMMMUIdx mmu_idx,
5842                                                 int32_t address, int *prot)
5843 {
5844     *prot = PAGE_READ | PAGE_WRITE;
5845     switch (address) {
5846     case 0xF0000000 ... 0xFFFFFFFF:
5847         if (regime_sctlr(env, mmu_idx) & SCTLR_V) { /* hivecs execing is ok */
5848             *prot |= PAGE_EXEC;
5849         }
5850         break;
5851     case 0x00000000 ... 0x7FFFFFFF:
5852         *prot |= PAGE_EXEC;
5853         break;
5854     }
5855
5856 }
5857
5858 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
5859                                  int access_type, ARMMMUIdx mmu_idx,
5860                                  hwaddr *phys_ptr, int *prot, uint32_t *fsr)
5861 {
5862     ARMCPU *cpu = arm_env_get_cpu(env);
5863     int n;
5864     bool is_user = regime_is_user(env, mmu_idx);
5865
5866     *phys_ptr = address;
5867     *prot = 0;
5868
5869     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
5870         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
5871     } else { /* MPU enabled */
5872         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
5873             /* region search */
5874             uint32_t base = env->pmsav7.drbar[n];
5875             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
5876             uint32_t rmask;
5877             bool srdis = false;
5878
5879             if (!(env->pmsav7.drsr[n] & 0x1)) {
5880                 continue;
5881             }
5882
5883             if (!rsize) {
5884                 qemu_log_mask(LOG_GUEST_ERROR, "DRSR.Rsize field can not be 0");
5885                 continue;
5886             }
5887             rsize++;
5888             rmask = (1ull << rsize) - 1;
5889
5890             if (base & rmask) {
5891                 qemu_log_mask(LOG_GUEST_ERROR, "DRBAR %" PRIx32 " misaligned "
5892                               "to DRSR region size, mask = %" PRIx32,
5893                               base, rmask);
5894                 continue;
5895             }
5896
5897             if (address < base || address > base + rmask) {
5898                 continue;
5899             }
5900
5901             /* Region matched */
5902
5903             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
5904                 int i, snd;
5905                 uint32_t srdis_mask;
5906
5907                 rsize -= 3; /* sub region size (power of 2) */
5908                 snd = ((address - base) >> rsize) & 0x7;
5909                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
5910
5911                 srdis_mask = srdis ? 0x3 : 0x0;
5912                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
5913                     /* This will check in groups of 2, 4 and then 8, whether
5914                      * the subregion bits are consistent. rsize is incremented
5915                      * back up to give the region size, considering consistent
5916                      * adjacent subregions as one region. Stop testing if rsize
5917                      * is already big enough for an entire QEMU page.
5918                      */
5919                     int snd_rounded = snd & ~(i - 1);
5920                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
5921                                                      snd_rounded + 8, i);
5922                     if (srdis_mask ^ srdis_multi) {
5923                         break;
5924                     }
5925                     srdis_mask = (srdis_mask << i) | srdis_mask;
5926                     rsize++;
5927                 }
5928             }
5929             if (rsize < TARGET_PAGE_BITS) {
5930                 qemu_log_mask(LOG_UNIMP, "No support for MPU (sub)region"
5931                               "alignment of %" PRIu32 " bits. Minimum is %d\n",
5932                               rsize, TARGET_PAGE_BITS);
5933                 continue;
5934             }
5935             if (srdis) {
5936                 continue;
5937             }
5938             break;
5939         }
5940
5941         if (n == -1) { /* no hits */
5942             if (cpu->pmsav7_dregion &&
5943                 (is_user || !(regime_sctlr(env, mmu_idx) & SCTLR_BR))) {
5944                 /* background fault */
5945                 *fsr = 0;
5946                 return true;
5947             }
5948             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
5949         } else { /* a MPU hit! */
5950             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
5951
5952             if (is_user) { /* User mode AP bit decoding */
5953                 switch (ap) {
5954                 case 0:
5955                 case 1:
5956                 case 5:
5957                     break; /* no access */
5958                 case 3:
5959                     *prot |= PAGE_WRITE;
5960                     /* fall through */
5961                 case 2:
5962                 case 6:
5963                     *prot |= PAGE_READ | PAGE_EXEC;
5964                     break;
5965                 default:
5966                     qemu_log_mask(LOG_GUEST_ERROR,
5967                                   "Bad value for AP bits in DRACR %"
5968                                   PRIx32 "\n", ap);
5969                 }
5970             } else { /* Priv. mode AP bits decoding */
5971                 switch (ap) {
5972                 case 0:
5973                     break; /* no access */
5974                 case 1:
5975                 case 2:
5976                 case 3:
5977                     *prot |= PAGE_WRITE;
5978                     /* fall through */
5979                 case 5:
5980                 case 6:
5981                     *prot |= PAGE_READ | PAGE_EXEC;
5982                     break;
5983                 default:
5984                     qemu_log_mask(LOG_GUEST_ERROR,
5985                                   "Bad value for AP bits in DRACR %"
5986                                   PRIx32 "\n", ap);
5987                 }
5988             }
5989
5990             /* execute never */
5991             if (env->pmsav7.dracr[n] & (1 << 12)) {
5992                 *prot &= ~PAGE_EXEC;
5993             }
5994         }
5995     }
5996
5997     *fsr = 0x00d; /* Permission fault */
5998     return !(*prot & (1 << access_type));
5999 }
6000
6001 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
6002                                  int access_type, ARMMMUIdx mmu_idx,
6003                                  hwaddr *phys_ptr, int *prot, uint32_t *fsr)
6004 {
6005     int n;
6006     uint32_t mask;
6007     uint32_t base;
6008     bool is_user = regime_is_user(env, mmu_idx);
6009
6010     *phys_ptr = address;
6011     for (n = 7; n >= 0; n--) {
6012         base = env->cp15.c6_region[n];
6013         if ((base & 1) == 0) {
6014             continue;
6015         }
6016         mask = 1 << ((base >> 1) & 0x1f);
6017         /* Keep this shift separate from the above to avoid an
6018            (undefined) << 32.  */
6019         mask = (mask << 1) - 1;
6020         if (((base ^ address) & ~mask) == 0) {
6021             break;
6022         }
6023     }
6024     if (n < 0) {
6025         *fsr = 2;
6026         return true;
6027     }
6028
6029     if (access_type == 2) {
6030         mask = env->cp15.pmsav5_insn_ap;
6031     } else {
6032         mask = env->cp15.pmsav5_data_ap;
6033     }
6034     mask = (mask >> (n * 4)) & 0xf;
6035     switch (mask) {
6036     case 0:
6037         *fsr = 1;
6038         return true;
6039     case 1:
6040         if (is_user) {
6041             *fsr = 1;
6042             return true;
6043         }
6044         *prot = PAGE_READ | PAGE_WRITE;
6045         break;
6046     case 2:
6047         *prot = PAGE_READ;
6048         if (!is_user) {
6049             *prot |= PAGE_WRITE;
6050         }
6051         break;
6052     case 3:
6053         *prot = PAGE_READ | PAGE_WRITE;
6054         break;
6055     case 5:
6056         if (is_user) {
6057             *fsr = 1;
6058             return true;
6059         }
6060         *prot = PAGE_READ;
6061         break;
6062     case 6:
6063         *prot = PAGE_READ;
6064         break;
6065     default:
6066         /* Bad permission.  */
6067         *fsr = 1;
6068         return true;
6069     }
6070     *prot |= PAGE_EXEC;
6071     return false;
6072 }
6073
6074 /* get_phys_addr - get the physical address for this virtual address
6075  *
6076  * Find the physical address corresponding to the given virtual address,
6077  * by doing a translation table walk on MMU based systems or using the
6078  * MPU state on MPU based systems.
6079  *
6080  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
6081  * prot and page_size may not be filled in, and the populated fsr value provides
6082  * information on why the translation aborted, in the format of a
6083  * DFSR/IFSR fault register, with the following caveats:
6084  *  * we honour the short vs long DFSR format differences.
6085  *  * the WnR bit is never set (the caller must do this).
6086  *  * for PSMAv5 based systems we don't bother to return a full FSR format
6087  *    value.
6088  *
6089  * @env: CPUARMState
6090  * @address: virtual address to get physical address for
6091  * @access_type: 0 for read, 1 for write, 2 for execute
6092  * @mmu_idx: MMU index indicating required translation regime
6093  * @phys_ptr: set to the physical address corresponding to the virtual address
6094  * @attrs: set to the memory transaction attributes to use
6095  * @prot: set to the permissions for the page containing phys_ptr
6096  * @page_size: set to the size of the page containing phys_ptr
6097  * @fsr: set to the DFSR/IFSR value on failure
6098  */
6099 static inline bool get_phys_addr(CPUARMState *env, target_ulong address,
6100                                  int access_type, ARMMMUIdx mmu_idx,
6101                                  hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
6102                                  target_ulong *page_size, uint32_t *fsr)
6103 {
6104     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
6105         /* TODO: when we support EL2 we should here call ourselves recursively
6106          * to do the stage 1 and then stage 2 translations. The arm_ld*_ptw
6107          * functions will also need changing to perform ARMMMUIdx_S2NS loads
6108          * rather than direct physical memory loads when appropriate.
6109          * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
6110          */
6111         assert(!arm_feature(env, ARM_FEATURE_EL2));
6112         mmu_idx += ARMMMUIdx_S1NSE0;
6113     }
6114
6115     /* The page table entries may downgrade secure to non-secure, but
6116      * cannot upgrade an non-secure translation regime's attributes
6117      * to secure.
6118      */
6119     attrs->secure = regime_is_secure(env, mmu_idx);
6120     attrs->user = regime_is_user(env, mmu_idx);
6121
6122     /* Fast Context Switch Extension. This doesn't exist at all in v8.
6123      * In v7 and earlier it affects all stage 1 translations.
6124      */
6125     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
6126         && !arm_feature(env, ARM_FEATURE_V8)) {
6127         if (regime_el(env, mmu_idx) == 3) {
6128             address += env->cp15.fcseidr_s;
6129         } else {
6130             address += env->cp15.fcseidr_ns;
6131         }
6132     }
6133
6134     /* pmsav7 has special handling for when MPU is disabled so call it before
6135      * the common MMU/MPU disabled check below.
6136      */
6137     if (arm_feature(env, ARM_FEATURE_MPU) &&
6138         arm_feature(env, ARM_FEATURE_V7)) {
6139         *page_size = TARGET_PAGE_SIZE;
6140         return get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
6141                                     phys_ptr, prot, fsr);
6142     }
6143
6144     if (regime_translation_disabled(env, mmu_idx)) {
6145         /* MMU/MPU disabled.  */
6146         *phys_ptr = address;
6147         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
6148         *page_size = TARGET_PAGE_SIZE;
6149         return 0;
6150     }
6151
6152     if (arm_feature(env, ARM_FEATURE_MPU)) {
6153         /* Pre-v7 MPU */
6154         *page_size = TARGET_PAGE_SIZE;
6155         return get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
6156                                     phys_ptr, prot, fsr);
6157     }
6158
6159     if (regime_using_lpae_format(env, mmu_idx)) {
6160         return get_phys_addr_lpae(env, address, access_type, mmu_idx, phys_ptr,
6161                                   attrs, prot, page_size, fsr);
6162     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
6163         return get_phys_addr_v6(env, address, access_type, mmu_idx, phys_ptr,
6164                                 attrs, prot, page_size, fsr);
6165     } else {
6166         return get_phys_addr_v5(env, address, access_type, mmu_idx, phys_ptr,
6167                                 prot, page_size, fsr);
6168     }
6169 }
6170
6171 /* Walk the page table and (if the mapping exists) add the page
6172  * to the TLB. Return false on success, or true on failure. Populate
6173  * fsr with ARM DFSR/IFSR fault register format value on failure.
6174  */
6175 bool arm_tlb_fill(CPUState *cs, vaddr address,
6176                   int access_type, int mmu_idx, uint32_t *fsr)
6177 {
6178     ARMCPU *cpu = ARM_CPU(cs);
6179     CPUARMState *env = &cpu->env;
6180     hwaddr phys_addr;
6181     target_ulong page_size;
6182     int prot;
6183     int ret;
6184     MemTxAttrs attrs = {};
6185
6186     ret = get_phys_addr(env, address, access_type, mmu_idx, &phys_addr,
6187                         &attrs, &prot, &page_size, fsr);
6188     if (!ret) {
6189         /* Map a single [sub]page.  */
6190         phys_addr &= TARGET_PAGE_MASK;
6191         address &= TARGET_PAGE_MASK;
6192         tlb_set_page_with_attrs(cs, address, phys_addr, attrs,
6193                                 prot, mmu_idx, page_size);
6194         return 0;
6195     }
6196
6197     return ret;
6198 }
6199
6200 hwaddr arm_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
6201 {
6202     ARMCPU *cpu = ARM_CPU(cs);
6203     CPUARMState *env = &cpu->env;
6204     hwaddr phys_addr;
6205     target_ulong page_size;
6206     int prot;
6207     bool ret;
6208     uint32_t fsr;
6209     MemTxAttrs attrs = {};
6210
6211     ret = get_phys_addr(env, addr, 0, cpu_mmu_index(env), &phys_addr,
6212                         &attrs, &prot, &page_size, &fsr);
6213
6214     if (ret) {
6215         return -1;
6216     }
6217
6218     return phys_addr;
6219 }
6220
6221 void HELPER(set_r13_banked)(CPUARMState *env, uint32_t mode, uint32_t val)
6222 {
6223     if ((env->uncached_cpsr & CPSR_M) == mode) {
6224         env->regs[13] = val;
6225     } else {
6226         env->banked_r13[bank_number(mode)] = val;
6227     }
6228 }
6229
6230 uint32_t HELPER(get_r13_banked)(CPUARMState *env, uint32_t mode)
6231 {
6232     if ((env->uncached_cpsr & CPSR_M) == mode) {
6233         return env->regs[13];
6234     } else {
6235         return env->banked_r13[bank_number(mode)];
6236     }
6237 }
6238
6239 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
6240 {
6241     ARMCPU *cpu = arm_env_get_cpu(env);
6242
6243     switch (reg) {
6244     case 0: /* APSR */
6245         return xpsr_read(env) & 0xf8000000;
6246     case 1: /* IAPSR */
6247         return xpsr_read(env) & 0xf80001ff;
6248     case 2: /* EAPSR */
6249         return xpsr_read(env) & 0xff00fc00;
6250     case 3: /* xPSR */
6251         return xpsr_read(env) & 0xff00fdff;
6252     case 5: /* IPSR */
6253         return xpsr_read(env) & 0x000001ff;
6254     case 6: /* EPSR */
6255         return xpsr_read(env) & 0x0700fc00;
6256     case 7: /* IEPSR */
6257         return xpsr_read(env) & 0x0700edff;
6258     case 8: /* MSP */
6259         return env->v7m.current_sp ? env->v7m.other_sp : env->regs[13];
6260     case 9: /* PSP */
6261         return env->v7m.current_sp ? env->regs[13] : env->v7m.other_sp;
6262     case 16: /* PRIMASK */
6263         return (env->daif & PSTATE_I) != 0;
6264     case 17: /* BASEPRI */
6265     case 18: /* BASEPRI_MAX */
6266         return env->v7m.basepri;
6267     case 19: /* FAULTMASK */
6268         return (env->daif & PSTATE_F) != 0;
6269     case 20: /* CONTROL */
6270         return env->v7m.control;
6271     default:
6272         /* ??? For debugging only.  */
6273         cpu_abort(CPU(cpu), "Unimplemented system register read (%d)\n", reg);
6274         return 0;
6275     }
6276 }
6277
6278 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
6279 {
6280     ARMCPU *cpu = arm_env_get_cpu(env);
6281
6282     switch (reg) {
6283     case 0: /* APSR */
6284         xpsr_write(env, val, 0xf8000000);
6285         break;
6286     case 1: /* IAPSR */
6287         xpsr_write(env, val, 0xf8000000);
6288         break;
6289     case 2: /* EAPSR */
6290         xpsr_write(env, val, 0xfe00fc00);
6291         break;
6292     case 3: /* xPSR */
6293         xpsr_write(env, val, 0xfe00fc00);
6294         break;
6295     case 5: /* IPSR */
6296         /* IPSR bits are readonly.  */
6297         break;
6298     case 6: /* EPSR */
6299         xpsr_write(env, val, 0x0600fc00);
6300         break;
6301     case 7: /* IEPSR */
6302         xpsr_write(env, val, 0x0600fc00);
6303         break;
6304     case 8: /* MSP */
6305         if (env->v7m.current_sp)
6306             env->v7m.other_sp = val;
6307         else
6308             env->regs[13] = val;
6309         break;
6310     case 9: /* PSP */
6311         if (env->v7m.current_sp)
6312             env->regs[13] = val;
6313         else
6314             env->v7m.other_sp = val;
6315         break;
6316     case 16: /* PRIMASK */
6317         if (val & 1) {
6318             env->daif |= PSTATE_I;
6319         } else {
6320             env->daif &= ~PSTATE_I;
6321         }
6322         break;
6323     case 17: /* BASEPRI */
6324         env->v7m.basepri = val & 0xff;
6325         break;
6326     case 18: /* BASEPRI_MAX */
6327         val &= 0xff;
6328         if (val != 0 && (val < env->v7m.basepri || env->v7m.basepri == 0))
6329             env->v7m.basepri = val;
6330         break;
6331     case 19: /* FAULTMASK */
6332         if (val & 1) {
6333             env->daif |= PSTATE_F;
6334         } else {
6335             env->daif &= ~PSTATE_F;
6336         }
6337         break;
6338     case 20: /* CONTROL */
6339         env->v7m.control = val & 3;
6340         switch_v7m_sp(env, (val & 2) != 0);
6341         break;
6342     default:
6343         /* ??? For debugging only.  */
6344         cpu_abort(CPU(cpu), "Unimplemented system register write (%d)\n", reg);
6345         return;
6346     }
6347 }
6348
6349 #endif
6350
6351 void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)
6352 {
6353     /* Implement DC ZVA, which zeroes a fixed-length block of memory.
6354      * Note that we do not implement the (architecturally mandated)
6355      * alignment fault for attempts to use this on Device memory
6356      * (which matches the usual QEMU behaviour of not implementing either
6357      * alignment faults or any memory attribute handling).
6358      */
6359
6360     ARMCPU *cpu = arm_env_get_cpu(env);
6361     uint64_t blocklen = 4 << cpu->dcz_blocksize;
6362     uint64_t vaddr = vaddr_in & ~(blocklen - 1);
6363
6364 #ifndef CONFIG_USER_ONLY
6365     {
6366         /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than
6367          * the block size so we might have to do more than one TLB lookup.
6368          * We know that in fact for any v8 CPU the page size is at least 4K
6369          * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only
6370          * 1K as an artefact of legacy v5 subpage support being present in the
6371          * same QEMU executable.
6372          */
6373         int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);
6374         void *hostaddr[maxidx];
6375         int try, i;
6376         unsigned mmu_idx = cpu_mmu_index(env);
6377         TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);
6378
6379         for (try = 0; try < 2; try++) {
6380
6381             for (i = 0; i < maxidx; i++) {
6382                 hostaddr[i] = tlb_vaddr_to_host(env,
6383                                                 vaddr + TARGET_PAGE_SIZE * i,
6384                                                 1, mmu_idx);
6385                 if (!hostaddr[i]) {
6386                     break;
6387                 }
6388             }
6389             if (i == maxidx) {
6390                 /* If it's all in the TLB it's fair game for just writing to;
6391                  * we know we don't need to update dirty status, etc.
6392                  */
6393                 for (i = 0; i < maxidx - 1; i++) {
6394                     memset(hostaddr[i], 0, TARGET_PAGE_SIZE);
6395                 }
6396                 memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));
6397                 return;
6398             }
6399             /* OK, try a store and see if we can populate the tlb. This
6400              * might cause an exception if the memory isn't writable,
6401              * in which case we will longjmp out of here. We must for
6402              * this purpose use the actual register value passed to us
6403              * so that we get the fault address right.
6404              */
6405             helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETRA());
6406             /* Now we can populate the other TLB entries, if any */
6407             for (i = 0; i < maxidx; i++) {
6408                 uint64_t va = vaddr + TARGET_PAGE_SIZE * i;
6409                 if (va != (vaddr_in & TARGET_PAGE_MASK)) {
6410                     helper_ret_stb_mmu(env, va, 0, oi, GETRA());
6411                 }
6412             }
6413         }
6414
6415         /* Slow path (probably attempt to do this to an I/O device or
6416          * similar, or clearing of a block of code we have translations
6417          * cached for). Just do a series of byte writes as the architecture
6418          * demands. It's not worth trying to use a cpu_physical_memory_map(),
6419          * memset(), unmap() sequence here because:
6420          *  + we'd need to account for the blocksize being larger than a page
6421          *  + the direct-RAM access case is almost always going to be dealt
6422          *    with in the fastpath code above, so there's no speed benefit
6423          *  + we would have to deal with the map returning NULL because the
6424          *    bounce buffer was in use
6425          */
6426         for (i = 0; i < blocklen; i++) {
6427             helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETRA());
6428         }
6429     }
6430 #else
6431     memset(g2h(vaddr), 0, blocklen);
6432 #endif
6433 }
6434
6435 /* Note that signed overflow is undefined in C.  The following routines are
6436    careful to use unsigned types where modulo arithmetic is required.
6437    Failure to do so _will_ break on newer gcc.  */
6438
6439 /* Signed saturating arithmetic.  */
6440
6441 /* Perform 16-bit signed saturating addition.  */
6442 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
6443 {
6444     uint16_t res;
6445
6446     res = a + b;
6447     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
6448         if (a & 0x8000)
6449             res = 0x8000;
6450         else
6451             res = 0x7fff;
6452     }
6453     return res;
6454 }
6455
6456 /* Perform 8-bit signed saturating addition.  */
6457 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
6458 {
6459     uint8_t res;
6460
6461     res = a + b;
6462     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
6463         if (a & 0x80)
6464             res = 0x80;
6465         else
6466             res = 0x7f;
6467     }
6468     return res;
6469 }
6470
6471 /* Perform 16-bit signed saturating subtraction.  */
6472 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
6473 {
6474     uint16_t res;
6475
6476     res = a - b;
6477     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
6478         if (a & 0x8000)
6479             res = 0x8000;
6480         else
6481             res = 0x7fff;
6482     }
6483     return res;
6484 }
6485
6486 /* Perform 8-bit signed saturating subtraction.  */
6487 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
6488 {
6489     uint8_t res;
6490
6491     res = a - b;
6492     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
6493         if (a & 0x80)
6494             res = 0x80;
6495         else
6496             res = 0x7f;
6497     }
6498     return res;
6499 }
6500
6501 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
6502 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
6503 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
6504 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
6505 #define PFX q
6506
6507 #include "op_addsub.h"
6508
6509 /* Unsigned saturating arithmetic.  */
6510 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
6511 {
6512     uint16_t res;
6513     res = a + b;
6514     if (res < a)
6515         res = 0xffff;
6516     return res;
6517 }
6518
6519 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
6520 {
6521     if (a > b)
6522         return a - b;
6523     else
6524         return 0;
6525 }
6526
6527 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
6528 {
6529     uint8_t res;
6530     res = a + b;
6531     if (res < a)
6532         res = 0xff;
6533     return res;
6534 }
6535
6536 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
6537 {
6538     if (a > b)
6539         return a - b;
6540     else
6541         return 0;
6542 }
6543
6544 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
6545 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
6546 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
6547 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
6548 #define PFX uq
6549
6550 #include "op_addsub.h"
6551
6552 /* Signed modulo arithmetic.  */
6553 #define SARITH16(a, b, n, op) do { \
6554     int32_t sum; \
6555     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
6556     RESULT(sum, n, 16); \
6557     if (sum >= 0) \
6558         ge |= 3 << (n * 2); \
6559     } while(0)
6560
6561 #define SARITH8(a, b, n, op) do { \
6562     int32_t sum; \
6563     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
6564     RESULT(sum, n, 8); \
6565     if (sum >= 0) \
6566         ge |= 1 << n; \
6567     } while(0)
6568
6569
6570 #define ADD16(a, b, n) SARITH16(a, b, n, +)
6571 #define SUB16(a, b, n) SARITH16(a, b, n, -)
6572 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
6573 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
6574 #define PFX s
6575 #define ARITH_GE
6576
6577 #include "op_addsub.h"
6578
6579 /* Unsigned modulo arithmetic.  */
6580 #define ADD16(a, b, n) do { \
6581     uint32_t sum; \
6582     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
6583     RESULT(sum, n, 16); \
6584     if ((sum >> 16) == 1) \
6585         ge |= 3 << (n * 2); \
6586     } while(0)
6587
6588 #define ADD8(a, b, n) do { \
6589     uint32_t sum; \
6590     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
6591     RESULT(sum, n, 8); \
6592     if ((sum >> 8) == 1) \
6593         ge |= 1 << n; \
6594     } while(0)
6595
6596 #define SUB16(a, b, n) do { \
6597     uint32_t sum; \
6598     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
6599     RESULT(sum, n, 16); \
6600     if ((sum >> 16) == 0) \
6601         ge |= 3 << (n * 2); \
6602     } while(0)
6603
6604 #define SUB8(a, b, n) do { \
6605     uint32_t sum; \
6606     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
6607     RESULT(sum, n, 8); \
6608     if ((sum >> 8) == 0) \
6609         ge |= 1 << n; \
6610     } while(0)
6611
6612 #define PFX u
6613 #define ARITH_GE
6614
6615 #include "op_addsub.h"
6616
6617 /* Halved signed arithmetic.  */
6618 #define ADD16(a, b, n) \
6619   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
6620 #define SUB16(a, b, n) \
6621   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
6622 #define ADD8(a, b, n) \
6623   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
6624 #define SUB8(a, b, n) \
6625   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
6626 #define PFX sh
6627
6628 #include "op_addsub.h"
6629
6630 /* Halved unsigned arithmetic.  */
6631 #define ADD16(a, b, n) \
6632   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
6633 #define SUB16(a, b, n) \
6634   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
6635 #define ADD8(a, b, n) \
6636   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
6637 #define SUB8(a, b, n) \
6638   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
6639 #define PFX uh
6640
6641 #include "op_addsub.h"
6642
6643 static inline uint8_t do_usad(uint8_t a, uint8_t b)
6644 {
6645     if (a > b)
6646         return a - b;
6647     else
6648         return b - a;
6649 }
6650
6651 /* Unsigned sum of absolute byte differences.  */
6652 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
6653 {
6654     uint32_t sum;
6655     sum = do_usad(a, b);
6656     sum += do_usad(a >> 8, b >> 8);
6657     sum += do_usad(a >> 16, b >>16);
6658     sum += do_usad(a >> 24, b >> 24);
6659     return sum;
6660 }
6661
6662 /* For ARMv6 SEL instruction.  */
6663 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
6664 {
6665     uint32_t mask;
6666
6667     mask = 0;
6668     if (flags & 1)
6669         mask |= 0xff;
6670     if (flags & 2)
6671         mask |= 0xff00;
6672     if (flags & 4)
6673         mask |= 0xff0000;
6674     if (flags & 8)
6675         mask |= 0xff000000;
6676     return (a & mask) | (b & ~mask);
6677 }
6678
6679 /* VFP support.  We follow the convention used for VFP instructions:
6680    Single precision routines have a "s" suffix, double precision a
6681    "d" suffix.  */
6682
6683 /* Convert host exception flags to vfp form.  */
6684 static inline int vfp_exceptbits_from_host(int host_bits)
6685 {
6686     int target_bits = 0;
6687
6688     if (host_bits & float_flag_invalid)
6689         target_bits |= 1;
6690     if (host_bits & float_flag_divbyzero)
6691         target_bits |= 2;
6692     if (host_bits & float_flag_overflow)
6693         target_bits |= 4;
6694     if (host_bits & (float_flag_underflow | float_flag_output_denormal))
6695         target_bits |= 8;
6696     if (host_bits & float_flag_inexact)
6697         target_bits |= 0x10;
6698     if (host_bits & float_flag_input_denormal)
6699         target_bits |= 0x80;
6700     return target_bits;
6701 }
6702
6703 uint32_t HELPER(vfp_get_fpscr)(CPUARMState *env)
6704 {
6705     int i;
6706     uint32_t fpscr;
6707
6708     fpscr = (env->vfp.xregs[ARM_VFP_FPSCR] & 0xffc8ffff)
6709             | (env->vfp.vec_len << 16)
6710             | (env->vfp.vec_stride << 20);
6711     i = get_float_exception_flags(&env->vfp.fp_status);
6712     i |= get_float_exception_flags(&env->vfp.standard_fp_status);
6713     fpscr |= vfp_exceptbits_from_host(i);
6714     return fpscr;
6715 }
6716
6717 uint32_t vfp_get_fpscr(CPUARMState *env)
6718 {
6719     return HELPER(vfp_get_fpscr)(env);
6720 }
6721
6722 /* Convert vfp exception flags to target form.  */
6723 static inline int vfp_exceptbits_to_host(int target_bits)
6724 {
6725     int host_bits = 0;
6726
6727     if (target_bits & 1)
6728         host_bits |= float_flag_invalid;
6729     if (target_bits & 2)
6730         host_bits |= float_flag_divbyzero;
6731     if (target_bits & 4)
6732         host_bits |= float_flag_overflow;
6733     if (target_bits & 8)
6734         host_bits |= float_flag_underflow;
6735     if (target_bits & 0x10)
6736         host_bits |= float_flag_inexact;
6737     if (target_bits & 0x80)
6738         host_bits |= float_flag_input_denormal;
6739     return host_bits;
6740 }
6741
6742 void HELPER(vfp_set_fpscr)(CPUARMState *env, uint32_t val)
6743 {
6744     int i;
6745     uint32_t changed;
6746
6747     changed = env->vfp.xregs[ARM_VFP_FPSCR];
6748     env->vfp.xregs[ARM_VFP_FPSCR] = (val & 0xffc8ffff);
6749     env->vfp.vec_len = (val >> 16) & 7;
6750     env->vfp.vec_stride = (val >> 20) & 3;
6751
6752     changed ^= val;
6753     if (changed & (3 << 22)) {
6754         i = (val >> 22) & 3;
6755         switch (i) {
6756         case FPROUNDING_TIEEVEN:
6757             i = float_round_nearest_even;
6758             break;
6759         case FPROUNDING_POSINF:
6760             i = float_round_up;
6761             break;
6762         case FPROUNDING_NEGINF:
6763             i = float_round_down;
6764             break;
6765         case FPROUNDING_ZERO:
6766             i = float_round_to_zero;
6767             break;
6768         }
6769         set_float_rounding_mode(i, &env->vfp.fp_status);
6770     }
6771     if (changed & (1 << 24)) {
6772         set_flush_to_zero((val & (1 << 24)) != 0, &env->vfp.fp_status);
6773         set_flush_inputs_to_zero((val & (1 << 24)) != 0, &env->vfp.fp_status);
6774     }
6775     if (changed & (1 << 25))
6776         set_default_nan_mode((val & (1 << 25)) != 0, &env->vfp.fp_status);
6777
6778     i = vfp_exceptbits_to_host(val);
6779     set_float_exception_flags(i, &env->vfp.fp_status);
6780     set_float_exception_flags(0, &env->vfp.standard_fp_status);
6781 }
6782
6783 void vfp_set_fpscr(CPUARMState *env, uint32_t val)
6784 {
6785     HELPER(vfp_set_fpscr)(env, val);
6786 }
6787
6788 #define VFP_HELPER(name, p) HELPER(glue(glue(vfp_,name),p))
6789
6790 #define VFP_BINOP(name) \
6791 float32 VFP_HELPER(name, s)(float32 a, float32 b, void *fpstp) \
6792 { \
6793     float_status *fpst = fpstp; \
6794     return float32_ ## name(a, b, fpst); \
6795 } \
6796 float64 VFP_HELPER(name, d)(float64 a, float64 b, void *fpstp) \
6797 { \
6798     float_status *fpst = fpstp; \
6799     return float64_ ## name(a, b, fpst); \
6800 }
6801 VFP_BINOP(add)
6802 VFP_BINOP(sub)
6803 VFP_BINOP(mul)
6804 VFP_BINOP(div)
6805 VFP_BINOP(min)
6806 VFP_BINOP(max)
6807 VFP_BINOP(minnum)
6808 VFP_BINOP(maxnum)
6809 #undef VFP_BINOP
6810
6811 float32 VFP_HELPER(neg, s)(float32 a)
6812 {
6813     return float32_chs(a);
6814 }
6815
6816 float64 VFP_HELPER(neg, d)(float64 a)
6817 {
6818     return float64_chs(a);
6819 }
6820
6821 float32 VFP_HELPER(abs, s)(float32 a)
6822 {
6823     return float32_abs(a);
6824 }
6825
6826 float64 VFP_HELPER(abs, d)(float64 a)
6827 {
6828     return float64_abs(a);
6829 }
6830
6831 float32 VFP_HELPER(sqrt, s)(float32 a, CPUARMState *env)
6832 {
6833     return float32_sqrt(a, &env->vfp.fp_status);
6834 }
6835
6836 float64 VFP_HELPER(sqrt, d)(float64 a, CPUARMState *env)
6837 {
6838     return float64_sqrt(a, &env->vfp.fp_status);
6839 }
6840
6841 /* XXX: check quiet/signaling case */
6842 #define DO_VFP_cmp(p, type) \
6843 void VFP_HELPER(cmp, p)(type a, type b, CPUARMState *env)  \
6844 { \
6845     uint32_t flags; \
6846     switch(type ## _compare_quiet(a, b, &env->vfp.fp_status)) { \
6847     case 0: flags = 0x6; break; \
6848     case -1: flags = 0x8; break; \
6849     case 1: flags = 0x2; break; \
6850     default: case 2: flags = 0x3; break; \
6851     } \
6852     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
6853         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
6854 } \
6855 void VFP_HELPER(cmpe, p)(type a, type b, CPUARMState *env) \
6856 { \
6857     uint32_t flags; \
6858     switch(type ## _compare(a, b, &env->vfp.fp_status)) { \
6859     case 0: flags = 0x6; break; \
6860     case -1: flags = 0x8; break; \
6861     case 1: flags = 0x2; break; \
6862     default: case 2: flags = 0x3; break; \
6863     } \
6864     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
6865         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
6866 }
6867 DO_VFP_cmp(s, float32)
6868 DO_VFP_cmp(d, float64)
6869 #undef DO_VFP_cmp
6870
6871 /* Integer to float and float to integer conversions */
6872
6873 #define CONV_ITOF(name, fsz, sign) \
6874     float##fsz HELPER(name)(uint32_t x, void *fpstp) \
6875 { \
6876     float_status *fpst = fpstp; \
6877     return sign##int32_to_##float##fsz((sign##int32_t)x, fpst); \
6878 }
6879
6880 #define CONV_FTOI(name, fsz, sign, round) \
6881 uint32_t HELPER(name)(float##fsz x, void *fpstp) \
6882 { \
6883     float_status *fpst = fpstp; \
6884     if (float##fsz##_is_any_nan(x)) { \
6885         float_raise(float_flag_invalid, fpst); \
6886         return 0; \
6887     } \
6888     return float##fsz##_to_##sign##int32##round(x, fpst); \
6889 }
6890
6891 #define FLOAT_CONVS(name, p, fsz, sign) \
6892 CONV_ITOF(vfp_##name##to##p, fsz, sign) \
6893 CONV_FTOI(vfp_to##name##p, fsz, sign, ) \
6894 CONV_FTOI(vfp_to##name##z##p, fsz, sign, _round_to_zero)
6895
6896 FLOAT_CONVS(si, s, 32, )
6897 FLOAT_CONVS(si, d, 64, )
6898 FLOAT_CONVS(ui, s, 32, u)
6899 FLOAT_CONVS(ui, d, 64, u)
6900
6901 #undef CONV_ITOF
6902 #undef CONV_FTOI
6903 #undef FLOAT_CONVS
6904
6905 /* floating point conversion */
6906 float64 VFP_HELPER(fcvtd, s)(float32 x, CPUARMState *env)
6907 {
6908     float64 r = float32_to_float64(x, &env->vfp.fp_status);
6909     /* ARM requires that S<->D conversion of any kind of NaN generates
6910      * a quiet NaN by forcing the most significant frac bit to 1.
6911      */
6912     return float64_maybe_silence_nan(r);
6913 }
6914
6915 float32 VFP_HELPER(fcvts, d)(float64 x, CPUARMState *env)
6916 {
6917     float32 r =  float64_to_float32(x, &env->vfp.fp_status);
6918     /* ARM requires that S<->D conversion of any kind of NaN generates
6919      * a quiet NaN by forcing the most significant frac bit to 1.
6920      */
6921     return float32_maybe_silence_nan(r);
6922 }
6923
6924 /* VFP3 fixed point conversion.  */
6925 #define VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype) \
6926 float##fsz HELPER(vfp_##name##to##p)(uint##isz##_t  x, uint32_t shift, \
6927                                      void *fpstp) \
6928 { \
6929     float_status *fpst = fpstp; \
6930     float##fsz tmp; \
6931     tmp = itype##_to_##float##fsz(x, fpst); \
6932     return float##fsz##_scalbn(tmp, -(int)shift, fpst); \
6933 }
6934
6935 /* Notice that we want only input-denormal exception flags from the
6936  * scalbn operation: the other possible flags (overflow+inexact if
6937  * we overflow to infinity, output-denormal) aren't correct for the
6938  * complete scale-and-convert operation.
6939  */
6940 #define VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, round) \
6941 uint##isz##_t HELPER(vfp_to##name##p##round)(float##fsz x, \
6942                                              uint32_t shift, \
6943                                              void *fpstp) \
6944 { \
6945     float_status *fpst = fpstp; \
6946     int old_exc_flags = get_float_exception_flags(fpst); \
6947     float##fsz tmp; \
6948     if (float##fsz##_is_any_nan(x)) { \
6949         float_raise(float_flag_invalid, fpst); \
6950         return 0; \
6951     } \
6952     tmp = float##fsz##_scalbn(x, shift, fpst); \
6953     old_exc_flags |= get_float_exception_flags(fpst) \
6954         & float_flag_input_denormal; \
6955     set_float_exception_flags(old_exc_flags, fpst); \
6956     return float##fsz##_to_##itype##round(tmp, fpst); \
6957 }
6958
6959 #define VFP_CONV_FIX(name, p, fsz, isz, itype)                   \
6960 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
6961 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, _round_to_zero) \
6962 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
6963
6964 #define VFP_CONV_FIX_A64(name, p, fsz, isz, itype)               \
6965 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
6966 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
6967
6968 VFP_CONV_FIX(sh, d, 64, 64, int16)
6969 VFP_CONV_FIX(sl, d, 64, 64, int32)
6970 VFP_CONV_FIX_A64(sq, d, 64, 64, int64)
6971 VFP_CONV_FIX(uh, d, 64, 64, uint16)
6972 VFP_CONV_FIX(ul, d, 64, 64, uint32)
6973 VFP_CONV_FIX_A64(uq, d, 64, 64, uint64)
6974 VFP_CONV_FIX(sh, s, 32, 32, int16)
6975 VFP_CONV_FIX(sl, s, 32, 32, int32)
6976 VFP_CONV_FIX_A64(sq, s, 32, 64, int64)
6977 VFP_CONV_FIX(uh, s, 32, 32, uint16)
6978 VFP_CONV_FIX(ul, s, 32, 32, uint32)
6979 VFP_CONV_FIX_A64(uq, s, 32, 64, uint64)
6980 #undef VFP_CONV_FIX
6981 #undef VFP_CONV_FIX_FLOAT
6982 #undef VFP_CONV_FLOAT_FIX_ROUND
6983
6984 /* Set the current fp rounding mode and return the old one.
6985  * The argument is a softfloat float_round_ value.
6986  */
6987 uint32_t HELPER(set_rmode)(uint32_t rmode, CPUARMState *env)
6988 {
6989     float_status *fp_status = &env->vfp.fp_status;
6990
6991     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
6992     set_float_rounding_mode(rmode, fp_status);
6993
6994     return prev_rmode;
6995 }
6996
6997 /* Set the current fp rounding mode in the standard fp status and return
6998  * the old one. This is for NEON instructions that need to change the
6999  * rounding mode but wish to use the standard FPSCR values for everything
7000  * else. Always set the rounding mode back to the correct value after
7001  * modifying it.
7002  * The argument is a softfloat float_round_ value.
7003  */
7004 uint32_t HELPER(set_neon_rmode)(uint32_t rmode, CPUARMState *env)
7005 {
7006     float_status *fp_status = &env->vfp.standard_fp_status;
7007
7008     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
7009     set_float_rounding_mode(rmode, fp_status);
7010
7011     return prev_rmode;
7012 }
7013
7014 /* Half precision conversions.  */
7015 static float32 do_fcvt_f16_to_f32(uint32_t a, CPUARMState *env, float_status *s)
7016 {
7017     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
7018     float32 r = float16_to_float32(make_float16(a), ieee, s);
7019     if (ieee) {
7020         return float32_maybe_silence_nan(r);
7021     }
7022     return r;
7023 }
7024
7025 static uint32_t do_fcvt_f32_to_f16(float32 a, CPUARMState *env, float_status *s)
7026 {
7027     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
7028     float16 r = float32_to_float16(a, ieee, s);
7029     if (ieee) {
7030         r = float16_maybe_silence_nan(r);
7031     }
7032     return float16_val(r);
7033 }
7034
7035 float32 HELPER(neon_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
7036 {
7037     return do_fcvt_f16_to_f32(a, env, &env->vfp.standard_fp_status);
7038 }
7039
7040 uint32_t HELPER(neon_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
7041 {
7042     return do_fcvt_f32_to_f16(a, env, &env->vfp.standard_fp_status);
7043 }
7044
7045 float32 HELPER(vfp_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
7046 {
7047     return do_fcvt_f16_to_f32(a, env, &env->vfp.fp_status);
7048 }
7049
7050 uint32_t HELPER(vfp_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
7051 {
7052     return do_fcvt_f32_to_f16(a, env, &env->vfp.fp_status);
7053 }
7054
7055 float64 HELPER(vfp_fcvt_f16_to_f64)(uint32_t a, CPUARMState *env)
7056 {
7057     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
7058     float64 r = float16_to_float64(make_float16(a), ieee, &env->vfp.fp_status);
7059     if (ieee) {
7060         return float64_maybe_silence_nan(r);
7061     }
7062     return r;
7063 }
7064
7065 uint32_t HELPER(vfp_fcvt_f64_to_f16)(float64 a, CPUARMState *env)
7066 {
7067     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
7068     float16 r = float64_to_float16(a, ieee, &env->vfp.fp_status);
7069     if (ieee) {
7070         r = float16_maybe_silence_nan(r);
7071     }
7072     return float16_val(r);
7073 }
7074
7075 #define float32_two make_float32(0x40000000)
7076 #define float32_three make_float32(0x40400000)
7077 #define float32_one_point_five make_float32(0x3fc00000)
7078
7079 float32 HELPER(recps_f32)(float32 a, float32 b, CPUARMState *env)
7080 {
7081     float_status *s = &env->vfp.standard_fp_status;
7082     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
7083         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
7084         if (!(float32_is_zero(a) || float32_is_zero(b))) {
7085             float_raise(float_flag_input_denormal, s);
7086         }
7087         return float32_two;
7088     }
7089     return float32_sub(float32_two, float32_mul(a, b, s), s);
7090 }
7091
7092 float32 HELPER(rsqrts_f32)(float32 a, float32 b, CPUARMState *env)
7093 {
7094     float_status *s = &env->vfp.standard_fp_status;
7095     float32 product;
7096     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
7097         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
7098         if (!(float32_is_zero(a) || float32_is_zero(b))) {
7099             float_raise(float_flag_input_denormal, s);
7100         }
7101         return float32_one_point_five;
7102     }
7103     product = float32_mul(a, b, s);
7104     return float32_div(float32_sub(float32_three, product, s), float32_two, s);
7105 }
7106
7107 /* NEON helpers.  */
7108
7109 /* Constants 256 and 512 are used in some helpers; we avoid relying on
7110  * int->float conversions at run-time.  */
7111 #define float64_256 make_float64(0x4070000000000000LL)
7112 #define float64_512 make_float64(0x4080000000000000LL)
7113 #define float32_maxnorm make_float32(0x7f7fffff)
7114 #define float64_maxnorm make_float64(0x7fefffffffffffffLL)
7115
7116 /* Reciprocal functions
7117  *
7118  * The algorithm that must be used to calculate the estimate
7119  * is specified by the ARM ARM, see FPRecipEstimate()
7120  */
7121
7122 static float64 recip_estimate(float64 a, float_status *real_fp_status)
7123 {
7124     /* These calculations mustn't set any fp exception flags,
7125      * so we use a local copy of the fp_status.
7126      */
7127     float_status dummy_status = *real_fp_status;
7128     float_status *s = &dummy_status;
7129     /* q = (int)(a * 512.0) */
7130     float64 q = float64_mul(float64_512, a, s);
7131     int64_t q_int = float64_to_int64_round_to_zero(q, s);
7132
7133     /* r = 1.0 / (((double)q + 0.5) / 512.0) */
7134     q = int64_to_float64(q_int, s);
7135     q = float64_add(q, float64_half, s);
7136     q = float64_div(q, float64_512, s);
7137     q = float64_div(float64_one, q, s);
7138
7139     /* s = (int)(256.0 * r + 0.5) */
7140     q = float64_mul(q, float64_256, s);
7141     q = float64_add(q, float64_half, s);
7142     q_int = float64_to_int64_round_to_zero(q, s);
7143
7144     /* return (double)s / 256.0 */
7145     return float64_div(int64_to_float64(q_int, s), float64_256, s);
7146 }
7147
7148 /* Common wrapper to call recip_estimate */
7149 static float64 call_recip_estimate(float64 num, int off, float_status *fpst)
7150 {
7151     uint64_t val64 = float64_val(num);
7152     uint64_t frac = extract64(val64, 0, 52);
7153     int64_t exp = extract64(val64, 52, 11);
7154     uint64_t sbit;
7155     float64 scaled, estimate;
7156
7157     /* Generate the scaled number for the estimate function */
7158     if (exp == 0) {
7159         if (extract64(frac, 51, 1) == 0) {
7160             exp = -1;
7161             frac = extract64(frac, 0, 50) << 2;
7162         } else {
7163             frac = extract64(frac, 0, 51) << 1;
7164         }
7165     }
7166
7167     /* scaled = '0' : '01111111110' : fraction<51:44> : Zeros(44); */
7168     scaled = make_float64((0x3feULL << 52)
7169                           | extract64(frac, 44, 8) << 44);
7170
7171     estimate = recip_estimate(scaled, fpst);
7172
7173     /* Build new result */
7174     val64 = float64_val(estimate);
7175     sbit = 0x8000000000000000ULL & val64;
7176     exp = off - exp;
7177     frac = extract64(val64, 0, 52);
7178
7179     if (exp == 0) {
7180         frac = 1ULL << 51 | extract64(frac, 1, 51);
7181     } else if (exp == -1) {
7182         frac = 1ULL << 50 | extract64(frac, 2, 50);
7183         exp = 0;
7184     }
7185
7186     return make_float64(sbit | (exp << 52) | frac);
7187 }
7188
7189 static bool round_to_inf(float_status *fpst, bool sign_bit)
7190 {
7191     switch (fpst->float_rounding_mode) {
7192     case float_round_nearest_even: /* Round to Nearest */
7193         return true;
7194     case float_round_up: /* Round to +Inf */
7195         return !sign_bit;
7196     case float_round_down: /* Round to -Inf */
7197         return sign_bit;
7198     case float_round_to_zero: /* Round to Zero */
7199         return false;
7200     }
7201
7202     g_assert_not_reached();
7203 }
7204
7205 float32 HELPER(recpe_f32)(float32 input, void *fpstp)
7206 {
7207     float_status *fpst = fpstp;
7208     float32 f32 = float32_squash_input_denormal(input, fpst);
7209     uint32_t f32_val = float32_val(f32);
7210     uint32_t f32_sbit = 0x80000000ULL & f32_val;
7211     int32_t f32_exp = extract32(f32_val, 23, 8);
7212     uint32_t f32_frac = extract32(f32_val, 0, 23);
7213     float64 f64, r64;
7214     uint64_t r64_val;
7215     int64_t r64_exp;
7216     uint64_t r64_frac;
7217
7218     if (float32_is_any_nan(f32)) {
7219         float32 nan = f32;
7220         if (float32_is_signaling_nan(f32)) {
7221             float_raise(float_flag_invalid, fpst);
7222             nan = float32_maybe_silence_nan(f32);
7223         }
7224         if (fpst->default_nan_mode) {
7225             nan =  float32_default_nan;
7226         }
7227         return nan;
7228     } else if (float32_is_infinity(f32)) {
7229         return float32_set_sign(float32_zero, float32_is_neg(f32));
7230     } else if (float32_is_zero(f32)) {
7231         float_raise(float_flag_divbyzero, fpst);
7232         return float32_set_sign(float32_infinity, float32_is_neg(f32));
7233     } else if ((f32_val & ~(1ULL << 31)) < (1ULL << 21)) {
7234         /* Abs(value) < 2.0^-128 */
7235         float_raise(float_flag_overflow | float_flag_inexact, fpst);
7236         if (round_to_inf(fpst, f32_sbit)) {
7237             return float32_set_sign(float32_infinity, float32_is_neg(f32));
7238         } else {
7239             return float32_set_sign(float32_maxnorm, float32_is_neg(f32));
7240         }
7241     } else if (f32_exp >= 253 && fpst->flush_to_zero) {
7242         float_raise(float_flag_underflow, fpst);
7243         return float32_set_sign(float32_zero, float32_is_neg(f32));
7244     }
7245
7246
7247     f64 = make_float64(((int64_t)(f32_exp) << 52) | (int64_t)(f32_frac) << 29);
7248     r64 = call_recip_estimate(f64, 253, fpst);
7249     r64_val = float64_val(r64);
7250     r64_exp = extract64(r64_val, 52, 11);
7251     r64_frac = extract64(r64_val, 0, 52);
7252
7253     /* result = sign : result_exp<7:0> : fraction<51:29>; */
7254     return make_float32(f32_sbit |
7255                         (r64_exp & 0xff) << 23 |
7256                         extract64(r64_frac, 29, 24));
7257 }
7258
7259 float64 HELPER(recpe_f64)(float64 input, void *fpstp)
7260 {
7261     float_status *fpst = fpstp;
7262     float64 f64 = float64_squash_input_denormal(input, fpst);
7263     uint64_t f64_val = float64_val(f64);
7264     uint64_t f64_sbit = 0x8000000000000000ULL & f64_val;
7265     int64_t f64_exp = extract64(f64_val, 52, 11);
7266     float64 r64;
7267     uint64_t r64_val;
7268     int64_t r64_exp;
7269     uint64_t r64_frac;
7270
7271     /* Deal with any special cases */
7272     if (float64_is_any_nan(f64)) {
7273         float64 nan = f64;
7274         if (float64_is_signaling_nan(f64)) {
7275             float_raise(float_flag_invalid, fpst);
7276             nan = float64_maybe_silence_nan(f64);
7277         }
7278         if (fpst->default_nan_mode) {
7279             nan =  float64_default_nan;
7280         }
7281         return nan;
7282     } else if (float64_is_infinity(f64)) {
7283         return float64_set_sign(float64_zero, float64_is_neg(f64));
7284     } else if (float64_is_zero(f64)) {
7285         float_raise(float_flag_divbyzero, fpst);
7286         return float64_set_sign(float64_infinity, float64_is_neg(f64));
7287     } else if ((f64_val & ~(1ULL << 63)) < (1ULL << 50)) {
7288         /* Abs(value) < 2.0^-1024 */
7289         float_raise(float_flag_overflow | float_flag_inexact, fpst);
7290         if (round_to_inf(fpst, f64_sbit)) {
7291             return float64_set_sign(float64_infinity, float64_is_neg(f64));
7292         } else {
7293             return float64_set_sign(float64_maxnorm, float64_is_neg(f64));
7294         }
7295     } else if (f64_exp >= 2045 && fpst->flush_to_zero) {
7296         float_raise(float_flag_underflow, fpst);
7297         return float64_set_sign(float64_zero, float64_is_neg(f64));
7298     }
7299
7300     r64 = call_recip_estimate(f64, 2045, fpst);
7301     r64_val = float64_val(r64);
7302     r64_exp = extract64(r64_val, 52, 11);
7303     r64_frac = extract64(r64_val, 0, 52);
7304
7305     /* result = sign : result_exp<10:0> : fraction<51:0> */
7306     return make_float64(f64_sbit |
7307                         ((r64_exp & 0x7ff) << 52) |
7308                         r64_frac);
7309 }
7310
7311 /* The algorithm that must be used to calculate the estimate
7312  * is specified by the ARM ARM.
7313  */
7314 static float64 recip_sqrt_estimate(float64 a, float_status *real_fp_status)
7315 {
7316     /* These calculations mustn't set any fp exception flags,
7317      * so we use a local copy of the fp_status.
7318      */
7319     float_status dummy_status = *real_fp_status;
7320     float_status *s = &dummy_status;
7321     float64 q;
7322     int64_t q_int;
7323
7324     if (float64_lt(a, float64_half, s)) {
7325         /* range 0.25 <= a < 0.5 */
7326
7327         /* a in units of 1/512 rounded down */
7328         /* q0 = (int)(a * 512.0);  */
7329         q = float64_mul(float64_512, a, s);
7330         q_int = float64_to_int64_round_to_zero(q, s);
7331
7332         /* reciprocal root r */
7333         /* r = 1.0 / sqrt(((double)q0 + 0.5) / 512.0);  */
7334         q = int64_to_float64(q_int, s);
7335         q = float64_add(q, float64_half, s);
7336         q = float64_div(q, float64_512, s);
7337         q = float64_sqrt(q, s);
7338         q = float64_div(float64_one, q, s);
7339     } else {
7340         /* range 0.5 <= a < 1.0 */
7341
7342         /* a in units of 1/256 rounded down */
7343         /* q1 = (int)(a * 256.0); */
7344         q = float64_mul(float64_256, a, s);
7345         int64_t q_int = float64_to_int64_round_to_zero(q, s);
7346
7347         /* reciprocal root r */
7348         /* r = 1.0 /sqrt(((double)q1 + 0.5) / 256); */
7349         q = int64_to_float64(q_int, s);
7350         q = float64_add(q, float64_half, s);
7351         q = float64_div(q, float64_256, s);
7352         q = float64_sqrt(q, s);
7353         q = float64_div(float64_one, q, s);
7354     }
7355     /* r in units of 1/256 rounded to nearest */
7356     /* s = (int)(256.0 * r + 0.5); */
7357
7358     q = float64_mul(q, float64_256,s );
7359     q = float64_add(q, float64_half, s);
7360     q_int = float64_to_int64_round_to_zero(q, s);
7361
7362     /* return (double)s / 256.0;*/
7363     return float64_div(int64_to_float64(q_int, s), float64_256, s);
7364 }
7365
7366 float32 HELPER(rsqrte_f32)(float32 input, void *fpstp)
7367 {
7368     float_status *s = fpstp;
7369     float32 f32 = float32_squash_input_denormal(input, s);
7370     uint32_t val = float32_val(f32);
7371     uint32_t f32_sbit = 0x80000000 & val;
7372     int32_t f32_exp = extract32(val, 23, 8);
7373     uint32_t f32_frac = extract32(val, 0, 23);
7374     uint64_t f64_frac;
7375     uint64_t val64;
7376     int result_exp;
7377     float64 f64;
7378
7379     if (float32_is_any_nan(f32)) {
7380         float32 nan = f32;
7381         if (float32_is_signaling_nan(f32)) {
7382             float_raise(float_flag_invalid, s);
7383             nan = float32_maybe_silence_nan(f32);
7384         }
7385         if (s->default_nan_mode) {
7386             nan =  float32_default_nan;
7387         }
7388         return nan;
7389     } else if (float32_is_zero(f32)) {
7390         float_raise(float_flag_divbyzero, s);
7391         return float32_set_sign(float32_infinity, float32_is_neg(f32));
7392     } else if (float32_is_neg(f32)) {
7393         float_raise(float_flag_invalid, s);
7394         return float32_default_nan;
7395     } else if (float32_is_infinity(f32)) {
7396         return float32_zero;
7397     }
7398
7399     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
7400      * preserving the parity of the exponent.  */
7401
7402     f64_frac = ((uint64_t) f32_frac) << 29;
7403     if (f32_exp == 0) {
7404         while (extract64(f64_frac, 51, 1) == 0) {
7405             f64_frac = f64_frac << 1;
7406             f32_exp = f32_exp-1;
7407         }
7408         f64_frac = extract64(f64_frac, 0, 51) << 1;
7409     }
7410
7411     if (extract64(f32_exp, 0, 1) == 0) {
7412         f64 = make_float64(((uint64_t) f32_sbit) << 32
7413                            | (0x3feULL << 52)
7414                            | f64_frac);
7415     } else {
7416         f64 = make_float64(((uint64_t) f32_sbit) << 32
7417                            | (0x3fdULL << 52)
7418                            | f64_frac);
7419     }
7420
7421     result_exp = (380 - f32_exp) / 2;
7422
7423     f64 = recip_sqrt_estimate(f64, s);
7424
7425     val64 = float64_val(f64);
7426
7427     val = ((result_exp & 0xff) << 23)
7428         | ((val64 >> 29)  & 0x7fffff);
7429     return make_float32(val);
7430 }
7431
7432 float64 HELPER(rsqrte_f64)(float64 input, void *fpstp)
7433 {
7434     float_status *s = fpstp;
7435     float64 f64 = float64_squash_input_denormal(input, s);
7436     uint64_t val = float64_val(f64);
7437     uint64_t f64_sbit = 0x8000000000000000ULL & val;
7438     int64_t f64_exp = extract64(val, 52, 11);
7439     uint64_t f64_frac = extract64(val, 0, 52);
7440     int64_t result_exp;
7441     uint64_t result_frac;
7442
7443     if (float64_is_any_nan(f64)) {
7444         float64 nan = f64;
7445         if (float64_is_signaling_nan(f64)) {
7446             float_raise(float_flag_invalid, s);
7447             nan = float64_maybe_silence_nan(f64);
7448         }
7449         if (s->default_nan_mode) {
7450             nan =  float64_default_nan;
7451         }
7452         return nan;
7453     } else if (float64_is_zero(f64)) {
7454         float_raise(float_flag_divbyzero, s);
7455         return float64_set_sign(float64_infinity, float64_is_neg(f64));
7456     } else if (float64_is_neg(f64)) {
7457         float_raise(float_flag_invalid, s);
7458         return float64_default_nan;
7459     } else if (float64_is_infinity(f64)) {
7460         return float64_zero;
7461     }
7462
7463     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
7464      * preserving the parity of the exponent.  */
7465
7466     if (f64_exp == 0) {
7467         while (extract64(f64_frac, 51, 1) == 0) {
7468             f64_frac = f64_frac << 1;
7469             f64_exp = f64_exp - 1;
7470         }
7471         f64_frac = extract64(f64_frac, 0, 51) << 1;
7472     }
7473
7474     if (extract64(f64_exp, 0, 1) == 0) {
7475         f64 = make_float64(f64_sbit
7476                            | (0x3feULL << 52)
7477                            | f64_frac);
7478     } else {
7479         f64 = make_float64(f64_sbit
7480                            | (0x3fdULL << 52)
7481                            | f64_frac);
7482     }
7483
7484     result_exp = (3068 - f64_exp) / 2;
7485
7486     f64 = recip_sqrt_estimate(f64, s);
7487
7488     result_frac = extract64(float64_val(f64), 0, 52);
7489
7490     return make_float64(f64_sbit |
7491                         ((result_exp & 0x7ff) << 52) |
7492                         result_frac);
7493 }
7494
7495 uint32_t HELPER(recpe_u32)(uint32_t a, void *fpstp)
7496 {
7497     float_status *s = fpstp;
7498     float64 f64;
7499
7500     if ((a & 0x80000000) == 0) {
7501         return 0xffffffff;
7502     }
7503
7504     f64 = make_float64((0x3feULL << 52)
7505                        | ((int64_t)(a & 0x7fffffff) << 21));
7506
7507     f64 = recip_estimate(f64, s);
7508
7509     return 0x80000000 | ((float64_val(f64) >> 21) & 0x7fffffff);
7510 }
7511
7512 uint32_t HELPER(rsqrte_u32)(uint32_t a, void *fpstp)
7513 {
7514     float_status *fpst = fpstp;
7515     float64 f64;
7516
7517     if ((a & 0xc0000000) == 0) {
7518         return 0xffffffff;
7519     }
7520
7521     if (a & 0x80000000) {
7522         f64 = make_float64((0x3feULL << 52)
7523                            | ((uint64_t)(a & 0x7fffffff) << 21));
7524     } else { /* bits 31-30 == '01' */
7525         f64 = make_float64((0x3fdULL << 52)
7526                            | ((uint64_t)(a & 0x3fffffff) << 22));
7527     }
7528
7529     f64 = recip_sqrt_estimate(f64, fpst);
7530
7531     return 0x80000000 | ((float64_val(f64) >> 21) & 0x7fffffff);
7532 }
7533
7534 /* VFPv4 fused multiply-accumulate */
7535 float32 VFP_HELPER(muladd, s)(float32 a, float32 b, float32 c, void *fpstp)
7536 {
7537     float_status *fpst = fpstp;
7538     return float32_muladd(a, b, c, 0, fpst);
7539 }
7540
7541 float64 VFP_HELPER(muladd, d)(float64 a, float64 b, float64 c, void *fpstp)
7542 {
7543     float_status *fpst = fpstp;
7544     return float64_muladd(a, b, c, 0, fpst);
7545 }
7546
7547 /* ARMv8 round to integral */
7548 float32 HELPER(rints_exact)(float32 x, void *fp_status)
7549 {
7550     return float32_round_to_int(x, fp_status);
7551 }
7552
7553 float64 HELPER(rintd_exact)(float64 x, void *fp_status)
7554 {
7555     return float64_round_to_int(x, fp_status);
7556 }
7557
7558 float32 HELPER(rints)(float32 x, void *fp_status)
7559 {
7560     int old_flags = get_float_exception_flags(fp_status), new_flags;
7561     float32 ret;
7562
7563     ret = float32_round_to_int(x, fp_status);
7564
7565     /* Suppress any inexact exceptions the conversion produced */
7566     if (!(old_flags & float_flag_inexact)) {
7567         new_flags = get_float_exception_flags(fp_status);
7568         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
7569     }
7570
7571     return ret;
7572 }
7573
7574 float64 HELPER(rintd)(float64 x, void *fp_status)
7575 {
7576     int old_flags = get_float_exception_flags(fp_status), new_flags;
7577     float64 ret;
7578
7579     ret = float64_round_to_int(x, fp_status);
7580
7581     new_flags = get_float_exception_flags(fp_status);
7582
7583     /* Suppress any inexact exceptions the conversion produced */
7584     if (!(old_flags & float_flag_inexact)) {
7585         new_flags = get_float_exception_flags(fp_status);
7586         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
7587     }
7588
7589     return ret;
7590 }
7591
7592 /* Convert ARM rounding mode to softfloat */
7593 int arm_rmode_to_sf(int rmode)
7594 {
7595     switch (rmode) {
7596     case FPROUNDING_TIEAWAY:
7597         rmode = float_round_ties_away;
7598         break;
7599     case FPROUNDING_ODD:
7600         /* FIXME: add support for TIEAWAY and ODD */
7601         qemu_log_mask(LOG_UNIMP, "arm: unimplemented rounding mode: %d\n",
7602                       rmode);
7603     case FPROUNDING_TIEEVEN:
7604     default:
7605         rmode = float_round_nearest_even;
7606         break;
7607     case FPROUNDING_POSINF:
7608         rmode = float_round_up;
7609         break;
7610     case FPROUNDING_NEGINF:
7611         rmode = float_round_down;
7612         break;
7613     case FPROUNDING_ZERO:
7614         rmode = float_round_to_zero;
7615         break;
7616     }
7617     return rmode;
7618 }
7619
7620 /* CRC helpers.
7621  * The upper bytes of val (above the number specified by 'bytes') must have
7622  * been zeroed out by the caller.
7623  */
7624 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
7625 {
7626     uint8_t buf[4];
7627
7628     stl_le_p(buf, val);
7629
7630     /* zlib crc32 converts the accumulator and output to one's complement.  */
7631     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
7632 }
7633
7634 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
7635 {
7636     uint8_t buf[4];
7637
7638     stl_le_p(buf, val);
7639
7640     /* Linux crc32c converts the output to one's complement.  */
7641     return crc32c(acc, buf, bytes) ^ 0xffffffff;
7642 }