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