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