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