]> rtime.felk.cvut.cz Git - lisovros/qemu_apohw.git/blob - target-arm/helper.c
target-arm: Don't mention PMU in debug feature register
[lisovros/qemu_apohw.git] / target-arm / helper.c
1 #include "cpu.h"
2 #include "internals.h"
3 #include "exec/gdbstub.h"
4 #include "helper.h"
5 #include "qemu/host-utils.h"
6 #include "sysemu/arch_init.h"
7 #include "sysemu/sysemu.h"
8 #include "qemu/bitops.h"
9 #include "qemu/crc32c.h"
10 #include <zlib.h> /* For crc32 */
11
12 #ifndef CONFIG_USER_ONLY
13 static inline int get_phys_addr(CPUARMState *env, target_ulong address,
14                                 int access_type, int is_user,
15                                 hwaddr *phys_ptr, int *prot,
16                                 target_ulong *page_size);
17
18 /* Definitions for the PMCCNTR and PMCR registers */
19 #define PMCRD   0x8
20 #define PMCRC   0x4
21 #define PMCRE   0x1
22 #endif
23
24 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
25 {
26     int nregs;
27
28     /* VFP data registers are always little-endian.  */
29     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
30     if (reg < nregs) {
31         stfq_le_p(buf, env->vfp.regs[reg]);
32         return 8;
33     }
34     if (arm_feature(env, ARM_FEATURE_NEON)) {
35         /* Aliases for Q regs.  */
36         nregs += 16;
37         if (reg < nregs) {
38             stfq_le_p(buf, env->vfp.regs[(reg - 32) * 2]);
39             stfq_le_p(buf + 8, env->vfp.regs[(reg - 32) * 2 + 1]);
40             return 16;
41         }
42     }
43     switch (reg - nregs) {
44     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
45     case 1: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSCR]); return 4;
46     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
47     }
48     return 0;
49 }
50
51 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
52 {
53     int nregs;
54
55     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
56     if (reg < nregs) {
57         env->vfp.regs[reg] = ldfq_le_p(buf);
58         return 8;
59     }
60     if (arm_feature(env, ARM_FEATURE_NEON)) {
61         nregs += 16;
62         if (reg < nregs) {
63             env->vfp.regs[(reg - 32) * 2] = ldfq_le_p(buf);
64             env->vfp.regs[(reg - 32) * 2 + 1] = ldfq_le_p(buf + 8);
65             return 16;
66         }
67     }
68     switch (reg - nregs) {
69     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
70     case 1: env->vfp.xregs[ARM_VFP_FPSCR] = ldl_p(buf); return 4;
71     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
72     }
73     return 0;
74 }
75
76 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
77 {
78     switch (reg) {
79     case 0 ... 31:
80         /* 128 bit FP register */
81         stfq_le_p(buf, env->vfp.regs[reg * 2]);
82         stfq_le_p(buf + 8, env->vfp.regs[reg * 2 + 1]);
83         return 16;
84     case 32:
85         /* FPSR */
86         stl_p(buf, vfp_get_fpsr(env));
87         return 4;
88     case 33:
89         /* FPCR */
90         stl_p(buf, vfp_get_fpcr(env));
91         return 4;
92     default:
93         return 0;
94     }
95 }
96
97 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
98 {
99     switch (reg) {
100     case 0 ... 31:
101         /* 128 bit FP register */
102         env->vfp.regs[reg * 2] = ldfq_le_p(buf);
103         env->vfp.regs[reg * 2 + 1] = ldfq_le_p(buf + 8);
104         return 16;
105     case 32:
106         /* FPSR */
107         vfp_set_fpsr(env, ldl_p(buf));
108         return 4;
109     case 33:
110         /* FPCR */
111         vfp_set_fpcr(env, ldl_p(buf));
112         return 4;
113     default:
114         return 0;
115     }
116 }
117
118 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
119 {
120     if (cpreg_field_is_64bit(ri)) {
121         return CPREG_FIELD64(env, ri);
122     } else {
123         return CPREG_FIELD32(env, ri);
124     }
125 }
126
127 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
128                       uint64_t value)
129 {
130     if (cpreg_field_is_64bit(ri)) {
131         CPREG_FIELD64(env, ri) = value;
132     } else {
133         CPREG_FIELD32(env, ri) = value;
134     }
135 }
136
137 static uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
138 {
139     /* Raw read of a coprocessor register (as needed for migration, etc). */
140     if (ri->type & ARM_CP_CONST) {
141         return ri->resetvalue;
142     } else if (ri->raw_readfn) {
143         return ri->raw_readfn(env, ri);
144     } else if (ri->readfn) {
145         return ri->readfn(env, ri);
146     } else {
147         return raw_read(env, ri);
148     }
149 }
150
151 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
152                              uint64_t v)
153 {
154     /* Raw write of a coprocessor register (as needed for migration, etc).
155      * Note that constant registers are treated as write-ignored; the
156      * caller should check for success by whether a readback gives the
157      * value written.
158      */
159     if (ri->type & ARM_CP_CONST) {
160         return;
161     } else if (ri->raw_writefn) {
162         ri->raw_writefn(env, ri, v);
163     } else if (ri->writefn) {
164         ri->writefn(env, ri, v);
165     } else {
166         raw_write(env, ri, v);
167     }
168 }
169
170 bool write_cpustate_to_list(ARMCPU *cpu)
171 {
172     /* Write the coprocessor state from cpu->env to the (index,value) list. */
173     int i;
174     bool ok = true;
175
176     for (i = 0; i < cpu->cpreg_array_len; i++) {
177         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
178         const ARMCPRegInfo *ri;
179
180         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
181         if (!ri) {
182             ok = false;
183             continue;
184         }
185         if (ri->type & ARM_CP_NO_MIGRATE) {
186             continue;
187         }
188         cpu->cpreg_values[i] = read_raw_cp_reg(&cpu->env, ri);
189     }
190     return ok;
191 }
192
193 bool write_list_to_cpustate(ARMCPU *cpu)
194 {
195     int i;
196     bool ok = true;
197
198     for (i = 0; i < cpu->cpreg_array_len; i++) {
199         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
200         uint64_t v = cpu->cpreg_values[i];
201         const ARMCPRegInfo *ri;
202
203         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
204         if (!ri) {
205             ok = false;
206             continue;
207         }
208         if (ri->type & ARM_CP_NO_MIGRATE) {
209             continue;
210         }
211         /* Write value and confirm it reads back as written
212          * (to catch read-only registers and partially read-only
213          * registers where the incoming migration value doesn't match)
214          */
215         write_raw_cp_reg(&cpu->env, ri, v);
216         if (read_raw_cp_reg(&cpu->env, ri) != v) {
217             ok = false;
218         }
219     }
220     return ok;
221 }
222
223 static void add_cpreg_to_list(gpointer key, gpointer opaque)
224 {
225     ARMCPU *cpu = opaque;
226     uint64_t regidx;
227     const ARMCPRegInfo *ri;
228
229     regidx = *(uint32_t *)key;
230     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
231
232     if (!(ri->type & ARM_CP_NO_MIGRATE)) {
233         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
234         /* The value array need not be initialized at this point */
235         cpu->cpreg_array_len++;
236     }
237 }
238
239 static void count_cpreg(gpointer key, gpointer opaque)
240 {
241     ARMCPU *cpu = opaque;
242     uint64_t regidx;
243     const ARMCPRegInfo *ri;
244
245     regidx = *(uint32_t *)key;
246     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
247
248     if (!(ri->type & ARM_CP_NO_MIGRATE)) {
249         cpu->cpreg_array_len++;
250     }
251 }
252
253 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
254 {
255     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
256     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
257
258     if (aidx > bidx) {
259         return 1;
260     }
261     if (aidx < bidx) {
262         return -1;
263     }
264     return 0;
265 }
266
267 static void cpreg_make_keylist(gpointer key, gpointer value, gpointer udata)
268 {
269     GList **plist = udata;
270
271     *plist = g_list_prepend(*plist, key);
272 }
273
274 void init_cpreg_list(ARMCPU *cpu)
275 {
276     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
277      * Note that we require cpreg_tuples[] to be sorted by key ID.
278      */
279     GList *keys = NULL;
280     int arraylen;
281
282     g_hash_table_foreach(cpu->cp_regs, cpreg_make_keylist, &keys);
283
284     keys = g_list_sort(keys, cpreg_key_compare);
285
286     cpu->cpreg_array_len = 0;
287
288     g_list_foreach(keys, count_cpreg, cpu);
289
290     arraylen = cpu->cpreg_array_len;
291     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
292     cpu->cpreg_values = g_new(uint64_t, arraylen);
293     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
294     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
295     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
296     cpu->cpreg_array_len = 0;
297
298     g_list_foreach(keys, add_cpreg_to_list, cpu);
299
300     assert(cpu->cpreg_array_len == arraylen);
301
302     g_list_free(keys);
303 }
304
305 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
306 {
307     ARMCPU *cpu = arm_env_get_cpu(env);
308
309     env->cp15.c3 = value;
310     tlb_flush(CPU(cpu), 1); /* Flush TLB as domain not tracked in TLB */
311 }
312
313 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
314 {
315     ARMCPU *cpu = arm_env_get_cpu(env);
316
317     if (env->cp15.c13_fcse != value) {
318         /* Unlike real hardware the qemu TLB uses virtual addresses,
319          * not modified virtual addresses, so this causes a TLB flush.
320          */
321         tlb_flush(CPU(cpu), 1);
322         env->cp15.c13_fcse = value;
323     }
324 }
325
326 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
327                              uint64_t value)
328 {
329     ARMCPU *cpu = arm_env_get_cpu(env);
330
331     if (env->cp15.c13_context != value && !arm_feature(env, ARM_FEATURE_MPU)) {
332         /* For VMSA (when not using the LPAE long descriptor page table
333          * format) this register includes the ASID, so do a TLB flush.
334          * For PMSA it is purely a process ID and no action is needed.
335          */
336         tlb_flush(CPU(cpu), 1);
337     }
338     env->cp15.c13_context = value;
339 }
340
341 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
342                           uint64_t value)
343 {
344     /* Invalidate all (TLBIALL) */
345     ARMCPU *cpu = arm_env_get_cpu(env);
346
347     tlb_flush(CPU(cpu), 1);
348 }
349
350 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
351                           uint64_t value)
352 {
353     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
354     ARMCPU *cpu = arm_env_get_cpu(env);
355
356     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
357 }
358
359 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
360                            uint64_t value)
361 {
362     /* Invalidate by ASID (TLBIASID) */
363     ARMCPU *cpu = arm_env_get_cpu(env);
364
365     tlb_flush(CPU(cpu), value == 0);
366 }
367
368 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
369                            uint64_t value)
370 {
371     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
372     ARMCPU *cpu = arm_env_get_cpu(env);
373
374     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
375 }
376
377 static const ARMCPRegInfo cp_reginfo[] = {
378     /* DBGDIDR: just RAZ. In particular this means the "debug architecture
379      * version" bits will read as a reserved value, which should cause
380      * Linux to not try to use the debug hardware.
381      */
382     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
383       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
384     /* MMU Domain access control / MPU write buffer control */
385     { .name = "DACR", .cp = 15,
386       .crn = 3, .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
387       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c3),
388       .resetvalue = 0, .writefn = dacr_write, .raw_writefn = raw_write, },
389     { .name = "FCSEIDR", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 0,
390       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c13_fcse),
391       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
392     { .name = "CONTEXTIDR", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 1,
393       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c13_context),
394       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
395     /* ??? This covers not just the impdef TLB lockdown registers but also
396      * some v7VMSA registers relating to TEX remap, so it is overly broad.
397      */
398     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = CP_ANY,
399       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
400     /* MMU TLB control. Note that the wildcarding means we cover not just
401      * the unified TLB ops but also the dside/iside/inner-shareable variants.
402      */
403     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
404       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
405       .type = ARM_CP_NO_MIGRATE },
406     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
407       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
408       .type = ARM_CP_NO_MIGRATE },
409     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
410       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
411       .type = ARM_CP_NO_MIGRATE },
412     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
413       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
414       .type = ARM_CP_NO_MIGRATE },
415     /* Cache maintenance ops; some of this space may be overridden later. */
416     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
417       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
418       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
419     REGINFO_SENTINEL
420 };
421
422 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
423     /* Not all pre-v6 cores implemented this WFI, so this is slightly
424      * over-broad.
425      */
426     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
427       .access = PL1_W, .type = ARM_CP_WFI },
428     REGINFO_SENTINEL
429 };
430
431 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
432     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
433      * is UNPREDICTABLE; we choose to NOP as most implementations do).
434      */
435     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
436       .access = PL1_W, .type = ARM_CP_WFI },
437     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
438      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
439      * OMAPCP will override this space.
440      */
441     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
442       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
443       .resetvalue = 0 },
444     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
445       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
446       .resetvalue = 0 },
447     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
448     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
449       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_MIGRATE,
450       .resetvalue = 0 },
451     REGINFO_SENTINEL
452 };
453
454 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
455                         uint64_t value)
456 {
457     if (env->cp15.c1_coproc != value) {
458         env->cp15.c1_coproc = value;
459         /* ??? Is this safe when called from within a TB?  */
460         tb_flush(env);
461     }
462 }
463
464 static const ARMCPRegInfo v6_cp_reginfo[] = {
465     /* prefetch by MVA in v6, NOP in v7 */
466     { .name = "MVA_prefetch",
467       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
468       .access = PL1_W, .type = ARM_CP_NOP },
469     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
470       .access = PL0_W, .type = ARM_CP_NOP },
471     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
472       .access = PL0_W, .type = ARM_CP_NOP },
473     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
474       .access = PL0_W, .type = ARM_CP_NOP },
475     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
476       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c6_insn),
477       .resetvalue = 0, },
478     /* Watchpoint Fault Address Register : should actually only be present
479      * for 1136, 1176, 11MPCore.
480      */
481     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
482       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
483     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
484       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2,
485       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c1_coproc),
486       .resetvalue = 0, .writefn = cpacr_write },
487     REGINFO_SENTINEL
488 };
489
490 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri)
491 {
492     /* Performance monitor registers user accessibility is controlled
493      * by PMUSERENR.
494      */
495     if (arm_current_pl(env) == 0 && !env->cp15.c9_pmuserenr) {
496         return CP_ACCESS_TRAP;
497     }
498     return CP_ACCESS_OK;
499 }
500
501 #ifndef CONFIG_USER_ONLY
502 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
503                        uint64_t value)
504 {
505     /* Don't computer the number of ticks in user mode */
506     uint32_t temp_ticks;
507
508     temp_ticks = qemu_clock_get_us(QEMU_CLOCK_VIRTUAL) *
509                   get_ticks_per_sec() / 1000000;
510
511     if (env->cp15.c9_pmcr & PMCRE) {
512         /* If the counter is enabled */
513         if (env->cp15.c9_pmcr & PMCRD) {
514             /* Increment once every 64 processor clock cycles */
515             env->cp15.c15_ccnt = (temp_ticks/64) - env->cp15.c15_ccnt;
516         } else {
517             env->cp15.c15_ccnt = temp_ticks - env->cp15.c15_ccnt;
518         }
519     }
520
521     if (value & PMCRC) {
522         /* The counter has been reset */
523         env->cp15.c15_ccnt = 0;
524     }
525
526     /* only the DP, X, D and E bits are writable */
527     env->cp15.c9_pmcr &= ~0x39;
528     env->cp15.c9_pmcr |= (value & 0x39);
529
530     if (env->cp15.c9_pmcr & PMCRE) {
531         if (env->cp15.c9_pmcr & PMCRD) {
532             /* Increment once every 64 processor clock cycles */
533             temp_ticks /= 64;
534         }
535         env->cp15.c15_ccnt = temp_ticks - env->cp15.c15_ccnt;
536     }
537 }
538
539 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
540 {
541     uint32_t total_ticks;
542
543     if (!(env->cp15.c9_pmcr & PMCRE)) {
544         /* Counter is disabled, do not change value */
545         return env->cp15.c15_ccnt;
546     }
547
548     total_ticks = qemu_clock_get_us(QEMU_CLOCK_VIRTUAL) *
549                   get_ticks_per_sec() / 1000000;
550
551     if (env->cp15.c9_pmcr & PMCRD) {
552         /* Increment once every 64 processor clock cycles */
553         total_ticks /= 64;
554     }
555     return total_ticks - env->cp15.c15_ccnt;
556 }
557
558 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
559                         uint64_t value)
560 {
561     uint32_t total_ticks;
562
563     if (!(env->cp15.c9_pmcr & PMCRE)) {
564         /* Counter is disabled, set the absolute value */
565         env->cp15.c15_ccnt = value;
566         return;
567     }
568
569     total_ticks = qemu_clock_get_us(QEMU_CLOCK_VIRTUAL) *
570                   get_ticks_per_sec() / 1000000;
571
572     if (env->cp15.c9_pmcr & PMCRD) {
573         /* Increment once every 64 processor clock cycles */
574         total_ticks /= 64;
575     }
576     env->cp15.c15_ccnt = total_ticks - value;
577 }
578 #endif
579
580 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
581                             uint64_t value)
582 {
583     value &= (1 << 31);
584     env->cp15.c9_pmcnten |= value;
585 }
586
587 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
588                              uint64_t value)
589 {
590     value &= (1 << 31);
591     env->cp15.c9_pmcnten &= ~value;
592 }
593
594 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
595                          uint64_t value)
596 {
597     env->cp15.c9_pmovsr &= ~value;
598 }
599
600 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
601                              uint64_t value)
602 {
603     env->cp15.c9_pmxevtyper = value & 0xff;
604 }
605
606 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
607                             uint64_t value)
608 {
609     env->cp15.c9_pmuserenr = value & 1;
610 }
611
612 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
613                              uint64_t value)
614 {
615     /* We have no event counters so only the C bit can be changed */
616     value &= (1 << 31);
617     env->cp15.c9_pminten |= value;
618 }
619
620 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
621                              uint64_t value)
622 {
623     value &= (1 << 31);
624     env->cp15.c9_pminten &= ~value;
625 }
626
627 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
628                        uint64_t value)
629 {
630     /* Note that even though the AArch64 view of this register has bits
631      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
632      * architectural requirements for bits which are RES0 only in some
633      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
634      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
635      */
636     env->cp15.c12_vbar = value & ~0x1Ful;
637 }
638
639 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
640 {
641     ARMCPU *cpu = arm_env_get_cpu(env);
642     return cpu->ccsidr[env->cp15.c0_cssel];
643 }
644
645 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
646                          uint64_t value)
647 {
648     env->cp15.c0_cssel = value & 0xf;
649 }
650
651 static const ARMCPRegInfo v7_cp_reginfo[] = {
652     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
653      * debug components
654      */
655     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
656       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
657     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
658       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
659     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
660     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
661       .access = PL1_W, .type = ARM_CP_NOP },
662     /* Performance monitors are implementation defined in v7,
663      * but with an ARM recommended set of registers, which we
664      * follow (although we don't actually implement any counters)
665      *
666      * Performance registers fall into three categories:
667      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
668      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
669      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
670      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
671      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
672      */
673     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
674       .access = PL0_RW, .resetvalue = 0,
675       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
676       .writefn = pmcntenset_write,
677       .accessfn = pmreg_access,
678       .raw_writefn = raw_write },
679     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
680       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
681       .accessfn = pmreg_access,
682       .writefn = pmcntenclr_write,
683       .type = ARM_CP_NO_MIGRATE },
684     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
685       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
686       .accessfn = pmreg_access,
687       .writefn = pmovsr_write,
688       .raw_writefn = raw_write },
689     /* Unimplemented so WI. */
690     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
691       .access = PL0_W, .accessfn = pmreg_access, .type = ARM_CP_NOP },
692     /* Since we don't implement any events, writing to PMSELR is UNPREDICTABLE.
693      * We choose to RAZ/WI.
694      */
695     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
696       .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0,
697       .accessfn = pmreg_access },
698 #ifndef CONFIG_USER_ONLY
699     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
700       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_IO,
701       .readfn = pmccntr_read, .writefn = pmccntr_write,
702       .accessfn = pmreg_access },
703 #endif
704     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
705       .access = PL0_RW,
706       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmxevtyper),
707       .accessfn = pmreg_access, .writefn = pmxevtyper_write,
708       .raw_writefn = raw_write },
709     /* Unimplemented, RAZ/WI. */
710     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
711       .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0,
712       .accessfn = pmreg_access },
713     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
714       .access = PL0_R | PL1_RW,
715       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
716       .resetvalue = 0,
717       .writefn = pmuserenr_write, .raw_writefn = raw_write },
718     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
719       .access = PL1_RW,
720       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
721       .resetvalue = 0,
722       .writefn = pmintenset_write, .raw_writefn = raw_write },
723     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
724       .access = PL1_RW, .type = ARM_CP_NO_MIGRATE,
725       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
726       .resetvalue = 0, .writefn = pmintenclr_write, },
727     { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
728       .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
729       .access = PL1_RW, .writefn = vbar_write,
730       .fieldoffset = offsetof(CPUARMState, cp15.c12_vbar),
731       .resetvalue = 0 },
732     { .name = "SCR", .cp = 15, .crn = 1, .crm = 1, .opc1 = 0, .opc2 = 0,
733       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c1_scr),
734       .resetvalue = 0, },
735     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
736       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
737       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_MIGRATE },
738     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
739       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
740       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c0_cssel),
741       .writefn = csselr_write, .resetvalue = 0 },
742     /* Auxiliary ID register: this actually has an IMPDEF value but for now
743      * just RAZ for all cores:
744      */
745     { .name = "AIDR", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 7,
746       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
747     /* MAIR can just read-as-written because we don't implement caches
748      * and so don't need to care about memory attributes.
749      */
750     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
751       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
752       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el1),
753       .resetvalue = 0 },
754     /* For non-long-descriptor page tables these are PRRR and NMRR;
755      * regardless they still act as reads-as-written for QEMU.
756      * The override is necessary because of the overly-broad TLB_LOCKDOWN
757      * definition.
758      */
759     { .name = "MAIR0", .state = ARM_CP_STATE_AA32, .type = ARM_CP_OVERRIDE,
760       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
761       .fieldoffset = offsetoflow32(CPUARMState, cp15.mair_el1),
762       .resetfn = arm_cp_reset_ignore },
763     { .name = "MAIR1", .state = ARM_CP_STATE_AA32, .type = ARM_CP_OVERRIDE,
764       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
765       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el1),
766       .resetfn = arm_cp_reset_ignore },
767     REGINFO_SENTINEL
768 };
769
770 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
771                         uint64_t value)
772 {
773     value &= 1;
774     env->teecr = value;
775 }
776
777 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri)
778 {
779     if (arm_current_pl(env) == 0 && (env->teecr & 1)) {
780         return CP_ACCESS_TRAP;
781     }
782     return CP_ACCESS_OK;
783 }
784
785 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
786     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
787       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
788       .resetvalue = 0,
789       .writefn = teecr_write },
790     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
791       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
792       .accessfn = teehbr_access, .resetvalue = 0 },
793     REGINFO_SENTINEL
794 };
795
796 static const ARMCPRegInfo v6k_cp_reginfo[] = {
797     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
798       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
799       .access = PL0_RW,
800       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el0), .resetvalue = 0 },
801     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
802       .access = PL0_RW,
803       .fieldoffset = offsetoflow32(CPUARMState, cp15.tpidr_el0),
804       .resetfn = arm_cp_reset_ignore },
805     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
806       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
807       .access = PL0_R|PL1_W,
808       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el0), .resetvalue = 0 },
809     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
810       .access = PL0_R|PL1_W,
811       .fieldoffset = offsetoflow32(CPUARMState, cp15.tpidrro_el0),
812       .resetfn = arm_cp_reset_ignore },
813     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_BOTH,
814       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
815       .access = PL1_RW,
816       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el1), .resetvalue = 0 },
817     REGINFO_SENTINEL
818 };
819
820 #ifndef CONFIG_USER_ONLY
821
822 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri)
823 {
824     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero */
825     if (arm_current_pl(env) == 0 && !extract32(env->cp15.c14_cntkctl, 0, 2)) {
826         return CP_ACCESS_TRAP;
827     }
828     return CP_ACCESS_OK;
829 }
830
831 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx)
832 {
833     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
834     if (arm_current_pl(env) == 0 &&
835         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
836         return CP_ACCESS_TRAP;
837     }
838     return CP_ACCESS_OK;
839 }
840
841 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx)
842 {
843     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
844      * EL0[PV]TEN is zero.
845      */
846     if (arm_current_pl(env) == 0 &&
847         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
848         return CP_ACCESS_TRAP;
849     }
850     return CP_ACCESS_OK;
851 }
852
853 static CPAccessResult gt_pct_access(CPUARMState *env,
854                                          const ARMCPRegInfo *ri)
855 {
856     return gt_counter_access(env, GTIMER_PHYS);
857 }
858
859 static CPAccessResult gt_vct_access(CPUARMState *env,
860                                          const ARMCPRegInfo *ri)
861 {
862     return gt_counter_access(env, GTIMER_VIRT);
863 }
864
865 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri)
866 {
867     return gt_timer_access(env, GTIMER_PHYS);
868 }
869
870 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri)
871 {
872     return gt_timer_access(env, GTIMER_VIRT);
873 }
874
875 static uint64_t gt_get_countervalue(CPUARMState *env)
876 {
877     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
878 }
879
880 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
881 {
882     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
883
884     if (gt->ctl & 1) {
885         /* Timer enabled: calculate and set current ISTATUS, irq, and
886          * reset timer to when ISTATUS next has to change
887          */
888         uint64_t count = gt_get_countervalue(&cpu->env);
889         /* Note that this must be unsigned 64 bit arithmetic: */
890         int istatus = count >= gt->cval;
891         uint64_t nexttick;
892
893         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
894         qemu_set_irq(cpu->gt_timer_outputs[timeridx],
895                      (istatus && !(gt->ctl & 2)));
896         if (istatus) {
897             /* Next transition is when count rolls back over to zero */
898             nexttick = UINT64_MAX;
899         } else {
900             /* Next transition is when we hit cval */
901             nexttick = gt->cval;
902         }
903         /* Note that the desired next expiry time might be beyond the
904          * signed-64-bit range of a QEMUTimer -- in this case we just
905          * set the timer for as far in the future as possible. When the
906          * timer expires we will reset the timer for any remaining period.
907          */
908         if (nexttick > INT64_MAX / GTIMER_SCALE) {
909             nexttick = INT64_MAX / GTIMER_SCALE;
910         }
911         timer_mod(cpu->gt_timer[timeridx], nexttick);
912     } else {
913         /* Timer disabled: ISTATUS and timer output always clear */
914         gt->ctl &= ~4;
915         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
916         timer_del(cpu->gt_timer[timeridx]);
917     }
918 }
919
920 static void gt_cnt_reset(CPUARMState *env, const ARMCPRegInfo *ri)
921 {
922     ARMCPU *cpu = arm_env_get_cpu(env);
923     int timeridx = ri->opc1 & 1;
924
925     timer_del(cpu->gt_timer[timeridx]);
926 }
927
928 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
929 {
930     return gt_get_countervalue(env);
931 }
932
933 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
934                           uint64_t value)
935 {
936     int timeridx = ri->opc1 & 1;
937
938     env->cp15.c14_timer[timeridx].cval = value;
939     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
940 }
941
942 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
943 {
944     int timeridx = ri->crm & 1;
945
946     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
947                       gt_get_countervalue(env));
948 }
949
950 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
951                           uint64_t value)
952 {
953     int timeridx = ri->crm & 1;
954
955     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) +
956         + sextract64(value, 0, 32);
957     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
958 }
959
960 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
961                          uint64_t value)
962 {
963     ARMCPU *cpu = arm_env_get_cpu(env);
964     int timeridx = ri->crm & 1;
965     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
966
967     env->cp15.c14_timer[timeridx].ctl = value & 3;
968     if ((oldval ^ value) & 1) {
969         /* Enable toggled */
970         gt_recalc_timer(cpu, timeridx);
971     } else if ((oldval & value) & 2) {
972         /* IMASK toggled: don't need to recalculate,
973          * just set the interrupt line based on ISTATUS
974          */
975         qemu_set_irq(cpu->gt_timer_outputs[timeridx],
976                      (oldval & 4) && (value & 2));
977     }
978 }
979
980 void arm_gt_ptimer_cb(void *opaque)
981 {
982     ARMCPU *cpu = opaque;
983
984     gt_recalc_timer(cpu, GTIMER_PHYS);
985 }
986
987 void arm_gt_vtimer_cb(void *opaque)
988 {
989     ARMCPU *cpu = opaque;
990
991     gt_recalc_timer(cpu, GTIMER_VIRT);
992 }
993
994 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
995     /* Note that CNTFRQ is purely reads-as-written for the benefit
996      * of software; writing it doesn't actually change the timer frequency.
997      * Our reset value matches the fixed frequency we implement the timer at.
998      */
999     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
1000       .type = ARM_CP_NO_MIGRATE,
1001       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1002       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
1003       .resetfn = arm_cp_reset_ignore,
1004     },
1005     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
1006       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
1007       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1008       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
1009       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
1010     },
1011     /* overall control: mostly access permissions */
1012     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
1013       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
1014       .access = PL1_RW,
1015       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
1016       .resetvalue = 0,
1017     },
1018     /* per-timer control */
1019     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
1020       .type = ARM_CP_IO | ARM_CP_NO_MIGRATE, .access = PL1_RW | PL0_R,
1021       .accessfn = gt_ptimer_access,
1022       .fieldoffset = offsetoflow32(CPUARMState,
1023                                    cp15.c14_timer[GTIMER_PHYS].ctl),
1024       .resetfn = arm_cp_reset_ignore,
1025       .writefn = gt_ctl_write, .raw_writefn = raw_write,
1026     },
1027     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
1028       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
1029       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
1030       .accessfn = gt_ptimer_access,
1031       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
1032       .resetvalue = 0,
1033       .writefn = gt_ctl_write, .raw_writefn = raw_write,
1034     },
1035     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
1036       .type = ARM_CP_IO | ARM_CP_NO_MIGRATE, .access = PL1_RW | PL0_R,
1037       .accessfn = gt_vtimer_access,
1038       .fieldoffset = offsetoflow32(CPUARMState,
1039                                    cp15.c14_timer[GTIMER_VIRT].ctl),
1040       .resetfn = arm_cp_reset_ignore,
1041       .writefn = gt_ctl_write, .raw_writefn = raw_write,
1042     },
1043     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
1044       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
1045       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
1046       .accessfn = gt_vtimer_access,
1047       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
1048       .resetvalue = 0,
1049       .writefn = gt_ctl_write, .raw_writefn = raw_write,
1050     },
1051     /* TimerValue views: a 32 bit downcounting view of the underlying state */
1052     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
1053       .type = ARM_CP_NO_MIGRATE | ARM_CP_IO, .access = PL1_RW | PL0_R,
1054       .accessfn = gt_ptimer_access,
1055       .readfn = gt_tval_read, .writefn = gt_tval_write,
1056     },
1057     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
1058       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
1059       .type = ARM_CP_NO_MIGRATE | ARM_CP_IO, .access = PL1_RW | PL0_R,
1060       .readfn = gt_tval_read, .writefn = gt_tval_write,
1061     },
1062     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
1063       .type = ARM_CP_NO_MIGRATE | ARM_CP_IO, .access = PL1_RW | PL0_R,
1064       .accessfn = gt_vtimer_access,
1065       .readfn = gt_tval_read, .writefn = gt_tval_write,
1066     },
1067     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
1068       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
1069       .type = ARM_CP_NO_MIGRATE | ARM_CP_IO, .access = PL1_RW | PL0_R,
1070       .readfn = gt_tval_read, .writefn = gt_tval_write,
1071     },
1072     /* The counter itself */
1073     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
1074       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_MIGRATE | ARM_CP_IO,
1075       .accessfn = gt_pct_access,
1076       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
1077     },
1078     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
1079       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
1080       .access = PL0_R, .type = ARM_CP_NO_MIGRATE | ARM_CP_IO,
1081       .accessfn = gt_pct_access,
1082       .readfn = gt_cnt_read, .resetfn = gt_cnt_reset,
1083     },
1084     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
1085       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_MIGRATE | ARM_CP_IO,
1086       .accessfn = gt_vct_access,
1087       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
1088     },
1089     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
1090       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
1091       .access = PL0_R, .type = ARM_CP_NO_MIGRATE | ARM_CP_IO,
1092       .accessfn = gt_vct_access,
1093       .readfn = gt_cnt_read, .resetfn = gt_cnt_reset,
1094     },
1095     /* Comparison value, indicating when the timer goes off */
1096     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
1097       .access = PL1_RW | PL0_R,
1098       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_NO_MIGRATE,
1099       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
1100       .accessfn = gt_ptimer_access, .resetfn = arm_cp_reset_ignore,
1101       .writefn = gt_cval_write, .raw_writefn = raw_write,
1102     },
1103     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
1104       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
1105       .access = PL1_RW | PL0_R,
1106       .type = ARM_CP_IO,
1107       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
1108       .resetvalue = 0, .accessfn = gt_vtimer_access,
1109       .writefn = gt_cval_write, .raw_writefn = raw_write,
1110     },
1111     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
1112       .access = PL1_RW | PL0_R,
1113       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_NO_MIGRATE,
1114       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
1115       .accessfn = gt_vtimer_access, .resetfn = arm_cp_reset_ignore,
1116       .writefn = gt_cval_write, .raw_writefn = raw_write,
1117     },
1118     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
1119       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
1120       .access = PL1_RW | PL0_R,
1121       .type = ARM_CP_IO,
1122       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
1123       .resetvalue = 0, .accessfn = gt_vtimer_access,
1124       .writefn = gt_cval_write, .raw_writefn = raw_write,
1125     },
1126     REGINFO_SENTINEL
1127 };
1128
1129 #else
1130 /* In user-mode none of the generic timer registers are accessible,
1131  * and their implementation depends on QEMU_CLOCK_VIRTUAL and qdev gpio outputs,
1132  * so instead just don't register any of them.
1133  */
1134 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
1135     REGINFO_SENTINEL
1136 };
1137
1138 #endif
1139
1140 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1141 {
1142     if (arm_feature(env, ARM_FEATURE_LPAE)) {
1143         env->cp15.c7_par = value;
1144     } else if (arm_feature(env, ARM_FEATURE_V7)) {
1145         env->cp15.c7_par = value & 0xfffff6ff;
1146     } else {
1147         env->cp15.c7_par = value & 0xfffff1ff;
1148     }
1149 }
1150
1151 #ifndef CONFIG_USER_ONLY
1152 /* get_phys_addr() isn't present for user-mode-only targets */
1153
1154 /* Return true if extended addresses are enabled.
1155  * This is always the case if our translation regime is 64 bit,
1156  * but depends on TTBCR.EAE for 32 bit.
1157  */
1158 static inline bool extended_addresses_enabled(CPUARMState *env)
1159 {
1160     return arm_el_is_aa64(env, 1)
1161         || ((arm_feature(env, ARM_FEATURE_LPAE)
1162              && (env->cp15.c2_control & (1U << 31))));
1163 }
1164
1165 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri)
1166 {
1167     if (ri->opc2 & 4) {
1168         /* Other states are only available with TrustZone; in
1169          * a non-TZ implementation these registers don't exist
1170          * at all, which is an Uncategorized trap. This underdecoding
1171          * is safe because the reginfo is NO_MIGRATE.
1172          */
1173         return CP_ACCESS_TRAP_UNCATEGORIZED;
1174     }
1175     return CP_ACCESS_OK;
1176 }
1177
1178 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1179 {
1180     hwaddr phys_addr;
1181     target_ulong page_size;
1182     int prot;
1183     int ret, is_user = ri->opc2 & 2;
1184     int access_type = ri->opc2 & 1;
1185
1186     ret = get_phys_addr(env, value, access_type, is_user,
1187                         &phys_addr, &prot, &page_size);
1188     if (extended_addresses_enabled(env)) {
1189         /* ret is a DFSR/IFSR value for the long descriptor
1190          * translation table format, but with WnR always clear.
1191          * Convert it to a 64-bit PAR.
1192          */
1193         uint64_t par64 = (1 << 11); /* LPAE bit always set */
1194         if (ret == 0) {
1195             par64 |= phys_addr & ~0xfffULL;
1196             /* We don't set the ATTR or SH fields in the PAR. */
1197         } else {
1198             par64 |= 1; /* F */
1199             par64 |= (ret & 0x3f) << 1; /* FS */
1200             /* Note that S2WLK and FSTAGE are always zero, because we don't
1201              * implement virtualization and therefore there can't be a stage 2
1202              * fault.
1203              */
1204         }
1205         env->cp15.c7_par = par64;
1206         env->cp15.c7_par_hi = par64 >> 32;
1207     } else {
1208         /* ret is a DFSR/IFSR value for the short descriptor
1209          * translation table format (with WnR always clear).
1210          * Convert it to a 32-bit PAR.
1211          */
1212         if (ret == 0) {
1213             /* We do not set any attribute bits in the PAR */
1214             if (page_size == (1 << 24)
1215                 && arm_feature(env, ARM_FEATURE_V7)) {
1216                 env->cp15.c7_par = (phys_addr & 0xff000000) | 1 << 1;
1217             } else {
1218                 env->cp15.c7_par = phys_addr & 0xfffff000;
1219             }
1220         } else {
1221             env->cp15.c7_par = ((ret & (1 << 10)) >> 5) |
1222                 ((ret & (1 << 12)) >> 6) |
1223                 ((ret & 0xf) << 1) | 1;
1224         }
1225         env->cp15.c7_par_hi = 0;
1226     }
1227 }
1228 #endif
1229
1230 static const ARMCPRegInfo vapa_cp_reginfo[] = {
1231     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
1232       .access = PL1_RW, .resetvalue = 0,
1233       .fieldoffset = offsetof(CPUARMState, cp15.c7_par),
1234       .writefn = par_write },
1235 #ifndef CONFIG_USER_ONLY
1236     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
1237       .access = PL1_W, .accessfn = ats_access,
1238       .writefn = ats_write, .type = ARM_CP_NO_MIGRATE },
1239 #endif
1240     REGINFO_SENTINEL
1241 };
1242
1243 /* Return basic MPU access permission bits.  */
1244 static uint32_t simple_mpu_ap_bits(uint32_t val)
1245 {
1246     uint32_t ret;
1247     uint32_t mask;
1248     int i;
1249     ret = 0;
1250     mask = 3;
1251     for (i = 0; i < 16; i += 2) {
1252         ret |= (val >> i) & mask;
1253         mask <<= 2;
1254     }
1255     return ret;
1256 }
1257
1258 /* Pad basic MPU access permission bits to extended format.  */
1259 static uint32_t extended_mpu_ap_bits(uint32_t val)
1260 {
1261     uint32_t ret;
1262     uint32_t mask;
1263     int i;
1264     ret = 0;
1265     mask = 3;
1266     for (i = 0; i < 16; i += 2) {
1267         ret |= (val & mask) << i;
1268         mask <<= 2;
1269     }
1270     return ret;
1271 }
1272
1273 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
1274                                  uint64_t value)
1275 {
1276     env->cp15.c5_data = extended_mpu_ap_bits(value);
1277 }
1278
1279 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
1280 {
1281     return simple_mpu_ap_bits(env->cp15.c5_data);
1282 }
1283
1284 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
1285                                  uint64_t value)
1286 {
1287     env->cp15.c5_insn = extended_mpu_ap_bits(value);
1288 }
1289
1290 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
1291 {
1292     return simple_mpu_ap_bits(env->cp15.c5_insn);
1293 }
1294
1295 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
1296     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
1297       .access = PL1_RW, .type = ARM_CP_NO_MIGRATE,
1298       .fieldoffset = offsetof(CPUARMState, cp15.c5_data), .resetvalue = 0,
1299       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
1300     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
1301       .access = PL1_RW, .type = ARM_CP_NO_MIGRATE,
1302       .fieldoffset = offsetof(CPUARMState, cp15.c5_insn), .resetvalue = 0,
1303       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
1304     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
1305       .access = PL1_RW,
1306       .fieldoffset = offsetof(CPUARMState, cp15.c5_data), .resetvalue = 0, },
1307     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
1308       .access = PL1_RW,
1309       .fieldoffset = offsetof(CPUARMState, cp15.c5_insn), .resetvalue = 0, },
1310     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
1311       .access = PL1_RW,
1312       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
1313     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
1314       .access = PL1_RW,
1315       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
1316     /* Protection region base and size registers */
1317     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
1318       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
1319       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
1320     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
1321       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
1322       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
1323     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
1324       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
1325       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
1326     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
1327       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
1328       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
1329     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
1330       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
1331       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
1332     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
1333       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
1334       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
1335     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
1336       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
1337       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
1338     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
1339       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
1340       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
1341     REGINFO_SENTINEL
1342 };
1343
1344 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
1345                                  uint64_t value)
1346 {
1347     int maskshift = extract32(value, 0, 3);
1348
1349     if (arm_feature(env, ARM_FEATURE_LPAE) && (value & (1 << 31))) {
1350         value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
1351     } else {
1352         value &= 7;
1353     }
1354     /* Note that we always calculate c2_mask and c2_base_mask, but
1355      * they are only used for short-descriptor tables (ie if EAE is 0);
1356      * for long-descriptor tables the TTBCR fields are used differently
1357      * and the c2_mask and c2_base_mask values are meaningless.
1358      */
1359     env->cp15.c2_control = value;
1360     env->cp15.c2_mask = ~(((uint32_t)0xffffffffu) >> maskshift);
1361     env->cp15.c2_base_mask = ~((uint32_t)0x3fffu >> maskshift);
1362 }
1363
1364 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1365                              uint64_t value)
1366 {
1367     ARMCPU *cpu = arm_env_get_cpu(env);
1368
1369     if (arm_feature(env, ARM_FEATURE_LPAE)) {
1370         /* With LPAE the TTBCR could result in a change of ASID
1371          * via the TTBCR.A1 bit, so do a TLB flush.
1372          */
1373         tlb_flush(CPU(cpu), 1);
1374     }
1375     vmsa_ttbcr_raw_write(env, ri, value);
1376 }
1377
1378 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1379 {
1380     env->cp15.c2_base_mask = 0xffffc000u;
1381     env->cp15.c2_control = 0;
1382     env->cp15.c2_mask = 0;
1383 }
1384
1385 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
1386                                uint64_t value)
1387 {
1388     ARMCPU *cpu = arm_env_get_cpu(env);
1389
1390     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
1391     tlb_flush(CPU(cpu), 1);
1392     env->cp15.c2_control = value;
1393 }
1394
1395 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1396                             uint64_t value)
1397 {
1398     /* 64 bit accesses to the TTBRs can change the ASID and so we
1399      * must flush the TLB.
1400      */
1401     if (cpreg_field_is_64bit(ri)) {
1402         ARMCPU *cpu = arm_env_get_cpu(env);
1403
1404         tlb_flush(CPU(cpu), 1);
1405     }
1406     raw_write(env, ri, value);
1407 }
1408
1409 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
1410     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
1411       .access = PL1_RW,
1412       .fieldoffset = offsetof(CPUARMState, cp15.c5_data), .resetvalue = 0, },
1413     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
1414       .access = PL1_RW,
1415       .fieldoffset = offsetof(CPUARMState, cp15.c5_insn), .resetvalue = 0, },
1416     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
1417       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
1418       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el1),
1419       .writefn = vmsa_ttbr_write, .resetvalue = 0 },
1420     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
1421       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
1422       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el1),
1423       .writefn = vmsa_ttbr_write, .resetvalue = 0 },
1424     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
1425       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
1426       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
1427       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
1428       .fieldoffset = offsetof(CPUARMState, cp15.c2_control) },
1429     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
1430       .access = PL1_RW, .type = ARM_CP_NO_MIGRATE, .writefn = vmsa_ttbcr_write,
1431       .resetfn = arm_cp_reset_ignore, .raw_writefn = vmsa_ttbcr_raw_write,
1432       .fieldoffset = offsetoflow32(CPUARMState, cp15.c2_control) },
1433     { .name = "DFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
1434       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c6_data),
1435       .resetvalue = 0, },
1436     REGINFO_SENTINEL
1437 };
1438
1439 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
1440                                 uint64_t value)
1441 {
1442     env->cp15.c15_ticonfig = value & 0xe7;
1443     /* The OS_TYPE bit in this register changes the reported CPUID! */
1444     env->cp15.c0_cpuid = (value & (1 << 5)) ?
1445         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
1446 }
1447
1448 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
1449                                 uint64_t value)
1450 {
1451     env->cp15.c15_threadid = value & 0xffff;
1452 }
1453
1454 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
1455                            uint64_t value)
1456 {
1457     /* Wait-for-interrupt (deprecated) */
1458     cpu_interrupt(CPU(arm_env_get_cpu(env)), CPU_INTERRUPT_HALT);
1459 }
1460
1461 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
1462                                   uint64_t value)
1463 {
1464     /* On OMAP there are registers indicating the max/min index of dcache lines
1465      * containing a dirty line; cache flush operations have to reset these.
1466      */
1467     env->cp15.c15_i_max = 0x000;
1468     env->cp15.c15_i_min = 0xff0;
1469 }
1470
1471 static const ARMCPRegInfo omap_cp_reginfo[] = {
1472     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
1473       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
1474       .fieldoffset = offsetof(CPUARMState, cp15.c5_data), .resetvalue = 0, },
1475     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
1476       .access = PL1_RW, .type = ARM_CP_NOP },
1477     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
1478       .access = PL1_RW,
1479       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
1480       .writefn = omap_ticonfig_write },
1481     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
1482       .access = PL1_RW,
1483       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
1484     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
1485       .access = PL1_RW, .resetvalue = 0xff0,
1486       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
1487     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
1488       .access = PL1_RW,
1489       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
1490       .writefn = omap_threadid_write },
1491     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
1492       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
1493       .type = ARM_CP_NO_MIGRATE,
1494       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
1495     /* TODO: Peripheral port remap register:
1496      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
1497      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
1498      * when MMU is off.
1499      */
1500     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
1501       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
1502       .type = ARM_CP_OVERRIDE | ARM_CP_NO_MIGRATE,
1503       .writefn = omap_cachemaint_write },
1504     { .name = "C9", .cp = 15, .crn = 9,
1505       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
1506       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
1507     REGINFO_SENTINEL
1508 };
1509
1510 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1511                               uint64_t value)
1512 {
1513     value &= 0x3fff;
1514     if (env->cp15.c15_cpar != value) {
1515         /* Changes cp0 to cp13 behavior, so needs a TB flush.  */
1516         tb_flush(env);
1517         env->cp15.c15_cpar = value;
1518     }
1519 }
1520
1521 static const ARMCPRegInfo xscale_cp_reginfo[] = {
1522     { .name = "XSCALE_CPAR",
1523       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
1524       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
1525       .writefn = xscale_cpar_write, },
1526     { .name = "XSCALE_AUXCR",
1527       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
1528       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
1529       .resetvalue = 0, },
1530     REGINFO_SENTINEL
1531 };
1532
1533 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
1534     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
1535      * implementation of this implementation-defined space.
1536      * Ideally this should eventually disappear in favour of actually
1537      * implementing the correct behaviour for all cores.
1538      */
1539     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
1540       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
1541       .access = PL1_RW,
1542       .type = ARM_CP_CONST | ARM_CP_NO_MIGRATE | ARM_CP_OVERRIDE,
1543       .resetvalue = 0 },
1544     REGINFO_SENTINEL
1545 };
1546
1547 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
1548     /* Cache status: RAZ because we have no cache so it's always clean */
1549     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
1550       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_MIGRATE,
1551       .resetvalue = 0 },
1552     REGINFO_SENTINEL
1553 };
1554
1555 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
1556     /* We never have a a block transfer operation in progress */
1557     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
1558       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_MIGRATE,
1559       .resetvalue = 0 },
1560     /* The cache ops themselves: these all NOP for QEMU */
1561     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
1562       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
1563     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
1564       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
1565     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
1566       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
1567     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
1568       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
1569     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
1570       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
1571     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
1572       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
1573     REGINFO_SENTINEL
1574 };
1575
1576 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
1577     /* The cache test-and-clean instructions always return (1 << 30)
1578      * to indicate that there are no dirty cache lines.
1579      */
1580     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
1581       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_MIGRATE,
1582       .resetvalue = (1 << 30) },
1583     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
1584       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_MIGRATE,
1585       .resetvalue = (1 << 30) },
1586     REGINFO_SENTINEL
1587 };
1588
1589 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
1590     /* Ignore ReadBuffer accesses */
1591     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
1592       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
1593       .access = PL1_RW, .resetvalue = 0,
1594       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_MIGRATE },
1595     REGINFO_SENTINEL
1596 };
1597
1598 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1599 {
1600     CPUState *cs = CPU(arm_env_get_cpu(env));
1601     uint32_t mpidr = cs->cpu_index;
1602     /* We don't support setting cluster ID ([8..11]) (known as Aff1
1603      * in later ARM ARM versions), or any of the higher affinity level fields,
1604      * so these bits always RAZ.
1605      */
1606     if (arm_feature(env, ARM_FEATURE_V7MP)) {
1607         mpidr |= (1U << 31);
1608         /* Cores which are uniprocessor (non-coherent)
1609          * but still implement the MP extensions set
1610          * bit 30. (For instance, A9UP.) However we do
1611          * not currently model any of those cores.
1612          */
1613     }
1614     return mpidr;
1615 }
1616
1617 static const ARMCPRegInfo mpidr_cp_reginfo[] = {
1618     { .name = "MPIDR", .state = ARM_CP_STATE_BOTH,
1619       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
1620       .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_MIGRATE },
1621     REGINFO_SENTINEL
1622 };
1623
1624 static uint64_t par64_read(CPUARMState *env, const ARMCPRegInfo *ri)
1625 {
1626     return ((uint64_t)env->cp15.c7_par_hi << 32) | env->cp15.c7_par;
1627 }
1628
1629 static void par64_write(CPUARMState *env, const ARMCPRegInfo *ri,
1630                         uint64_t value)
1631 {
1632     env->cp15.c7_par_hi = value >> 32;
1633     env->cp15.c7_par = value;
1634 }
1635
1636 static void par64_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1637 {
1638     env->cp15.c7_par_hi = 0;
1639     env->cp15.c7_par = 0;
1640 }
1641
1642 static const ARMCPRegInfo lpae_cp_reginfo[] = {
1643     /* NOP AMAIR0/1: the override is because these clash with the rather
1644      * broadly specified TLB_LOCKDOWN entry in the generic cp_reginfo.
1645      */
1646     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
1647       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
1648       .access = PL1_RW, .type = ARM_CP_CONST | ARM_CP_OVERRIDE,
1649       .resetvalue = 0 },
1650     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
1651     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
1652       .access = PL1_RW, .type = ARM_CP_CONST | ARM_CP_OVERRIDE,
1653       .resetvalue = 0 },
1654     /* 64 bit access versions of the (dummy) debug registers */
1655     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
1656       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
1657     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
1658       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
1659     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
1660       .access = PL1_RW, .type = ARM_CP_64BIT,
1661       .readfn = par64_read, .writefn = par64_write, .resetfn = par64_reset },
1662     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
1663       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_NO_MIGRATE,
1664       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el1),
1665       .writefn = vmsa_ttbr_write, .resetfn = arm_cp_reset_ignore },
1666     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
1667       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_NO_MIGRATE,
1668       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el1),
1669       .writefn = vmsa_ttbr_write, .resetfn = arm_cp_reset_ignore },
1670     REGINFO_SENTINEL
1671 };
1672
1673 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1674 {
1675     return vfp_get_fpcr(env);
1676 }
1677
1678 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1679                             uint64_t value)
1680 {
1681     vfp_set_fpcr(env, value);
1682 }
1683
1684 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1685 {
1686     return vfp_get_fpsr(env);
1687 }
1688
1689 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1690                             uint64_t value)
1691 {
1692     vfp_set_fpsr(env, value);
1693 }
1694
1695 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri)
1696 {
1697     if (arm_current_pl(env) == 0 && !(env->cp15.c1_sys & SCTLR_UMA)) {
1698         return CP_ACCESS_TRAP;
1699     }
1700     return CP_ACCESS_OK;
1701 }
1702
1703 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
1704                             uint64_t value)
1705 {
1706     env->daif = value & PSTATE_DAIF;
1707 }
1708
1709 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
1710                                           const ARMCPRegInfo *ri)
1711 {
1712     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
1713      * SCTLR_EL1.UCI is set.
1714      */
1715     if (arm_current_pl(env) == 0 && !(env->cp15.c1_sys & SCTLR_UCI)) {
1716         return CP_ACCESS_TRAP;
1717     }
1718     return CP_ACCESS_OK;
1719 }
1720
1721 static void tlbi_aa64_va_write(CPUARMState *env, const ARMCPRegInfo *ri,
1722                                uint64_t value)
1723 {
1724     /* Invalidate by VA (AArch64 version) */
1725     ARMCPU *cpu = arm_env_get_cpu(env);
1726     uint64_t pageaddr = value << 12;
1727     tlb_flush_page(CPU(cpu), pageaddr);
1728 }
1729
1730 static void tlbi_aa64_vaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
1731                                 uint64_t value)
1732 {
1733     /* Invalidate by VA, all ASIDs (AArch64 version) */
1734     ARMCPU *cpu = arm_env_get_cpu(env);
1735     uint64_t pageaddr = value << 12;
1736     tlb_flush_page(CPU(cpu), pageaddr);
1737 }
1738
1739 static void tlbi_aa64_asid_write(CPUARMState *env, const ARMCPRegInfo *ri,
1740                                  uint64_t value)
1741 {
1742     /* Invalidate by ASID (AArch64 version) */
1743     ARMCPU *cpu = arm_env_get_cpu(env);
1744     int asid = extract64(value, 48, 16);
1745     tlb_flush(CPU(cpu), asid == 0);
1746 }
1747
1748 static const ARMCPRegInfo v8_cp_reginfo[] = {
1749     /* Minimal set of EL0-visible registers. This will need to be expanded
1750      * significantly for system emulation of AArch64 CPUs.
1751      */
1752     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
1753       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
1754       .access = PL0_RW, .type = ARM_CP_NZCV },
1755     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
1756       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
1757       .type = ARM_CP_NO_MIGRATE,
1758       .access = PL0_RW, .accessfn = aa64_daif_access,
1759       .fieldoffset = offsetof(CPUARMState, daif),
1760       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
1761     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
1762       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
1763       .access = PL0_RW, .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
1764     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
1765       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
1766       .access = PL0_RW, .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
1767     /* Prohibit use of DC ZVA. OPTME: implement DC ZVA and allow its use.
1768      * For system mode the DZP bit here will need to be computed, not constant.
1769      */
1770     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
1771       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
1772       .access = PL0_R, .type = ARM_CP_CONST,
1773       .resetvalue = 0x10 },
1774     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
1775       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
1776       .access = PL1_R, .type = ARM_CP_CURRENTEL },
1777     /* Cache ops: all NOPs since we don't emulate caches */
1778     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
1779       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
1780       .access = PL1_W, .type = ARM_CP_NOP },
1781     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
1782       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
1783       .access = PL1_W, .type = ARM_CP_NOP },
1784     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
1785       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
1786       .access = PL0_W, .type = ARM_CP_NOP,
1787       .accessfn = aa64_cacheop_access },
1788     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
1789       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
1790       .access = PL1_W, .type = ARM_CP_NOP },
1791     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
1792       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
1793       .access = PL1_W, .type = ARM_CP_NOP },
1794     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
1795       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
1796       .access = PL0_W, .type = ARM_CP_NOP,
1797       .accessfn = aa64_cacheop_access },
1798     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
1799       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
1800       .access = PL1_W, .type = ARM_CP_NOP },
1801     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
1802       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
1803       .access = PL0_W, .type = ARM_CP_NOP,
1804       .accessfn = aa64_cacheop_access },
1805     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
1806       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
1807       .access = PL0_W, .type = ARM_CP_NOP,
1808       .accessfn = aa64_cacheop_access },
1809     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
1810       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
1811       .access = PL1_W, .type = ARM_CP_NOP },
1812     /* TLBI operations */
1813     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
1814       .opc0 = 1, .opc2 = 0, .crn = 8, .crm = 3, .opc2 = 0,
1815       .access = PL1_W, .type = ARM_CP_NO_MIGRATE,
1816       .writefn = tlbiall_write },
1817     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
1818       .opc0 = 1, .opc2 = 0, .crn = 8, .crm = 3, .opc2 = 1,
1819       .access = PL1_W, .type = ARM_CP_NO_MIGRATE,
1820       .writefn = tlbi_aa64_va_write },
1821     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
1822       .opc0 = 1, .opc2 = 0, .crn = 8, .crm = 3, .opc2 = 2,
1823       .access = PL1_W, .type = ARM_CP_NO_MIGRATE,
1824       .writefn = tlbi_aa64_asid_write },
1825     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
1826       .opc0 = 1, .opc2 = 0, .crn = 8, .crm = 3, .opc2 = 3,
1827       .access = PL1_W, .type = ARM_CP_NO_MIGRATE,
1828       .writefn = tlbi_aa64_vaa_write },
1829     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
1830       .opc0 = 1, .opc2 = 0, .crn = 8, .crm = 3, .opc2 = 5,
1831       .access = PL1_W, .type = ARM_CP_NO_MIGRATE,
1832       .writefn = tlbi_aa64_va_write },
1833     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
1834       .opc0 = 1, .opc2 = 0, .crn = 8, .crm = 3, .opc2 = 7,
1835       .access = PL1_W, .type = ARM_CP_NO_MIGRATE,
1836       .writefn = tlbi_aa64_vaa_write },
1837     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
1838       .opc0 = 1, .opc2 = 0, .crn = 8, .crm = 7, .opc2 = 0,
1839       .access = PL1_W, .type = ARM_CP_NO_MIGRATE,
1840       .writefn = tlbiall_write },
1841     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
1842       .opc0 = 1, .opc2 = 0, .crn = 8, .crm = 7, .opc2 = 1,
1843       .access = PL1_W, .type = ARM_CP_NO_MIGRATE,
1844       .writefn = tlbi_aa64_va_write },
1845     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
1846       .opc0 = 1, .opc2 = 0, .crn = 8, .crm = 7, .opc2 = 2,
1847       .access = PL1_W, .type = ARM_CP_NO_MIGRATE,
1848       .writefn = tlbi_aa64_asid_write },
1849     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
1850       .opc0 = 1, .opc2 = 0, .crn = 8, .crm = 7, .opc2 = 3,
1851       .access = PL1_W, .type = ARM_CP_NO_MIGRATE,
1852       .writefn = tlbi_aa64_vaa_write },
1853     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
1854       .opc0 = 1, .opc2 = 0, .crn = 8, .crm = 7, .opc2 = 5,
1855       .access = PL1_W, .type = ARM_CP_NO_MIGRATE,
1856       .writefn = tlbi_aa64_va_write },
1857     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
1858       .opc0 = 1, .opc2 = 0, .crn = 8, .crm = 7, .opc2 = 7,
1859       .access = PL1_W, .type = ARM_CP_NO_MIGRATE,
1860       .writefn = tlbi_aa64_vaa_write },
1861     /* Dummy implementation of monitor debug system control register:
1862      * we don't support debug.
1863      */
1864     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_AA64,
1865       .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
1866       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1867     /* We define a dummy WI OSLAR_EL1, because Linux writes to it. */
1868     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_AA64,
1869       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
1870       .access = PL1_W, .type = ARM_CP_NOP },
1871     REGINFO_SENTINEL
1872 };
1873
1874 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1875                         uint64_t value)
1876 {
1877     ARMCPU *cpu = arm_env_get_cpu(env);
1878
1879     env->cp15.c1_sys = value;
1880     /* ??? Lots of these bits are not implemented.  */
1881     /* This may enable/disable the MMU, so do a TLB flush.  */
1882     tlb_flush(CPU(cpu), 1);
1883 }
1884
1885 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri)
1886 {
1887     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
1888      * but the AArch32 CTR has its own reginfo struct)
1889      */
1890     if (arm_current_pl(env) == 0 && !(env->cp15.c1_sys & SCTLR_UCT)) {
1891         return CP_ACCESS_TRAP;
1892     }
1893     return CP_ACCESS_OK;
1894 }
1895
1896 static void define_aarch64_debug_regs(ARMCPU *cpu)
1897 {
1898     /* Define breakpoint and watchpoint registers. These do nothing
1899      * but read as written, for now.
1900      */
1901     int i;
1902
1903     for (i = 0; i < 16; i++) {
1904         ARMCPRegInfo dbgregs[] = {
1905             { .name = "DBGBVR", .state = ARM_CP_STATE_AA64,
1906               .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
1907               .access = PL1_RW,
1908               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]) },
1909             { .name = "DBGBCR", .state = ARM_CP_STATE_AA64,
1910               .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
1911               .access = PL1_RW,
1912               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]) },
1913             { .name = "DBGWVR", .state = ARM_CP_STATE_AA64,
1914               .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
1915               .access = PL1_RW,
1916               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]) },
1917             { .name = "DBGWCR", .state = ARM_CP_STATE_AA64,
1918               .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
1919               .access = PL1_RW,
1920               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]) },
1921                REGINFO_SENTINEL
1922         };
1923         define_arm_cp_regs(cpu, dbgregs);
1924     }
1925 }
1926
1927 void register_cp_regs_for_features(ARMCPU *cpu)
1928 {
1929     /* Register all the coprocessor registers based on feature bits */
1930     CPUARMState *env = &cpu->env;
1931     if (arm_feature(env, ARM_FEATURE_M)) {
1932         /* M profile has no coprocessor registers */
1933         return;
1934     }
1935
1936     define_arm_cp_regs(cpu, cp_reginfo);
1937     if (arm_feature(env, ARM_FEATURE_V6)) {
1938         /* The ID registers all have impdef reset values */
1939         ARMCPRegInfo v6_idregs[] = {
1940             { .name = "ID_PFR0", .cp = 15, .crn = 0, .crm = 1,
1941               .opc1 = 0, .opc2 = 0, .access = PL1_R, .type = ARM_CP_CONST,
1942               .resetvalue = cpu->id_pfr0 },
1943             { .name = "ID_PFR1", .cp = 15, .crn = 0, .crm = 1,
1944               .opc1 = 0, .opc2 = 1, .access = PL1_R, .type = ARM_CP_CONST,
1945               .resetvalue = cpu->id_pfr1 },
1946             { .name = "ID_DFR0", .cp = 15, .crn = 0, .crm = 1,
1947               .opc1 = 0, .opc2 = 2, .access = PL1_R, .type = ARM_CP_CONST,
1948               .resetvalue = cpu->id_dfr0 },
1949             { .name = "ID_AFR0", .cp = 15, .crn = 0, .crm = 1,
1950               .opc1 = 0, .opc2 = 3, .access = PL1_R, .type = ARM_CP_CONST,
1951               .resetvalue = cpu->id_afr0 },
1952             { .name = "ID_MMFR0", .cp = 15, .crn = 0, .crm = 1,
1953               .opc1 = 0, .opc2 = 4, .access = PL1_R, .type = ARM_CP_CONST,
1954               .resetvalue = cpu->id_mmfr0 },
1955             { .name = "ID_MMFR1", .cp = 15, .crn = 0, .crm = 1,
1956               .opc1 = 0, .opc2 = 5, .access = PL1_R, .type = ARM_CP_CONST,
1957               .resetvalue = cpu->id_mmfr1 },
1958             { .name = "ID_MMFR2", .cp = 15, .crn = 0, .crm = 1,
1959               .opc1 = 0, .opc2 = 6, .access = PL1_R, .type = ARM_CP_CONST,
1960               .resetvalue = cpu->id_mmfr2 },
1961             { .name = "ID_MMFR3", .cp = 15, .crn = 0, .crm = 1,
1962               .opc1 = 0, .opc2 = 7, .access = PL1_R, .type = ARM_CP_CONST,
1963               .resetvalue = cpu->id_mmfr3 },
1964             { .name = "ID_ISAR0", .cp = 15, .crn = 0, .crm = 2,
1965               .opc1 = 0, .opc2 = 0, .access = PL1_R, .type = ARM_CP_CONST,
1966               .resetvalue = cpu->id_isar0 },
1967             { .name = "ID_ISAR1", .cp = 15, .crn = 0, .crm = 2,
1968               .opc1 = 0, .opc2 = 1, .access = PL1_R, .type = ARM_CP_CONST,
1969               .resetvalue = cpu->id_isar1 },
1970             { .name = "ID_ISAR2", .cp = 15, .crn = 0, .crm = 2,
1971               .opc1 = 0, .opc2 = 2, .access = PL1_R, .type = ARM_CP_CONST,
1972               .resetvalue = cpu->id_isar2 },
1973             { .name = "ID_ISAR3", .cp = 15, .crn = 0, .crm = 2,
1974               .opc1 = 0, .opc2 = 3, .access = PL1_R, .type = ARM_CP_CONST,
1975               .resetvalue = cpu->id_isar3 },
1976             { .name = "ID_ISAR4", .cp = 15, .crn = 0, .crm = 2,
1977               .opc1 = 0, .opc2 = 4, .access = PL1_R, .type = ARM_CP_CONST,
1978               .resetvalue = cpu->id_isar4 },
1979             { .name = "ID_ISAR5", .cp = 15, .crn = 0, .crm = 2,
1980               .opc1 = 0, .opc2 = 5, .access = PL1_R, .type = ARM_CP_CONST,
1981               .resetvalue = cpu->id_isar5 },
1982             /* 6..7 are as yet unallocated and must RAZ */
1983             { .name = "ID_ISAR6", .cp = 15, .crn = 0, .crm = 2,
1984               .opc1 = 0, .opc2 = 6, .access = PL1_R, .type = ARM_CP_CONST,
1985               .resetvalue = 0 },
1986             { .name = "ID_ISAR7", .cp = 15, .crn = 0, .crm = 2,
1987               .opc1 = 0, .opc2 = 7, .access = PL1_R, .type = ARM_CP_CONST,
1988               .resetvalue = 0 },
1989             REGINFO_SENTINEL
1990         };
1991         define_arm_cp_regs(cpu, v6_idregs);
1992         define_arm_cp_regs(cpu, v6_cp_reginfo);
1993     } else {
1994         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
1995     }
1996     if (arm_feature(env, ARM_FEATURE_V6K)) {
1997         define_arm_cp_regs(cpu, v6k_cp_reginfo);
1998     }
1999     if (arm_feature(env, ARM_FEATURE_V7)) {
2000         /* v7 performance monitor control register: same implementor
2001          * field as main ID register, and we implement only the cycle
2002          * count register.
2003          */
2004 #ifndef CONFIG_USER_ONLY
2005         ARMCPRegInfo pmcr = {
2006             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
2007             .access = PL0_RW, .resetvalue = cpu->midr & 0xff000000,
2008             .type = ARM_CP_IO,
2009             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
2010             .accessfn = pmreg_access, .writefn = pmcr_write,
2011             .raw_writefn = raw_write,
2012         };
2013         define_one_arm_cp_reg(cpu, &pmcr);
2014 #endif
2015         ARMCPRegInfo clidr = {
2016             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
2017             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
2018             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
2019         };
2020         define_one_arm_cp_reg(cpu, &clidr);
2021         define_arm_cp_regs(cpu, v7_cp_reginfo);
2022     } else {
2023         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
2024     }
2025     if (arm_feature(env, ARM_FEATURE_V8)) {
2026         /* AArch64 ID registers, which all have impdef reset values */
2027         ARMCPRegInfo v8_idregs[] = {
2028             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
2029               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
2030               .access = PL1_R, .type = ARM_CP_CONST,
2031               .resetvalue = cpu->id_aa64pfr0 },
2032             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
2033               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
2034               .access = PL1_R, .type = ARM_CP_CONST,
2035               .resetvalue = cpu->id_aa64pfr1},
2036             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
2037               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
2038               .access = PL1_R, .type = ARM_CP_CONST,
2039               /* We mask out the PMUVer field, beacuse we don't currently
2040                * implement the PMU. Not advertising it prevents the guest
2041                * from trying to use it and getting UNDEFs on registers we
2042                * don't implement.
2043                */
2044               .resetvalue = cpu->id_aa64dfr0 & ~0xf00 },
2045             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
2046               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
2047               .access = PL1_R, .type = ARM_CP_CONST,
2048               .resetvalue = cpu->id_aa64dfr1 },
2049             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
2050               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
2051               .access = PL1_R, .type = ARM_CP_CONST,
2052               .resetvalue = cpu->id_aa64afr0 },
2053             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
2054               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
2055               .access = PL1_R, .type = ARM_CP_CONST,
2056               .resetvalue = cpu->id_aa64afr1 },
2057             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
2058               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
2059               .access = PL1_R, .type = ARM_CP_CONST,
2060               .resetvalue = cpu->id_aa64isar0 },
2061             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
2062               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
2063               .access = PL1_R, .type = ARM_CP_CONST,
2064               .resetvalue = cpu->id_aa64isar1 },
2065             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
2066               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
2067               .access = PL1_R, .type = ARM_CP_CONST,
2068               .resetvalue = cpu->id_aa64mmfr0 },
2069             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
2070               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
2071               .access = PL1_R, .type = ARM_CP_CONST,
2072               .resetvalue = cpu->id_aa64mmfr1 },
2073             REGINFO_SENTINEL
2074         };
2075         define_arm_cp_regs(cpu, v8_idregs);
2076         define_arm_cp_regs(cpu, v8_cp_reginfo);
2077         define_aarch64_debug_regs(cpu);
2078     }
2079     if (arm_feature(env, ARM_FEATURE_MPU)) {
2080         /* These are the MPU registers prior to PMSAv6. Any new
2081          * PMSA core later than the ARM946 will require that we
2082          * implement the PMSAv6 or PMSAv7 registers, which are
2083          * completely different.
2084          */
2085         assert(!arm_feature(env, ARM_FEATURE_V6));
2086         define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
2087     } else {
2088         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
2089     }
2090     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
2091         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
2092     }
2093     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
2094         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
2095     }
2096     if (arm_feature(env, ARM_FEATURE_VAPA)) {
2097         define_arm_cp_regs(cpu, vapa_cp_reginfo);
2098     }
2099     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
2100         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
2101     }
2102     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
2103         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
2104     }
2105     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
2106         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
2107     }
2108     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
2109         define_arm_cp_regs(cpu, omap_cp_reginfo);
2110     }
2111     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
2112         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
2113     }
2114     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
2115         define_arm_cp_regs(cpu, xscale_cp_reginfo);
2116     }
2117     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
2118         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
2119     }
2120     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2121         define_arm_cp_regs(cpu, lpae_cp_reginfo);
2122     }
2123     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
2124      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
2125      * be read-only (ie write causes UNDEF exception).
2126      */
2127     {
2128         ARMCPRegInfo id_cp_reginfo[] = {
2129             /* Note that the MIDR isn't a simple constant register because
2130              * of the TI925 behaviour where writes to another register can
2131              * cause the MIDR value to change.
2132              *
2133              * Unimplemented registers in the c15 0 0 0 space default to
2134              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
2135              * and friends override accordingly.
2136              */
2137             { .name = "MIDR",
2138               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
2139               .access = PL1_R, .resetvalue = cpu->midr,
2140               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
2141               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
2142               .type = ARM_CP_OVERRIDE },
2143             { .name = "MIDR_EL1", .state = ARM_CP_STATE_AA64,
2144               .opc0 = 3, .opc1 = 0, .opc2 = 0, .crn = 0, .crm = 0,
2145               .access = PL1_R, .resetvalue = cpu->midr, .type = ARM_CP_CONST },
2146             { .name = "CTR",
2147               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
2148               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
2149             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
2150               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
2151               .access = PL0_R, .accessfn = ctr_el0_access,
2152               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
2153             { .name = "TCMTR",
2154               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
2155               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2156             { .name = "TLBTR",
2157               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
2158               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2159             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
2160             { .name = "DUMMY",
2161               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
2162               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2163             { .name = "DUMMY",
2164               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
2165               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2166             { .name = "DUMMY",
2167               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
2168               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2169             { .name = "DUMMY",
2170               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
2171               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2172             { .name = "DUMMY",
2173               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
2174               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2175             REGINFO_SENTINEL
2176         };
2177         ARMCPRegInfo crn0_wi_reginfo = {
2178             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
2179             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
2180             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
2181         };
2182         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
2183             arm_feature(env, ARM_FEATURE_STRONGARM)) {
2184             ARMCPRegInfo *r;
2185             /* Register the blanket "writes ignored" value first to cover the
2186              * whole space. Then update the specific ID registers to allow write
2187              * access, so that they ignore writes rather than causing them to
2188              * UNDEF.
2189              */
2190             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
2191             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
2192                 r->access = PL1_RW;
2193             }
2194         }
2195         define_arm_cp_regs(cpu, id_cp_reginfo);
2196     }
2197
2198     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
2199         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
2200     }
2201
2202     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
2203         ARMCPRegInfo auxcr = {
2204             .name = "AUXCR", .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1,
2205             .access = PL1_RW, .type = ARM_CP_CONST,
2206             .resetvalue = cpu->reset_auxcr
2207         };
2208         define_one_arm_cp_reg(cpu, &auxcr);
2209     }
2210
2211     if (arm_feature(env, ARM_FEATURE_CBAR)) {
2212         ARMCPRegInfo cbar = {
2213             .name = "CBAR", .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
2214             .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
2215             .fieldoffset = offsetof(CPUARMState, cp15.c15_config_base_address)
2216         };
2217         define_one_arm_cp_reg(cpu, &cbar);
2218     }
2219
2220     /* Generic registers whose values depend on the implementation */
2221     {
2222         ARMCPRegInfo sctlr = {
2223             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
2224             .opc0 = 3, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
2225             .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c1_sys),
2226             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
2227             .raw_writefn = raw_write,
2228         };
2229         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
2230             /* Normally we would always end the TB on an SCTLR write, but Linux
2231              * arch/arm/mach-pxa/sleep.S expects two instructions following
2232              * an MMU enable to execute from cache.  Imitate this behaviour.
2233              */
2234             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
2235         }
2236         define_one_arm_cp_reg(cpu, &sctlr);
2237     }
2238 }
2239
2240 ARMCPU *cpu_arm_init(const char *cpu_model)
2241 {
2242     return ARM_CPU(cpu_generic_init(TYPE_ARM_CPU, cpu_model));
2243 }
2244
2245 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
2246 {
2247     CPUState *cs = CPU(cpu);
2248     CPUARMState *env = &cpu->env;
2249
2250     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
2251         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
2252                                  aarch64_fpu_gdb_set_reg,
2253                                  34, "aarch64-fpu.xml", 0);
2254     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
2255         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
2256                                  51, "arm-neon.xml", 0);
2257     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
2258         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
2259                                  35, "arm-vfp3.xml", 0);
2260     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
2261         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
2262                                  19, "arm-vfp.xml", 0);
2263     }
2264 }
2265
2266 /* Sort alphabetically by type name, except for "any". */
2267 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
2268 {
2269     ObjectClass *class_a = (ObjectClass *)a;
2270     ObjectClass *class_b = (ObjectClass *)b;
2271     const char *name_a, *name_b;
2272
2273     name_a = object_class_get_name(class_a);
2274     name_b = object_class_get_name(class_b);
2275     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
2276         return 1;
2277     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
2278         return -1;
2279     } else {
2280         return strcmp(name_a, name_b);
2281     }
2282 }
2283
2284 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
2285 {
2286     ObjectClass *oc = data;
2287     CPUListState *s = user_data;
2288     const char *typename;
2289     char *name;
2290
2291     typename = object_class_get_name(oc);
2292     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
2293     (*s->cpu_fprintf)(s->file, "  %s\n",
2294                       name);
2295     g_free(name);
2296 }
2297
2298 void arm_cpu_list(FILE *f, fprintf_function cpu_fprintf)
2299 {
2300     CPUListState s = {
2301         .file = f,
2302         .cpu_fprintf = cpu_fprintf,
2303     };
2304     GSList *list;
2305
2306     list = object_class_get_list(TYPE_ARM_CPU, false);
2307     list = g_slist_sort(list, arm_cpu_list_compare);
2308     (*cpu_fprintf)(f, "Available CPUs:\n");
2309     g_slist_foreach(list, arm_cpu_list_entry, &s);
2310     g_slist_free(list);
2311 #ifdef CONFIG_KVM
2312     /* The 'host' CPU type is dynamically registered only if KVM is
2313      * enabled, so we have to special-case it here:
2314      */
2315     (*cpu_fprintf)(f, "  host (only available in KVM mode)\n");
2316 #endif
2317 }
2318
2319 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
2320 {
2321     ObjectClass *oc = data;
2322     CpuDefinitionInfoList **cpu_list = user_data;
2323     CpuDefinitionInfoList *entry;
2324     CpuDefinitionInfo *info;
2325     const char *typename;
2326
2327     typename = object_class_get_name(oc);
2328     info = g_malloc0(sizeof(*info));
2329     info->name = g_strndup(typename,
2330                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
2331
2332     entry = g_malloc0(sizeof(*entry));
2333     entry->value = info;
2334     entry->next = *cpu_list;
2335     *cpu_list = entry;
2336 }
2337
2338 CpuDefinitionInfoList *arch_query_cpu_definitions(Error **errp)
2339 {
2340     CpuDefinitionInfoList *cpu_list = NULL;
2341     GSList *list;
2342
2343     list = object_class_get_list(TYPE_ARM_CPU, false);
2344     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
2345     g_slist_free(list);
2346
2347     return cpu_list;
2348 }
2349
2350 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
2351                                    void *opaque, int state,
2352                                    int crm, int opc1, int opc2)
2353 {
2354     /* Private utility function for define_one_arm_cp_reg_with_opaque():
2355      * add a single reginfo struct to the hash table.
2356      */
2357     uint32_t *key = g_new(uint32_t, 1);
2358     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
2359     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
2360     if (r->state == ARM_CP_STATE_BOTH && state == ARM_CP_STATE_AA32) {
2361         /* The AArch32 view of a shared register sees the lower 32 bits
2362          * of a 64 bit backing field. It is not migratable as the AArch64
2363          * view handles that. AArch64 also handles reset.
2364          * We assume it is a cp15 register.
2365          */
2366         r2->cp = 15;
2367         r2->type |= ARM_CP_NO_MIGRATE;
2368         r2->resetfn = arm_cp_reset_ignore;
2369 #ifdef HOST_WORDS_BIGENDIAN
2370         if (r2->fieldoffset) {
2371             r2->fieldoffset += sizeof(uint32_t);
2372         }
2373 #endif
2374     }
2375     if (state == ARM_CP_STATE_AA64) {
2376         /* To allow abbreviation of ARMCPRegInfo
2377          * definitions, we treat cp == 0 as equivalent to
2378          * the value for "standard guest-visible sysreg".
2379          */
2380         if (r->cp == 0) {
2381             r2->cp = CP_REG_ARM64_SYSREG_CP;
2382         }
2383         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
2384                                   r2->opc0, opc1, opc2);
2385     } else {
2386         *key = ENCODE_CP_REG(r2->cp, is64, r2->crn, crm, opc1, opc2);
2387     }
2388     if (opaque) {
2389         r2->opaque = opaque;
2390     }
2391     /* reginfo passed to helpers is correct for the actual access,
2392      * and is never ARM_CP_STATE_BOTH:
2393      */
2394     r2->state = state;
2395     /* Make sure reginfo passed to helpers for wildcarded regs
2396      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
2397      */
2398     r2->crm = crm;
2399     r2->opc1 = opc1;
2400     r2->opc2 = opc2;
2401     /* By convention, for wildcarded registers only the first
2402      * entry is used for migration; the others are marked as
2403      * NO_MIGRATE so we don't try to transfer the register
2404      * multiple times. Special registers (ie NOP/WFI) are
2405      * never migratable.
2406      */
2407     if ((r->type & ARM_CP_SPECIAL) ||
2408         ((r->crm == CP_ANY) && crm != 0) ||
2409         ((r->opc1 == CP_ANY) && opc1 != 0) ||
2410         ((r->opc2 == CP_ANY) && opc2 != 0)) {
2411         r2->type |= ARM_CP_NO_MIGRATE;
2412     }
2413
2414     /* Overriding of an existing definition must be explicitly
2415      * requested.
2416      */
2417     if (!(r->type & ARM_CP_OVERRIDE)) {
2418         ARMCPRegInfo *oldreg;
2419         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
2420         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
2421             fprintf(stderr, "Register redefined: cp=%d %d bit "
2422                     "crn=%d crm=%d opc1=%d opc2=%d, "
2423                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
2424                     r2->crn, r2->crm, r2->opc1, r2->opc2,
2425                     oldreg->name, r2->name);
2426             g_assert_not_reached();
2427         }
2428     }
2429     g_hash_table_insert(cpu->cp_regs, key, r2);
2430 }
2431
2432
2433 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
2434                                        const ARMCPRegInfo *r, void *opaque)
2435 {
2436     /* Define implementations of coprocessor registers.
2437      * We store these in a hashtable because typically
2438      * there are less than 150 registers in a space which
2439      * is 16*16*16*8*8 = 262144 in size.
2440      * Wildcarding is supported for the crm, opc1 and opc2 fields.
2441      * If a register is defined twice then the second definition is
2442      * used, so this can be used to define some generic registers and
2443      * then override them with implementation specific variations.
2444      * At least one of the original and the second definition should
2445      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
2446      * against accidental use.
2447      *
2448      * The state field defines whether the register is to be
2449      * visible in the AArch32 or AArch64 execution state. If the
2450      * state is set to ARM_CP_STATE_BOTH then we synthesise a
2451      * reginfo structure for the AArch32 view, which sees the lower
2452      * 32 bits of the 64 bit register.
2453      *
2454      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
2455      * be wildcarded. AArch64 registers are always considered to be 64
2456      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
2457      * the register, if any.
2458      */
2459     int crm, opc1, opc2, state;
2460     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
2461     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
2462     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
2463     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
2464     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
2465     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
2466     /* 64 bit registers have only CRm and Opc1 fields */
2467     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
2468     /* op0 only exists in the AArch64 encodings */
2469     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
2470     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
2471     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
2472     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
2473      * encodes a minimum access level for the register. We roll this
2474      * runtime check into our general permission check code, so check
2475      * here that the reginfo's specified permissions are strict enough
2476      * to encompass the generic architectural permission check.
2477      */
2478     if (r->state != ARM_CP_STATE_AA32) {
2479         int mask = 0;
2480         switch (r->opc1) {
2481         case 0: case 1: case 2:
2482             /* min_EL EL1 */
2483             mask = PL1_RW;
2484             break;
2485         case 3:
2486             /* min_EL EL0 */
2487             mask = PL0_RW;
2488             break;
2489         case 4:
2490             /* min_EL EL2 */
2491             mask = PL2_RW;
2492             break;
2493         case 5:
2494             /* unallocated encoding, so not possible */
2495             assert(false);
2496             break;
2497         case 6:
2498             /* min_EL EL3 */
2499             mask = PL3_RW;
2500             break;
2501         case 7:
2502             /* min_EL EL1, secure mode only (we don't check the latter) */
2503             mask = PL1_RW;
2504             break;
2505         default:
2506             /* broken reginfo with out-of-range opc1 */
2507             assert(false);
2508             break;
2509         }
2510         /* assert our permissions are not too lax (stricter is fine) */
2511         assert((r->access & ~mask) == 0);
2512     }
2513
2514     /* Check that the register definition has enough info to handle
2515      * reads and writes if they are permitted.
2516      */
2517     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
2518         if (r->access & PL3_R) {
2519             assert(r->fieldoffset || r->readfn);
2520         }
2521         if (r->access & PL3_W) {
2522             assert(r->fieldoffset || r->writefn);
2523         }
2524     }
2525     /* Bad type field probably means missing sentinel at end of reg list */
2526     assert(cptype_valid(r->type));
2527     for (crm = crmmin; crm <= crmmax; crm++) {
2528         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
2529             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
2530                 for (state = ARM_CP_STATE_AA32;
2531                      state <= ARM_CP_STATE_AA64; state++) {
2532                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
2533                         continue;
2534                     }
2535                     add_cpreg_to_hashtable(cpu, r, opaque, state,
2536                                            crm, opc1, opc2);
2537                 }
2538             }
2539         }
2540     }
2541 }
2542
2543 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
2544                                     const ARMCPRegInfo *regs, void *opaque)
2545 {
2546     /* Define a whole list of registers */
2547     const ARMCPRegInfo *r;
2548     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
2549         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
2550     }
2551 }
2552
2553 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
2554 {
2555     return g_hash_table_lookup(cpregs, &encoded_cp);
2556 }
2557
2558 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
2559                          uint64_t value)
2560 {
2561     /* Helper coprocessor write function for write-ignore registers */
2562 }
2563
2564 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
2565 {
2566     /* Helper coprocessor write function for read-as-zero registers */
2567     return 0;
2568 }
2569
2570 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
2571 {
2572     /* Helper coprocessor reset function for do-nothing-on-reset registers */
2573 }
2574
2575 static int bad_mode_switch(CPUARMState *env, int mode)
2576 {
2577     /* Return true if it is not valid for us to switch to
2578      * this CPU mode (ie all the UNPREDICTABLE cases in
2579      * the ARM ARM CPSRWriteByInstr pseudocode).
2580      */
2581     switch (mode) {
2582     case ARM_CPU_MODE_USR:
2583     case ARM_CPU_MODE_SYS:
2584     case ARM_CPU_MODE_SVC:
2585     case ARM_CPU_MODE_ABT:
2586     case ARM_CPU_MODE_UND:
2587     case ARM_CPU_MODE_IRQ:
2588     case ARM_CPU_MODE_FIQ:
2589         return 0;
2590     default:
2591         return 1;
2592     }
2593 }
2594
2595 uint32_t cpsr_read(CPUARMState *env)
2596 {
2597     int ZF;
2598     ZF = (env->ZF == 0);
2599     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
2600         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
2601         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
2602         | ((env->condexec_bits & 0xfc) << 8)
2603         | (env->GE << 16) | (env->daif & CPSR_AIF);
2604 }
2605
2606 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask)
2607 {
2608     if (mask & CPSR_NZCV) {
2609         env->ZF = (~val) & CPSR_Z;
2610         env->NF = val;
2611         env->CF = (val >> 29) & 1;
2612         env->VF = (val << 3) & 0x80000000;
2613     }
2614     if (mask & CPSR_Q)
2615         env->QF = ((val & CPSR_Q) != 0);
2616     if (mask & CPSR_T)
2617         env->thumb = ((val & CPSR_T) != 0);
2618     if (mask & CPSR_IT_0_1) {
2619         env->condexec_bits &= ~3;
2620         env->condexec_bits |= (val >> 25) & 3;
2621     }
2622     if (mask & CPSR_IT_2_7) {
2623         env->condexec_bits &= 3;
2624         env->condexec_bits |= (val >> 8) & 0xfc;
2625     }
2626     if (mask & CPSR_GE) {
2627         env->GE = (val >> 16) & 0xf;
2628     }
2629
2630     env->daif &= ~(CPSR_AIF & mask);
2631     env->daif |= val & CPSR_AIF & mask;
2632
2633     if ((env->uncached_cpsr ^ val) & mask & CPSR_M) {
2634         if (bad_mode_switch(env, val & CPSR_M)) {
2635             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE.
2636              * We choose to ignore the attempt and leave the CPSR M field
2637              * untouched.
2638              */
2639             mask &= ~CPSR_M;
2640         } else {
2641             switch_mode(env, val & CPSR_M);
2642         }
2643     }
2644     mask &= ~CACHED_CPSR_BITS;
2645     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
2646 }
2647
2648 /* Sign/zero extend */
2649 uint32_t HELPER(sxtb16)(uint32_t x)
2650 {
2651     uint32_t res;
2652     res = (uint16_t)(int8_t)x;
2653     res |= (uint32_t)(int8_t)(x >> 16) << 16;
2654     return res;
2655 }
2656
2657 uint32_t HELPER(uxtb16)(uint32_t x)
2658 {
2659     uint32_t res;
2660     res = (uint16_t)(uint8_t)x;
2661     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
2662     return res;
2663 }
2664
2665 uint32_t HELPER(clz)(uint32_t x)
2666 {
2667     return clz32(x);
2668 }
2669
2670 int32_t HELPER(sdiv)(int32_t num, int32_t den)
2671 {
2672     if (den == 0)
2673       return 0;
2674     if (num == INT_MIN && den == -1)
2675       return INT_MIN;
2676     return num / den;
2677 }
2678
2679 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
2680 {
2681     if (den == 0)
2682       return 0;
2683     return num / den;
2684 }
2685
2686 uint32_t HELPER(rbit)(uint32_t x)
2687 {
2688     x =  ((x & 0xff000000) >> 24)
2689        | ((x & 0x00ff0000) >> 8)
2690        | ((x & 0x0000ff00) << 8)
2691        | ((x & 0x000000ff) << 24);
2692     x =  ((x & 0xf0f0f0f0) >> 4)
2693        | ((x & 0x0f0f0f0f) << 4);
2694     x =  ((x & 0x88888888) >> 3)
2695        | ((x & 0x44444444) >> 1)
2696        | ((x & 0x22222222) << 1)
2697        | ((x & 0x11111111) << 3);
2698     return x;
2699 }
2700
2701 #if defined(CONFIG_USER_ONLY)
2702
2703 void arm_cpu_do_interrupt(CPUState *cs)
2704 {
2705     cs->exception_index = -1;
2706 }
2707
2708 int arm_cpu_handle_mmu_fault(CPUState *cs, vaddr address, int rw,
2709                              int mmu_idx)
2710 {
2711     ARMCPU *cpu = ARM_CPU(cs);
2712     CPUARMState *env = &cpu->env;
2713
2714     env->exception.vaddress = address;
2715     if (rw == 2) {
2716         cs->exception_index = EXCP_PREFETCH_ABORT;
2717     } else {
2718         cs->exception_index = EXCP_DATA_ABORT;
2719     }
2720     return 1;
2721 }
2722
2723 /* These should probably raise undefined insn exceptions.  */
2724 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
2725 {
2726     ARMCPU *cpu = arm_env_get_cpu(env);
2727
2728     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
2729 }
2730
2731 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
2732 {
2733     ARMCPU *cpu = arm_env_get_cpu(env);
2734
2735     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
2736     return 0;
2737 }
2738
2739 void switch_mode(CPUARMState *env, int mode)
2740 {
2741     ARMCPU *cpu = arm_env_get_cpu(env);
2742
2743     if (mode != ARM_CPU_MODE_USR) {
2744         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
2745     }
2746 }
2747
2748 void HELPER(set_r13_banked)(CPUARMState *env, uint32_t mode, uint32_t val)
2749 {
2750     ARMCPU *cpu = arm_env_get_cpu(env);
2751
2752     cpu_abort(CPU(cpu), "banked r13 write\n");
2753 }
2754
2755 uint32_t HELPER(get_r13_banked)(CPUARMState *env, uint32_t mode)
2756 {
2757     ARMCPU *cpu = arm_env_get_cpu(env);
2758
2759     cpu_abort(CPU(cpu), "banked r13 read\n");
2760     return 0;
2761 }
2762
2763 #else
2764
2765 /* Map CPU modes onto saved register banks.  */
2766 int bank_number(int mode)
2767 {
2768     switch (mode) {
2769     case ARM_CPU_MODE_USR:
2770     case ARM_CPU_MODE_SYS:
2771         return 0;
2772     case ARM_CPU_MODE_SVC:
2773         return 1;
2774     case ARM_CPU_MODE_ABT:
2775         return 2;
2776     case ARM_CPU_MODE_UND:
2777         return 3;
2778     case ARM_CPU_MODE_IRQ:
2779         return 4;
2780     case ARM_CPU_MODE_FIQ:
2781         return 5;
2782     }
2783     hw_error("bank number requested for bad CPSR mode value 0x%x\n", mode);
2784 }
2785
2786 void switch_mode(CPUARMState *env, int mode)
2787 {
2788     int old_mode;
2789     int i;
2790
2791     old_mode = env->uncached_cpsr & CPSR_M;
2792     if (mode == old_mode)
2793         return;
2794
2795     if (old_mode == ARM_CPU_MODE_FIQ) {
2796         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
2797         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
2798     } else if (mode == ARM_CPU_MODE_FIQ) {
2799         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
2800         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
2801     }
2802
2803     i = bank_number(old_mode);
2804     env->banked_r13[i] = env->regs[13];
2805     env->banked_r14[i] = env->regs[14];
2806     env->banked_spsr[i] = env->spsr;
2807
2808     i = bank_number(mode);
2809     env->regs[13] = env->banked_r13[i];
2810     env->regs[14] = env->banked_r14[i];
2811     env->spsr = env->banked_spsr[i];
2812 }
2813
2814 static void v7m_push(CPUARMState *env, uint32_t val)
2815 {
2816     CPUState *cs = CPU(arm_env_get_cpu(env));
2817
2818     env->regs[13] -= 4;
2819     stl_phys(cs->as, env->regs[13], val);
2820 }
2821
2822 static uint32_t v7m_pop(CPUARMState *env)
2823 {
2824     CPUState *cs = CPU(arm_env_get_cpu(env));
2825     uint32_t val;
2826
2827     val = ldl_phys(cs->as, env->regs[13]);
2828     env->regs[13] += 4;
2829     return val;
2830 }
2831
2832 /* Switch to V7M main or process stack pointer.  */
2833 static void switch_v7m_sp(CPUARMState *env, int process)
2834 {
2835     uint32_t tmp;
2836     if (env->v7m.current_sp != process) {
2837         tmp = env->v7m.other_sp;
2838         env->v7m.other_sp = env->regs[13];
2839         env->regs[13] = tmp;
2840         env->v7m.current_sp = process;
2841     }
2842 }
2843
2844 static void do_v7m_exception_exit(CPUARMState *env)
2845 {
2846     uint32_t type;
2847     uint32_t xpsr;
2848
2849     type = env->regs[15];
2850     if (env->v7m.exception != 0)
2851         armv7m_nvic_complete_irq(env->nvic, env->v7m.exception);
2852
2853     /* Switch to the target stack.  */
2854     switch_v7m_sp(env, (type & 4) != 0);
2855     /* Pop registers.  */
2856     env->regs[0] = v7m_pop(env);
2857     env->regs[1] = v7m_pop(env);
2858     env->regs[2] = v7m_pop(env);
2859     env->regs[3] = v7m_pop(env);
2860     env->regs[12] = v7m_pop(env);
2861     env->regs[14] = v7m_pop(env);
2862     env->regs[15] = v7m_pop(env);
2863     xpsr = v7m_pop(env);
2864     xpsr_write(env, xpsr, 0xfffffdff);
2865     /* Undo stack alignment.  */
2866     if (xpsr & 0x200)
2867         env->regs[13] |= 4;
2868     /* ??? The exception return type specifies Thread/Handler mode.  However
2869        this is also implied by the xPSR value. Not sure what to do
2870        if there is a mismatch.  */
2871     /* ??? Likewise for mismatches between the CONTROL register and the stack
2872        pointer.  */
2873 }
2874
2875 /* Exception names for debug logging; note that not all of these
2876  * precisely correspond to architectural exceptions.
2877  */
2878 static const char * const excnames[] = {
2879     [EXCP_UDEF] = "Undefined Instruction",
2880     [EXCP_SWI] = "SVC",
2881     [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
2882     [EXCP_DATA_ABORT] = "Data Abort",
2883     [EXCP_IRQ] = "IRQ",
2884     [EXCP_FIQ] = "FIQ",
2885     [EXCP_BKPT] = "Breakpoint",
2886     [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
2887     [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
2888     [EXCP_STREX] = "QEMU intercept of STREX",
2889 };
2890
2891 static inline void arm_log_exception(int idx)
2892 {
2893     if (qemu_loglevel_mask(CPU_LOG_INT)) {
2894         const char *exc = NULL;
2895
2896         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
2897             exc = excnames[idx];
2898         }
2899         if (!exc) {
2900             exc = "unknown";
2901         }
2902         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
2903     }
2904 }
2905
2906 void arm_v7m_cpu_do_interrupt(CPUState *cs)
2907 {
2908     ARMCPU *cpu = ARM_CPU(cs);
2909     CPUARMState *env = &cpu->env;
2910     uint32_t xpsr = xpsr_read(env);
2911     uint32_t lr;
2912     uint32_t addr;
2913
2914     arm_log_exception(cs->exception_index);
2915
2916     lr = 0xfffffff1;
2917     if (env->v7m.current_sp)
2918         lr |= 4;
2919     if (env->v7m.exception == 0)
2920         lr |= 8;
2921
2922     /* For exceptions we just mark as pending on the NVIC, and let that
2923        handle it.  */
2924     /* TODO: Need to escalate if the current priority is higher than the
2925        one we're raising.  */
2926     switch (cs->exception_index) {
2927     case EXCP_UDEF:
2928         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE);
2929         return;
2930     case EXCP_SWI:
2931         /* The PC already points to the next instruction.  */
2932         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC);
2933         return;
2934     case EXCP_PREFETCH_ABORT:
2935     case EXCP_DATA_ABORT:
2936         /* TODO: if we implemented the MPU registers, this is where we
2937          * should set the MMFAR, etc from exception.fsr and exception.vaddress.
2938          */
2939         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM);
2940         return;
2941     case EXCP_BKPT:
2942         if (semihosting_enabled) {
2943             int nr;
2944             nr = arm_lduw_code(env, env->regs[15], env->bswap_code) & 0xff;
2945             if (nr == 0xab) {
2946                 env->regs[15] += 2;
2947                 env->regs[0] = do_arm_semihosting(env);
2948                 qemu_log_mask(CPU_LOG_INT, "...handled as semihosting call\n");
2949                 return;
2950             }
2951         }
2952         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG);
2953         return;
2954     case EXCP_IRQ:
2955         env->v7m.exception = armv7m_nvic_acknowledge_irq(env->nvic);
2956         break;
2957     case EXCP_EXCEPTION_EXIT:
2958         do_v7m_exception_exit(env);
2959         return;
2960     default:
2961         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
2962         return; /* Never happens.  Keep compiler happy.  */
2963     }
2964
2965     /* Align stack pointer.  */
2966     /* ??? Should only do this if Configuration Control Register
2967        STACKALIGN bit is set.  */
2968     if (env->regs[13] & 4) {
2969         env->regs[13] -= 4;
2970         xpsr |= 0x200;
2971     }
2972     /* Switch to the handler mode.  */
2973     v7m_push(env, xpsr);
2974     v7m_push(env, env->regs[15]);
2975     v7m_push(env, env->regs[14]);
2976     v7m_push(env, env->regs[12]);
2977     v7m_push(env, env->regs[3]);
2978     v7m_push(env, env->regs[2]);
2979     v7m_push(env, env->regs[1]);
2980     v7m_push(env, env->regs[0]);
2981     switch_v7m_sp(env, 0);
2982     /* Clear IT bits */
2983     env->condexec_bits = 0;
2984     env->regs[14] = lr;
2985     addr = ldl_phys(cs->as, env->v7m.vecbase + env->v7m.exception * 4);
2986     env->regs[15] = addr & 0xfffffffe;
2987     env->thumb = addr & 1;
2988 }
2989
2990 /* Handle a CPU exception.  */
2991 void arm_cpu_do_interrupt(CPUState *cs)
2992 {
2993     ARMCPU *cpu = ARM_CPU(cs);
2994     CPUARMState *env = &cpu->env;
2995     uint32_t addr;
2996     uint32_t mask;
2997     int new_mode;
2998     uint32_t offset;
2999
3000     assert(!IS_M(env));
3001
3002     arm_log_exception(cs->exception_index);
3003
3004     /* TODO: Vectored interrupt controller.  */
3005     switch (cs->exception_index) {
3006     case EXCP_UDEF:
3007         new_mode = ARM_CPU_MODE_UND;
3008         addr = 0x04;
3009         mask = CPSR_I;
3010         if (env->thumb)
3011             offset = 2;
3012         else
3013             offset = 4;
3014         break;
3015     case EXCP_SWI:
3016         if (semihosting_enabled) {
3017             /* Check for semihosting interrupt.  */
3018             if (env->thumb) {
3019                 mask = arm_lduw_code(env, env->regs[15] - 2, env->bswap_code)
3020                     & 0xff;
3021             } else {
3022                 mask = arm_ldl_code(env, env->regs[15] - 4, env->bswap_code)
3023                     & 0xffffff;
3024             }
3025             /* Only intercept calls from privileged modes, to provide some
3026                semblance of security.  */
3027             if (((mask == 0x123456 && !env->thumb)
3028                     || (mask == 0xab && env->thumb))
3029                   && (env->uncached_cpsr & CPSR_M) != ARM_CPU_MODE_USR) {
3030                 env->regs[0] = do_arm_semihosting(env);
3031                 qemu_log_mask(CPU_LOG_INT, "...handled as semihosting call\n");
3032                 return;
3033             }
3034         }
3035         new_mode = ARM_CPU_MODE_SVC;
3036         addr = 0x08;
3037         mask = CPSR_I;
3038         /* The PC already points to the next instruction.  */
3039         offset = 0;
3040         break;
3041     case EXCP_BKPT:
3042         /* See if this is a semihosting syscall.  */
3043         if (env->thumb && semihosting_enabled) {
3044             mask = arm_lduw_code(env, env->regs[15], env->bswap_code) & 0xff;
3045             if (mask == 0xab
3046                   && (env->uncached_cpsr & CPSR_M) != ARM_CPU_MODE_USR) {
3047                 env->regs[15] += 2;
3048                 env->regs[0] = do_arm_semihosting(env);
3049                 qemu_log_mask(CPU_LOG_INT, "...handled as semihosting call\n");
3050                 return;
3051             }
3052         }
3053         env->exception.fsr = 2;
3054         /* Fall through to prefetch abort.  */
3055     case EXCP_PREFETCH_ABORT:
3056         env->cp15.c5_insn = env->exception.fsr;
3057         env->cp15.c6_insn = env->exception.vaddress;
3058         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
3059                       env->cp15.c5_insn, env->cp15.c6_insn);
3060         new_mode = ARM_CPU_MODE_ABT;
3061         addr = 0x0c;
3062         mask = CPSR_A | CPSR_I;
3063         offset = 4;
3064         break;
3065     case EXCP_DATA_ABORT:
3066         env->cp15.c5_data = env->exception.fsr;
3067         env->cp15.c6_data = env->exception.vaddress;
3068         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
3069                       env->cp15.c5_data, env->cp15.c6_data);
3070         new_mode = ARM_CPU_MODE_ABT;
3071         addr = 0x10;
3072         mask = CPSR_A | CPSR_I;
3073         offset = 8;
3074         break;
3075     case EXCP_IRQ:
3076         new_mode = ARM_CPU_MODE_IRQ;
3077         addr = 0x18;
3078         /* Disable IRQ and imprecise data aborts.  */
3079         mask = CPSR_A | CPSR_I;
3080         offset = 4;
3081         break;
3082     case EXCP_FIQ:
3083         new_mode = ARM_CPU_MODE_FIQ;
3084         addr = 0x1c;
3085         /* Disable FIQ, IRQ and imprecise data aborts.  */
3086         mask = CPSR_A | CPSR_I | CPSR_F;
3087         offset = 4;
3088         break;
3089     default:
3090         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
3091         return; /* Never happens.  Keep compiler happy.  */
3092     }
3093     /* High vectors.  */
3094     if (env->cp15.c1_sys & SCTLR_V) {
3095         /* when enabled, base address cannot be remapped.  */
3096         addr += 0xffff0000;
3097     } else {
3098         /* ARM v7 architectures provide a vector base address register to remap
3099          * the interrupt vector table.
3100          * This register is only followed in non-monitor mode, and has a secure
3101          * and un-secure copy. Since the cpu is always in a un-secure operation
3102          * and is never in monitor mode this feature is always active.
3103          * Note: only bits 31:5 are valid.
3104          */
3105         addr += env->cp15.c12_vbar;
3106     }
3107     switch_mode (env, new_mode);
3108     env->spsr = cpsr_read(env);
3109     /* Clear IT bits.  */
3110     env->condexec_bits = 0;
3111     /* Switch to the new mode, and to the correct instruction set.  */
3112     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
3113     env->daif |= mask;
3114     /* this is a lie, as the was no c1_sys on V4T/V5, but who cares
3115      * and we should just guard the thumb mode on V4 */
3116     if (arm_feature(env, ARM_FEATURE_V4T)) {
3117         env->thumb = (env->cp15.c1_sys & SCTLR_TE) != 0;
3118     }
3119     env->regs[14] = env->regs[15] + offset;
3120     env->regs[15] = addr;
3121     cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
3122 }
3123
3124 /* Check section/page access permissions.
3125    Returns the page protection flags, or zero if the access is not
3126    permitted.  */
3127 static inline int check_ap(CPUARMState *env, int ap, int domain_prot,
3128                            int access_type, int is_user)
3129 {
3130   int prot_ro;
3131
3132   if (domain_prot == 3) {
3133     return PAGE_READ | PAGE_WRITE;
3134   }
3135
3136   if (access_type == 1)
3137       prot_ro = 0;
3138   else
3139       prot_ro = PAGE_READ;
3140
3141   switch (ap) {
3142   case 0:
3143       if (arm_feature(env, ARM_FEATURE_V7)) {
3144           return 0;
3145       }
3146       if (access_type == 1)
3147           return 0;
3148       switch (env->cp15.c1_sys & (SCTLR_S | SCTLR_R)) {
3149       case SCTLR_S:
3150           return is_user ? 0 : PAGE_READ;
3151       case SCTLR_R:
3152           return PAGE_READ;
3153       default:
3154           return 0;
3155       }
3156   case 1:
3157       return is_user ? 0 : PAGE_READ | PAGE_WRITE;
3158   case 2:
3159       if (is_user)
3160           return prot_ro;
3161       else
3162           return PAGE_READ | PAGE_WRITE;
3163   case 3:
3164       return PAGE_READ | PAGE_WRITE;
3165   case 4: /* Reserved.  */
3166       return 0;
3167   case 5:
3168       return is_user ? 0 : prot_ro;
3169   case 6:
3170       return prot_ro;
3171   case 7:
3172       if (!arm_feature (env, ARM_FEATURE_V6K))
3173           return 0;
3174       return prot_ro;
3175   default:
3176       abort();
3177   }
3178 }
3179
3180 static uint32_t get_level1_table_address(CPUARMState *env, uint32_t address)
3181 {
3182     uint32_t table;
3183
3184     if (address & env->cp15.c2_mask)
3185         table = env->cp15.ttbr1_el1 & 0xffffc000;
3186     else
3187         table = env->cp15.ttbr0_el1 & env->cp15.c2_base_mask;
3188
3189     table |= (address >> 18) & 0x3ffc;
3190     return table;
3191 }
3192
3193 static int get_phys_addr_v5(CPUARMState *env, uint32_t address, int access_type,
3194                             int is_user, hwaddr *phys_ptr,
3195                             int *prot, target_ulong *page_size)
3196 {
3197     CPUState *cs = CPU(arm_env_get_cpu(env));
3198     int code;
3199     uint32_t table;
3200     uint32_t desc;
3201     int type;
3202     int ap;
3203     int domain;
3204     int domain_prot;
3205     hwaddr phys_addr;
3206
3207     /* Pagetable walk.  */
3208     /* Lookup l1 descriptor.  */
3209     table = get_level1_table_address(env, address);
3210     desc = ldl_phys(cs->as, table);
3211     type = (desc & 3);
3212     domain = (desc >> 5) & 0x0f;
3213     domain_prot = (env->cp15.c3 >> (domain * 2)) & 3;
3214     if (type == 0) {
3215         /* Section translation fault.  */
3216         code = 5;
3217         goto do_fault;
3218     }
3219     if (domain_prot == 0 || domain_prot == 2) {
3220         if (type == 2)
3221             code = 9; /* Section domain fault.  */
3222         else
3223             code = 11; /* Page domain fault.  */
3224         goto do_fault;
3225     }
3226     if (type == 2) {
3227         /* 1Mb section.  */
3228         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
3229         ap = (desc >> 10) & 3;
3230         code = 13;
3231         *page_size = 1024 * 1024;
3232     } else {
3233         /* Lookup l2 entry.  */
3234         if (type == 1) {
3235             /* Coarse pagetable.  */
3236             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
3237         } else {
3238             /* Fine pagetable.  */
3239             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
3240         }
3241         desc = ldl_phys(cs->as, table);
3242         switch (desc & 3) {
3243         case 0: /* Page translation fault.  */
3244             code = 7;
3245             goto do_fault;
3246         case 1: /* 64k page.  */
3247             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
3248             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
3249             *page_size = 0x10000;
3250             break;
3251         case 2: /* 4k page.  */
3252             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
3253             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
3254             *page_size = 0x1000;
3255             break;
3256         case 3: /* 1k page.  */
3257             if (type == 1) {
3258                 if (arm_feature(env, ARM_FEATURE_XSCALE)) {
3259                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
3260                 } else {
3261                     /* Page translation fault.  */
3262                     code = 7;
3263                     goto do_fault;
3264                 }
3265             } else {
3266                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
3267             }
3268             ap = (desc >> 4) & 3;
3269             *page_size = 0x400;
3270             break;
3271         default:
3272             /* Never happens, but compiler isn't smart enough to tell.  */
3273             abort();
3274         }
3275         code = 15;
3276     }
3277     *prot = check_ap(env, ap, domain_prot, access_type, is_user);
3278     if (!*prot) {
3279         /* Access permission fault.  */
3280         goto do_fault;
3281     }
3282     *prot |= PAGE_EXEC;
3283     *phys_ptr = phys_addr;
3284     return 0;
3285 do_fault:
3286     return code | (domain << 4);
3287 }
3288
3289 static int get_phys_addr_v6(CPUARMState *env, uint32_t address, int access_type,
3290                             int is_user, hwaddr *phys_ptr,
3291                             int *prot, target_ulong *page_size)
3292 {
3293     CPUState *cs = CPU(arm_env_get_cpu(env));
3294     int code;
3295     uint32_t table;
3296     uint32_t desc;
3297     uint32_t xn;
3298     uint32_t pxn = 0;
3299     int type;
3300     int ap;
3301     int domain = 0;
3302     int domain_prot;
3303     hwaddr phys_addr;
3304
3305     /* Pagetable walk.  */
3306     /* Lookup l1 descriptor.  */
3307     table = get_level1_table_address(env, address);
3308     desc = ldl_phys(cs->as, table);
3309     type = (desc & 3);
3310     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
3311         /* Section translation fault, or attempt to use the encoding
3312          * which is Reserved on implementations without PXN.
3313          */
3314         code = 5;
3315         goto do_fault;
3316     }
3317     if ((type == 1) || !(desc & (1 << 18))) {
3318         /* Page or Section.  */
3319         domain = (desc >> 5) & 0x0f;
3320     }
3321     domain_prot = (env->cp15.c3 >> (domain * 2)) & 3;
3322     if (domain_prot == 0 || domain_prot == 2) {
3323         if (type != 1) {
3324             code = 9; /* Section domain fault.  */
3325         } else {
3326             code = 11; /* Page domain fault.  */
3327         }
3328         goto do_fault;
3329     }
3330     if (type != 1) {
3331         if (desc & (1 << 18)) {
3332             /* Supersection.  */
3333             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
3334             *page_size = 0x1000000;
3335         } else {
3336             /* Section.  */
3337             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
3338             *page_size = 0x100000;
3339         }
3340         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
3341         xn = desc & (1 << 4);
3342         pxn = desc & 1;
3343         code = 13;
3344     } else {
3345         if (arm_feature(env, ARM_FEATURE_PXN)) {
3346             pxn = (desc >> 2) & 1;
3347         }
3348         /* Lookup l2 entry.  */
3349         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
3350         desc = ldl_phys(cs->as, table);
3351         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
3352         switch (desc & 3) {
3353         case 0: /* Page translation fault.  */
3354             code = 7;
3355             goto do_fault;
3356         case 1: /* 64k page.  */
3357             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
3358             xn = desc & (1 << 15);
3359             *page_size = 0x10000;
3360             break;
3361         case 2: case 3: /* 4k page.  */
3362             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
3363             xn = desc & 1;
3364             *page_size = 0x1000;
3365             break;
3366         default:
3367             /* Never happens, but compiler isn't smart enough to tell.  */
3368             abort();
3369         }
3370         code = 15;
3371     }
3372     if (domain_prot == 3) {
3373         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
3374     } else {
3375         if (pxn && !is_user) {
3376             xn = 1;
3377         }
3378         if (xn && access_type == 2)
3379             goto do_fault;
3380
3381         /* The simplified model uses AP[0] as an access control bit.  */
3382         if ((env->cp15.c1_sys & SCTLR_AFE) && (ap & 1) == 0) {
3383             /* Access flag fault.  */
3384             code = (code == 15) ? 6 : 3;
3385             goto do_fault;
3386         }
3387         *prot = check_ap(env, ap, domain_prot, access_type, is_user);
3388         if (!*prot) {
3389             /* Access permission fault.  */
3390             goto do_fault;
3391         }
3392         if (!xn) {
3393             *prot |= PAGE_EXEC;
3394         }
3395     }
3396     *phys_ptr = phys_addr;
3397     return 0;
3398 do_fault:
3399     return code | (domain << 4);
3400 }
3401
3402 /* Fault type for long-descriptor MMU fault reporting; this corresponds
3403  * to bits [5..2] in the STATUS field in long-format DFSR/IFSR.
3404  */
3405 typedef enum {
3406     translation_fault = 1,
3407     access_fault = 2,
3408     permission_fault = 3,
3409 } MMUFaultType;
3410
3411 static int get_phys_addr_lpae(CPUARMState *env, target_ulong address,
3412                               int access_type, int is_user,
3413                               hwaddr *phys_ptr, int *prot,
3414                               target_ulong *page_size_ptr)
3415 {
3416     CPUState *cs = CPU(arm_env_get_cpu(env));
3417     /* Read an LPAE long-descriptor translation table. */
3418     MMUFaultType fault_type = translation_fault;
3419     uint32_t level = 1;
3420     uint32_t epd;
3421     int32_t tsz;
3422     uint32_t tg;
3423     uint64_t ttbr;
3424     int ttbr_select;
3425     hwaddr descaddr, descmask;
3426     uint32_t tableattrs;
3427     target_ulong page_size;
3428     uint32_t attrs;
3429     int32_t granule_sz = 9;
3430     int32_t va_size = 32;
3431     int32_t tbi = 0;
3432
3433     if (arm_el_is_aa64(env, 1)) {
3434         va_size = 64;
3435         if (extract64(address, 55, 1))
3436             tbi = extract64(env->cp15.c2_control, 38, 1);
3437         else
3438             tbi = extract64(env->cp15.c2_control, 37, 1);
3439         tbi *= 8;
3440     }
3441
3442     /* Determine whether this address is in the region controlled by
3443      * TTBR0 or TTBR1 (or if it is in neither region and should fault).
3444      * This is a Non-secure PL0/1 stage 1 translation, so controlled by
3445      * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:
3446      */
3447     uint32_t t0sz = extract32(env->cp15.c2_control, 0, 6);
3448     if (arm_el_is_aa64(env, 1)) {
3449         t0sz = MIN(t0sz, 39);
3450         t0sz = MAX(t0sz, 16);
3451     }
3452     uint32_t t1sz = extract32(env->cp15.c2_control, 16, 6);
3453     if (arm_el_is_aa64(env, 1)) {
3454         t1sz = MIN(t1sz, 39);
3455         t1sz = MAX(t1sz, 16);
3456     }
3457     if (t0sz && !extract64(address, va_size - t0sz, t0sz - tbi)) {
3458         /* there is a ttbr0 region and we are in it (high bits all zero) */
3459         ttbr_select = 0;
3460     } else if (t1sz && !extract64(~address, va_size - t1sz, t1sz - tbi)) {
3461         /* there is a ttbr1 region and we are in it (high bits all one) */
3462         ttbr_select = 1;
3463     } else if (!t0sz) {
3464         /* ttbr0 region is "everything not in the ttbr1 region" */
3465         ttbr_select = 0;
3466     } else if (!t1sz) {
3467         /* ttbr1 region is "everything not in the ttbr0 region" */
3468         ttbr_select = 1;
3469     } else {
3470         /* in the gap between the two regions, this is a Translation fault */
3471         fault_type = translation_fault;
3472         goto do_fault;
3473     }
3474
3475     /* Note that QEMU ignores shareability and cacheability attributes,
3476      * so we don't need to do anything with the SH, ORGN, IRGN fields
3477      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
3478      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
3479      * implement any ASID-like capability so we can ignore it (instead
3480      * we will always flush the TLB any time the ASID is changed).
3481      */
3482     if (ttbr_select == 0) {
3483         ttbr = env->cp15.ttbr0_el1;
3484         epd = extract32(env->cp15.c2_control, 7, 1);
3485         tsz = t0sz;
3486
3487         tg = extract32(env->cp15.c2_control, 14, 2);
3488         if (tg == 1) { /* 64KB pages */
3489             granule_sz = 13;
3490         }
3491         if (tg == 2) { /* 16KB pages */
3492             granule_sz = 11;
3493         }
3494     } else {
3495         ttbr = env->cp15.ttbr1_el1;
3496         epd = extract32(env->cp15.c2_control, 23, 1);
3497         tsz = t1sz;
3498
3499         tg = extract32(env->cp15.c2_control, 30, 2);
3500         if (tg == 3)  { /* 64KB pages */
3501             granule_sz = 13;
3502         }
3503         if (tg == 1) { /* 16KB pages */
3504             granule_sz = 11;
3505         }
3506     }
3507
3508     if (epd) {
3509         /* Translation table walk disabled => Translation fault on TLB miss */
3510         goto do_fault;
3511     }
3512
3513     /* The starting level depends on the virtual address size which can be
3514      * up to 48-bits and the translation granule size.
3515      */
3516     if ((va_size - tsz) > (granule_sz * 4 + 3)) {
3517         level = 0;
3518     } else if ((va_size - tsz) > (granule_sz * 3 + 3)) {
3519         level = 1;
3520     } else {
3521         level = 2;
3522     }
3523
3524     /* Clear the vaddr bits which aren't part of the within-region address,
3525      * so that we don't have to special case things when calculating the
3526      * first descriptor address.
3527      */
3528     if (tsz) {
3529         address &= (1ULL << (va_size - tsz)) - 1;
3530     }
3531
3532     descmask = (1ULL << (granule_sz + 3)) - 1;
3533
3534     /* Now we can extract the actual base address from the TTBR */
3535     descaddr = extract64(ttbr, 0, 48);
3536     descaddr &= ~((1ULL << (va_size - tsz - (granule_sz * (4 - level)))) - 1);
3537
3538     tableattrs = 0;
3539     for (;;) {
3540         uint64_t descriptor;
3541
3542         descaddr |= (address >> (granule_sz * (4 - level))) & descmask;
3543         descaddr &= ~7ULL;
3544         descriptor = ldq_phys(cs->as, descaddr);
3545         if (!(descriptor & 1) ||
3546             (!(descriptor & 2) && (level == 3))) {
3547             /* Invalid, or the Reserved level 3 encoding */
3548             goto do_fault;
3549         }
3550         descaddr = descriptor & 0xfffffff000ULL;
3551
3552         if ((descriptor & 2) && (level < 3)) {
3553             /* Table entry. The top five bits are attributes which  may
3554              * propagate down through lower levels of the table (and
3555              * which are all arranged so that 0 means "no effect", so
3556              * we can gather them up by ORing in the bits at each level).
3557              */
3558             tableattrs |= extract64(descriptor, 59, 5);
3559             level++;
3560             continue;
3561         }
3562         /* Block entry at level 1 or 2, or page entry at level 3.
3563          * These are basically the same thing, although the number
3564          * of bits we pull in from the vaddr varies.
3565          */
3566         page_size = (1 << ((granule_sz * (4 - level)) + 3));
3567         descaddr |= (address & (page_size - 1));
3568         /* Extract attributes from the descriptor and merge with table attrs */
3569         if (arm_feature(env, ARM_FEATURE_V8)) {
3570             attrs = extract64(descriptor, 2, 10)
3571                 | (extract64(descriptor, 53, 11) << 10);
3572         } else {
3573             attrs = extract64(descriptor, 2, 10)
3574                 | (extract64(descriptor, 52, 12) << 10);
3575         }
3576         attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */
3577         attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */
3578         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
3579          * means "force PL1 access only", which means forcing AP[1] to 0.
3580          */
3581         if (extract32(tableattrs, 2, 1)) {
3582             attrs &= ~(1 << 4);
3583         }
3584         /* Since we're always in the Non-secure state, NSTable is ignored. */
3585         break;
3586     }
3587     /* Here descaddr is the final physical address, and attributes
3588      * are all in attrs.
3589      */
3590     fault_type = access_fault;
3591     if ((attrs & (1 << 8)) == 0) {
3592         /* Access flag */
3593         goto do_fault;
3594     }
3595     fault_type = permission_fault;
3596     if (is_user && !(attrs & (1 << 4))) {
3597         /* Unprivileged access not enabled */
3598         goto do_fault;
3599     }
3600     *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
3601     if (attrs & (1 << 12) || (!is_user && (attrs & (1 << 11)))) {
3602         /* XN or PXN */
3603         if (access_type == 2) {
3604             goto do_fault;
3605         }
3606         *prot &= ~PAGE_EXEC;
3607     }
3608     if (attrs & (1 << 5)) {
3609         /* Write access forbidden */
3610         if (access_type == 1) {
3611             goto do_fault;
3612         }
3613         *prot &= ~PAGE_WRITE;
3614     }
3615
3616     *phys_ptr = descaddr;
3617     *page_size_ptr = page_size;
3618     return 0;
3619
3620 do_fault:
3621     /* Long-descriptor format IFSR/DFSR value */
3622     return (1 << 9) | (fault_type << 2) | level;
3623 }
3624
3625 static int get_phys_addr_mpu(CPUARMState *env, uint32_t address,
3626                              int access_type, int is_user,
3627                              hwaddr *phys_ptr, int *prot)
3628 {
3629     int n;
3630     uint32_t mask;
3631     uint32_t base;
3632
3633     *phys_ptr = address;
3634     for (n = 7; n >= 0; n--) {
3635         base = env->cp15.c6_region[n];
3636         if ((base & 1) == 0)
3637             continue;
3638         mask = 1 << ((base >> 1) & 0x1f);
3639         /* Keep this shift separate from the above to avoid an
3640            (undefined) << 32.  */
3641         mask = (mask << 1) - 1;
3642         if (((base ^ address) & ~mask) == 0)
3643             break;
3644     }
3645     if (n < 0)
3646         return 2;
3647
3648     if (access_type == 2) {
3649         mask = env->cp15.c5_insn;
3650     } else {
3651         mask = env->cp15.c5_data;
3652     }
3653     mask = (mask >> (n * 4)) & 0xf;
3654     switch (mask) {
3655     case 0:
3656         return 1;
3657     case 1:
3658         if (is_user)
3659           return 1;
3660         *prot = PAGE_READ | PAGE_WRITE;
3661         break;
3662     case 2:
3663         *prot = PAGE_READ;
3664         if (!is_user)
3665             *prot |= PAGE_WRITE;
3666         break;
3667     case 3:
3668         *prot = PAGE_READ | PAGE_WRITE;
3669         break;
3670     case 5:
3671         if (is_user)
3672             return 1;
3673         *prot = PAGE_READ;
3674         break;
3675     case 6:
3676         *prot = PAGE_READ;
3677         break;
3678     default:
3679         /* Bad permission.  */
3680         return 1;
3681     }
3682     *prot |= PAGE_EXEC;
3683     return 0;
3684 }
3685
3686 /* get_phys_addr - get the physical address for this virtual address
3687  *
3688  * Find the physical address corresponding to the given virtual address,
3689  * by doing a translation table walk on MMU based systems or using the
3690  * MPU state on MPU based systems.
3691  *
3692  * Returns 0 if the translation was successful. Otherwise, phys_ptr,
3693  * prot and page_size are not filled in, and the return value provides
3694  * information on why the translation aborted, in the format of a
3695  * DFSR/IFSR fault register, with the following caveats:
3696  *  * we honour the short vs long DFSR format differences.
3697  *  * the WnR bit is never set (the caller must do this).
3698  *  * for MPU based systems we don't bother to return a full FSR format
3699  *    value.
3700  *
3701  * @env: CPUARMState
3702  * @address: virtual address to get physical address for
3703  * @access_type: 0 for read, 1 for write, 2 for execute
3704  * @is_user: 0 for privileged access, 1 for user
3705  * @phys_ptr: set to the physical address corresponding to the virtual address
3706  * @prot: set to the permissions for the page containing phys_ptr
3707  * @page_size: set to the size of the page containing phys_ptr
3708  */
3709 static inline int get_phys_addr(CPUARMState *env, target_ulong address,
3710                                 int access_type, int is_user,
3711                                 hwaddr *phys_ptr, int *prot,
3712                                 target_ulong *page_size)
3713 {
3714     /* Fast Context Switch Extension.  */
3715     if (address < 0x02000000)
3716         address += env->cp15.c13_fcse;
3717
3718     if ((env->cp15.c1_sys & SCTLR_M) == 0) {
3719         /* MMU/MPU disabled.  */
3720         *phys_ptr = address;
3721         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
3722         *page_size = TARGET_PAGE_SIZE;
3723         return 0;
3724     } else if (arm_feature(env, ARM_FEATURE_MPU)) {
3725         *page_size = TARGET_PAGE_SIZE;
3726         return get_phys_addr_mpu(env, address, access_type, is_user, phys_ptr,
3727                                  prot);
3728     } else if (extended_addresses_enabled(env)) {
3729         return get_phys_addr_lpae(env, address, access_type, is_user, phys_ptr,
3730                                   prot, page_size);
3731     } else if (env->cp15.c1_sys & SCTLR_XP) {
3732         return get_phys_addr_v6(env, address, access_type, is_user, phys_ptr,
3733                                 prot, page_size);
3734     } else {
3735         return get_phys_addr_v5(env, address, access_type, is_user, phys_ptr,
3736                                 prot, page_size);
3737     }
3738 }
3739
3740 int arm_cpu_handle_mmu_fault(CPUState *cs, vaddr address,
3741                              int access_type, int mmu_idx)
3742 {
3743     ARMCPU *cpu = ARM_CPU(cs);
3744     CPUARMState *env = &cpu->env;
3745     hwaddr phys_addr;
3746     target_ulong page_size;
3747     int prot;
3748     int ret, is_user;
3749     uint32_t syn;
3750     bool same_el = (arm_current_pl(env) != 0);
3751
3752     is_user = mmu_idx == MMU_USER_IDX;
3753     ret = get_phys_addr(env, address, access_type, is_user, &phys_addr, &prot,
3754                         &page_size);
3755     if (ret == 0) {
3756         /* Map a single [sub]page.  */
3757         phys_addr &= ~(hwaddr)0x3ff;
3758         address &= ~(target_ulong)0x3ff;
3759         tlb_set_page(cs, address, phys_addr, prot, mmu_idx, page_size);
3760         return 0;
3761     }
3762
3763     /* AArch64 syndrome does not have an LPAE bit */
3764     syn = ret & ~(1 << 9);
3765
3766     /* For insn and data aborts we assume there is no instruction syndrome
3767      * information; this is always true for exceptions reported to EL1.
3768      */
3769     if (access_type == 2) {
3770         syn = syn_insn_abort(same_el, 0, 0, syn);
3771         cs->exception_index = EXCP_PREFETCH_ABORT;
3772     } else {
3773         syn = syn_data_abort(same_el, 0, 0, 0, access_type == 1, syn);
3774         if (access_type == 1 && arm_feature(env, ARM_FEATURE_V6)) {
3775             ret |= (1 << 11);
3776         }
3777         cs->exception_index = EXCP_DATA_ABORT;
3778     }
3779
3780     env->exception.syndrome = syn;
3781     env->exception.vaddress = address;
3782     env->exception.fsr = ret;
3783     return 1;
3784 }
3785
3786 hwaddr arm_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
3787 {
3788     ARMCPU *cpu = ARM_CPU(cs);
3789     hwaddr phys_addr;
3790     target_ulong page_size;
3791     int prot;
3792     int ret;
3793
3794     ret = get_phys_addr(&cpu->env, addr, 0, 0, &phys_addr, &prot, &page_size);
3795
3796     if (ret != 0) {
3797         return -1;
3798     }
3799
3800     return phys_addr;
3801 }
3802
3803 void HELPER(set_r13_banked)(CPUARMState *env, uint32_t mode, uint32_t val)
3804 {
3805     if ((env->uncached_cpsr & CPSR_M) == mode) {
3806         env->regs[13] = val;
3807     } else {
3808         env->banked_r13[bank_number(mode)] = val;
3809     }
3810 }
3811
3812 uint32_t HELPER(get_r13_banked)(CPUARMState *env, uint32_t mode)
3813 {
3814     if ((env->uncached_cpsr & CPSR_M) == mode) {
3815         return env->regs[13];
3816     } else {
3817         return env->banked_r13[bank_number(mode)];
3818     }
3819 }
3820
3821 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
3822 {
3823     ARMCPU *cpu = arm_env_get_cpu(env);
3824
3825     switch (reg) {
3826     case 0: /* APSR */
3827         return xpsr_read(env) & 0xf8000000;
3828     case 1: /* IAPSR */
3829         return xpsr_read(env) & 0xf80001ff;
3830     case 2: /* EAPSR */
3831         return xpsr_read(env) & 0xff00fc00;
3832     case 3: /* xPSR */
3833         return xpsr_read(env) & 0xff00fdff;
3834     case 5: /* IPSR */
3835         return xpsr_read(env) & 0x000001ff;
3836     case 6: /* EPSR */
3837         return xpsr_read(env) & 0x0700fc00;
3838     case 7: /* IEPSR */
3839         return xpsr_read(env) & 0x0700edff;
3840     case 8: /* MSP */
3841         return env->v7m.current_sp ? env->v7m.other_sp : env->regs[13];
3842     case 9: /* PSP */
3843         return env->v7m.current_sp ? env->regs[13] : env->v7m.other_sp;
3844     case 16: /* PRIMASK */
3845         return (env->daif & PSTATE_I) != 0;
3846     case 17: /* BASEPRI */
3847     case 18: /* BASEPRI_MAX */
3848         return env->v7m.basepri;
3849     case 19: /* FAULTMASK */
3850         return (env->daif & PSTATE_F) != 0;
3851     case 20: /* CONTROL */
3852         return env->v7m.control;
3853     default:
3854         /* ??? For debugging only.  */
3855         cpu_abort(CPU(cpu), "Unimplemented system register read (%d)\n", reg);
3856         return 0;
3857     }
3858 }
3859
3860 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
3861 {
3862     ARMCPU *cpu = arm_env_get_cpu(env);
3863
3864     switch (reg) {
3865     case 0: /* APSR */
3866         xpsr_write(env, val, 0xf8000000);
3867         break;
3868     case 1: /* IAPSR */
3869         xpsr_write(env, val, 0xf8000000);
3870         break;
3871     case 2: /* EAPSR */
3872         xpsr_write(env, val, 0xfe00fc00);
3873         break;
3874     case 3: /* xPSR */
3875         xpsr_write(env, val, 0xfe00fc00);
3876         break;
3877     case 5: /* IPSR */
3878         /* IPSR bits are readonly.  */
3879         break;
3880     case 6: /* EPSR */
3881         xpsr_write(env, val, 0x0600fc00);
3882         break;
3883     case 7: /* IEPSR */
3884         xpsr_write(env, val, 0x0600fc00);
3885         break;
3886     case 8: /* MSP */
3887         if (env->v7m.current_sp)
3888             env->v7m.other_sp = val;
3889         else
3890             env->regs[13] = val;
3891         break;
3892     case 9: /* PSP */
3893         if (env->v7m.current_sp)
3894             env->regs[13] = val;
3895         else
3896             env->v7m.other_sp = val;
3897         break;
3898     case 16: /* PRIMASK */
3899         if (val & 1) {
3900             env->daif |= PSTATE_I;
3901         } else {
3902             env->daif &= ~PSTATE_I;
3903         }
3904         break;
3905     case 17: /* BASEPRI */
3906         env->v7m.basepri = val & 0xff;
3907         break;
3908     case 18: /* BASEPRI_MAX */
3909         val &= 0xff;
3910         if (val != 0 && (val < env->v7m.basepri || env->v7m.basepri == 0))
3911             env->v7m.basepri = val;
3912         break;
3913     case 19: /* FAULTMASK */
3914         if (val & 1) {
3915             env->daif |= PSTATE_F;
3916         } else {
3917             env->daif &= ~PSTATE_F;
3918         }
3919         break;
3920     case 20: /* CONTROL */
3921         env->v7m.control = val & 3;
3922         switch_v7m_sp(env, (val & 2) != 0);
3923         break;
3924     default:
3925         /* ??? For debugging only.  */
3926         cpu_abort(CPU(cpu), "Unimplemented system register write (%d)\n", reg);
3927         return;
3928     }
3929 }
3930
3931 #endif
3932
3933 /* Note that signed overflow is undefined in C.  The following routines are
3934    careful to use unsigned types where modulo arithmetic is required.
3935    Failure to do so _will_ break on newer gcc.  */
3936
3937 /* Signed saturating arithmetic.  */
3938
3939 /* Perform 16-bit signed saturating addition.  */
3940 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
3941 {
3942     uint16_t res;
3943
3944     res = a + b;
3945     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
3946         if (a & 0x8000)
3947             res = 0x8000;
3948         else
3949             res = 0x7fff;
3950     }
3951     return res;
3952 }
3953
3954 /* Perform 8-bit signed saturating addition.  */
3955 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
3956 {
3957     uint8_t res;
3958
3959     res = a + b;
3960     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
3961         if (a & 0x80)
3962             res = 0x80;
3963         else
3964             res = 0x7f;
3965     }
3966     return res;
3967 }
3968
3969 /* Perform 16-bit signed saturating subtraction.  */
3970 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
3971 {
3972     uint16_t res;
3973
3974     res = a - b;
3975     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
3976         if (a & 0x8000)
3977             res = 0x8000;
3978         else
3979             res = 0x7fff;
3980     }
3981     return res;
3982 }
3983
3984 /* Perform 8-bit signed saturating subtraction.  */
3985 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
3986 {
3987     uint8_t res;
3988
3989     res = a - b;
3990     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
3991         if (a & 0x80)
3992             res = 0x80;
3993         else
3994             res = 0x7f;
3995     }
3996     return res;
3997 }
3998
3999 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
4000 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
4001 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
4002 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
4003 #define PFX q
4004
4005 #include "op_addsub.h"
4006
4007 /* Unsigned saturating arithmetic.  */
4008 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
4009 {
4010     uint16_t res;
4011     res = a + b;
4012     if (res < a)
4013         res = 0xffff;
4014     return res;
4015 }
4016
4017 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
4018 {
4019     if (a > b)
4020         return a - b;
4021     else
4022         return 0;
4023 }
4024
4025 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
4026 {
4027     uint8_t res;
4028     res = a + b;
4029     if (res < a)
4030         res = 0xff;
4031     return res;
4032 }
4033
4034 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
4035 {
4036     if (a > b)
4037         return a - b;
4038     else
4039         return 0;
4040 }
4041
4042 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
4043 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
4044 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
4045 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
4046 #define PFX uq
4047
4048 #include "op_addsub.h"
4049
4050 /* Signed modulo arithmetic.  */
4051 #define SARITH16(a, b, n, op) do { \
4052     int32_t sum; \
4053     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
4054     RESULT(sum, n, 16); \
4055     if (sum >= 0) \
4056         ge |= 3 << (n * 2); \
4057     } while(0)
4058
4059 #define SARITH8(a, b, n, op) do { \
4060     int32_t sum; \
4061     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
4062     RESULT(sum, n, 8); \
4063     if (sum >= 0) \
4064         ge |= 1 << n; \
4065     } while(0)
4066
4067
4068 #define ADD16(a, b, n) SARITH16(a, b, n, +)
4069 #define SUB16(a, b, n) SARITH16(a, b, n, -)
4070 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
4071 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
4072 #define PFX s
4073 #define ARITH_GE
4074
4075 #include "op_addsub.h"
4076
4077 /* Unsigned modulo arithmetic.  */
4078 #define ADD16(a, b, n) do { \
4079     uint32_t sum; \
4080     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
4081     RESULT(sum, n, 16); \
4082     if ((sum >> 16) == 1) \
4083         ge |= 3 << (n * 2); \
4084     } while(0)
4085
4086 #define ADD8(a, b, n) do { \
4087     uint32_t sum; \
4088     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
4089     RESULT(sum, n, 8); \
4090     if ((sum >> 8) == 1) \
4091         ge |= 1 << n; \
4092     } while(0)
4093
4094 #define SUB16(a, b, n) do { \
4095     uint32_t sum; \
4096     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
4097     RESULT(sum, n, 16); \
4098     if ((sum >> 16) == 0) \
4099         ge |= 3 << (n * 2); \
4100     } while(0)
4101
4102 #define SUB8(a, b, n) do { \
4103     uint32_t sum; \
4104     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
4105     RESULT(sum, n, 8); \
4106     if ((sum >> 8) == 0) \
4107         ge |= 1 << n; \
4108     } while(0)
4109
4110 #define PFX u
4111 #define ARITH_GE
4112
4113 #include "op_addsub.h"
4114
4115 /* Halved signed arithmetic.  */
4116 #define ADD16(a, b, n) \
4117   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
4118 #define SUB16(a, b, n) \
4119   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
4120 #define ADD8(a, b, n) \
4121   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
4122 #define SUB8(a, b, n) \
4123   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
4124 #define PFX sh
4125
4126 #include "op_addsub.h"
4127
4128 /* Halved unsigned arithmetic.  */
4129 #define ADD16(a, b, n) \
4130   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
4131 #define SUB16(a, b, n) \
4132   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
4133 #define ADD8(a, b, n) \
4134   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
4135 #define SUB8(a, b, n) \
4136   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
4137 #define PFX uh
4138
4139 #include "op_addsub.h"
4140
4141 static inline uint8_t do_usad(uint8_t a, uint8_t b)
4142 {
4143     if (a > b)
4144         return a - b;
4145     else
4146         return b - a;
4147 }
4148
4149 /* Unsigned sum of absolute byte differences.  */
4150 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
4151 {
4152     uint32_t sum;
4153     sum = do_usad(a, b);
4154     sum += do_usad(a >> 8, b >> 8);
4155     sum += do_usad(a >> 16, b >>16);
4156     sum += do_usad(a >> 24, b >> 24);
4157     return sum;
4158 }
4159
4160 /* For ARMv6 SEL instruction.  */
4161 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
4162 {
4163     uint32_t mask;
4164
4165     mask = 0;
4166     if (flags & 1)
4167         mask |= 0xff;
4168     if (flags & 2)
4169         mask |= 0xff00;
4170     if (flags & 4)
4171         mask |= 0xff0000;
4172     if (flags & 8)
4173         mask |= 0xff000000;
4174     return (a & mask) | (b & ~mask);
4175 }
4176
4177 /* VFP support.  We follow the convention used for VFP instructions:
4178    Single precision routines have a "s" suffix, double precision a
4179    "d" suffix.  */
4180
4181 /* Convert host exception flags to vfp form.  */
4182 static inline int vfp_exceptbits_from_host(int host_bits)
4183 {
4184     int target_bits = 0;
4185
4186     if (host_bits & float_flag_invalid)
4187         target_bits |= 1;
4188     if (host_bits & float_flag_divbyzero)
4189         target_bits |= 2;
4190     if (host_bits & float_flag_overflow)
4191         target_bits |= 4;
4192     if (host_bits & (float_flag_underflow | float_flag_output_denormal))
4193         target_bits |= 8;
4194     if (host_bits & float_flag_inexact)
4195         target_bits |= 0x10;
4196     if (host_bits & float_flag_input_denormal)
4197         target_bits |= 0x80;
4198     return target_bits;
4199 }
4200
4201 uint32_t HELPER(vfp_get_fpscr)(CPUARMState *env)
4202 {
4203     int i;
4204     uint32_t fpscr;
4205
4206     fpscr = (env->vfp.xregs[ARM_VFP_FPSCR] & 0xffc8ffff)
4207             | (env->vfp.vec_len << 16)
4208             | (env->vfp.vec_stride << 20);
4209     i = get_float_exception_flags(&env->vfp.fp_status);
4210     i |= get_float_exception_flags(&env->vfp.standard_fp_status);
4211     fpscr |= vfp_exceptbits_from_host(i);
4212     return fpscr;
4213 }
4214
4215 uint32_t vfp_get_fpscr(CPUARMState *env)
4216 {
4217     return HELPER(vfp_get_fpscr)(env);
4218 }
4219
4220 /* Convert vfp exception flags to target form.  */
4221 static inline int vfp_exceptbits_to_host(int target_bits)
4222 {
4223     int host_bits = 0;
4224
4225     if (target_bits & 1)
4226         host_bits |= float_flag_invalid;
4227     if (target_bits & 2)
4228         host_bits |= float_flag_divbyzero;
4229     if (target_bits & 4)
4230         host_bits |= float_flag_overflow;
4231     if (target_bits & 8)
4232         host_bits |= float_flag_underflow;
4233     if (target_bits & 0x10)
4234         host_bits |= float_flag_inexact;
4235     if (target_bits & 0x80)
4236         host_bits |= float_flag_input_denormal;
4237     return host_bits;
4238 }
4239
4240 void HELPER(vfp_set_fpscr)(CPUARMState *env, uint32_t val)
4241 {
4242     int i;
4243     uint32_t changed;
4244
4245     changed = env->vfp.xregs[ARM_VFP_FPSCR];
4246     env->vfp.xregs[ARM_VFP_FPSCR] = (val & 0xffc8ffff);
4247     env->vfp.vec_len = (val >> 16) & 7;
4248     env->vfp.vec_stride = (val >> 20) & 3;
4249
4250     changed ^= val;
4251     if (changed & (3 << 22)) {
4252         i = (val >> 22) & 3;
4253         switch (i) {
4254         case FPROUNDING_TIEEVEN:
4255             i = float_round_nearest_even;
4256             break;
4257         case FPROUNDING_POSINF:
4258             i = float_round_up;
4259             break;
4260         case FPROUNDING_NEGINF:
4261             i = float_round_down;
4262             break;
4263         case FPROUNDING_ZERO:
4264             i = float_round_to_zero;
4265             break;
4266         }
4267         set_float_rounding_mode(i, &env->vfp.fp_status);
4268     }
4269     if (changed & (1 << 24)) {
4270         set_flush_to_zero((val & (1 << 24)) != 0, &env->vfp.fp_status);
4271         set_flush_inputs_to_zero((val & (1 << 24)) != 0, &env->vfp.fp_status);
4272     }
4273     if (changed & (1 << 25))
4274         set_default_nan_mode((val & (1 << 25)) != 0, &env->vfp.fp_status);
4275
4276     i = vfp_exceptbits_to_host(val);
4277     set_float_exception_flags(i, &env->vfp.fp_status);
4278     set_float_exception_flags(0, &env->vfp.standard_fp_status);
4279 }
4280
4281 void vfp_set_fpscr(CPUARMState *env, uint32_t val)
4282 {
4283     HELPER(vfp_set_fpscr)(env, val);
4284 }
4285
4286 #define VFP_HELPER(name, p) HELPER(glue(glue(vfp_,name),p))
4287
4288 #define VFP_BINOP(name) \
4289 float32 VFP_HELPER(name, s)(float32 a, float32 b, void *fpstp) \
4290 { \
4291     float_status *fpst = fpstp; \
4292     return float32_ ## name(a, b, fpst); \
4293 } \
4294 float64 VFP_HELPER(name, d)(float64 a, float64 b, void *fpstp) \
4295 { \
4296     float_status *fpst = fpstp; \
4297     return float64_ ## name(a, b, fpst); \
4298 }
4299 VFP_BINOP(add)
4300 VFP_BINOP(sub)
4301 VFP_BINOP(mul)
4302 VFP_BINOP(div)
4303 VFP_BINOP(min)
4304 VFP_BINOP(max)
4305 VFP_BINOP(minnum)
4306 VFP_BINOP(maxnum)
4307 #undef VFP_BINOP
4308
4309 float32 VFP_HELPER(neg, s)(float32 a)
4310 {
4311     return float32_chs(a);
4312 }
4313
4314 float64 VFP_HELPER(neg, d)(float64 a)
4315 {
4316     return float64_chs(a);
4317 }
4318
4319 float32 VFP_HELPER(abs, s)(float32 a)
4320 {
4321     return float32_abs(a);
4322 }
4323
4324 float64 VFP_HELPER(abs, d)(float64 a)
4325 {
4326     return float64_abs(a);
4327 }
4328
4329 float32 VFP_HELPER(sqrt, s)(float32 a, CPUARMState *env)
4330 {
4331     return float32_sqrt(a, &env->vfp.fp_status);
4332 }
4333
4334 float64 VFP_HELPER(sqrt, d)(float64 a, CPUARMState *env)
4335 {
4336     return float64_sqrt(a, &env->vfp.fp_status);
4337 }
4338
4339 /* XXX: check quiet/signaling case */
4340 #define DO_VFP_cmp(p, type) \
4341 void VFP_HELPER(cmp, p)(type a, type b, CPUARMState *env)  \
4342 { \
4343     uint32_t flags; \
4344     switch(type ## _compare_quiet(a, b, &env->vfp.fp_status)) { \
4345     case 0: flags = 0x6; break; \
4346     case -1: flags = 0x8; break; \
4347     case 1: flags = 0x2; break; \
4348     default: case 2: flags = 0x3; break; \
4349     } \
4350     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
4351         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
4352 } \
4353 void VFP_HELPER(cmpe, p)(type a, type b, CPUARMState *env) \
4354 { \
4355     uint32_t flags; \
4356     switch(type ## _compare(a, b, &env->vfp.fp_status)) { \
4357     case 0: flags = 0x6; break; \
4358     case -1: flags = 0x8; break; \
4359     case 1: flags = 0x2; break; \
4360     default: case 2: flags = 0x3; break; \
4361     } \
4362     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
4363         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
4364 }
4365 DO_VFP_cmp(s, float32)
4366 DO_VFP_cmp(d, float64)
4367 #undef DO_VFP_cmp
4368
4369 /* Integer to float and float to integer conversions */
4370
4371 #define CONV_ITOF(name, fsz, sign) \
4372     float##fsz HELPER(name)(uint32_t x, void *fpstp) \
4373 { \
4374     float_status *fpst = fpstp; \
4375     return sign##int32_to_##float##fsz((sign##int32_t)x, fpst); \
4376 }
4377
4378 #define CONV_FTOI(name, fsz, sign, round) \
4379 uint32_t HELPER(name)(float##fsz x, void *fpstp) \
4380 { \
4381     float_status *fpst = fpstp; \
4382     if (float##fsz##_is_any_nan(x)) { \
4383         float_raise(float_flag_invalid, fpst); \
4384         return 0; \
4385     } \
4386     return float##fsz##_to_##sign##int32##round(x, fpst); \
4387 }
4388
4389 #define FLOAT_CONVS(name, p, fsz, sign) \
4390 CONV_ITOF(vfp_##name##to##p, fsz, sign) \
4391 CONV_FTOI(vfp_to##name##p, fsz, sign, ) \
4392 CONV_FTOI(vfp_to##name##z##p, fsz, sign, _round_to_zero)
4393
4394 FLOAT_CONVS(si, s, 32, )
4395 FLOAT_CONVS(si, d, 64, )
4396 FLOAT_CONVS(ui, s, 32, u)
4397 FLOAT_CONVS(ui, d, 64, u)
4398
4399 #undef CONV_ITOF
4400 #undef CONV_FTOI
4401 #undef FLOAT_CONVS
4402
4403 /* floating point conversion */
4404 float64 VFP_HELPER(fcvtd, s)(float32 x, CPUARMState *env)
4405 {
4406     float64 r = float32_to_float64(x, &env->vfp.fp_status);
4407     /* ARM requires that S<->D conversion of any kind of NaN generates
4408      * a quiet NaN by forcing the most significant frac bit to 1.
4409      */
4410     return float64_maybe_silence_nan(r);
4411 }
4412
4413 float32 VFP_HELPER(fcvts, d)(float64 x, CPUARMState *env)
4414 {
4415     float32 r =  float64_to_float32(x, &env->vfp.fp_status);
4416     /* ARM requires that S<->D conversion of any kind of NaN generates
4417      * a quiet NaN by forcing the most significant frac bit to 1.
4418      */
4419     return float32_maybe_silence_nan(r);
4420 }
4421
4422 /* VFP3 fixed point conversion.  */
4423 #define VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype) \
4424 float##fsz HELPER(vfp_##name##to##p)(uint##isz##_t  x, uint32_t shift, \
4425                                      void *fpstp) \
4426 { \
4427     float_status *fpst = fpstp; \
4428     float##fsz tmp; \
4429     tmp = itype##_to_##float##fsz(x, fpst); \
4430     return float##fsz##_scalbn(tmp, -(int)shift, fpst); \
4431 }
4432
4433 /* Notice that we want only input-denormal exception flags from the
4434  * scalbn operation: the other possible flags (overflow+inexact if
4435  * we overflow to infinity, output-denormal) aren't correct for the
4436  * complete scale-and-convert operation.
4437  */
4438 #define VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, round) \
4439 uint##isz##_t HELPER(vfp_to##name##p##round)(float##fsz x, \
4440                                              uint32_t shift, \
4441                                              void *fpstp) \
4442 { \
4443     float_status *fpst = fpstp; \
4444     int old_exc_flags = get_float_exception_flags(fpst); \
4445     float##fsz tmp; \
4446     if (float##fsz##_is_any_nan(x)) { \
4447         float_raise(float_flag_invalid, fpst); \
4448         return 0; \
4449     } \
4450     tmp = float##fsz##_scalbn(x, shift, fpst); \
4451     old_exc_flags |= get_float_exception_flags(fpst) \
4452         & float_flag_input_denormal; \
4453     set_float_exception_flags(old_exc_flags, fpst); \
4454     return float##fsz##_to_##itype##round(tmp, fpst); \
4455 }
4456
4457 #define VFP_CONV_FIX(name, p, fsz, isz, itype)                   \
4458 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
4459 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, _round_to_zero) \
4460 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
4461
4462 #define VFP_CONV_FIX_A64(name, p, fsz, isz, itype)               \
4463 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
4464 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
4465
4466 VFP_CONV_FIX(sh, d, 64, 64, int16)
4467 VFP_CONV_FIX(sl, d, 64, 64, int32)
4468 VFP_CONV_FIX_A64(sq, d, 64, 64, int64)
4469 VFP_CONV_FIX(uh, d, 64, 64, uint16)
4470 VFP_CONV_FIX(ul, d, 64, 64, uint32)
4471 VFP_CONV_FIX_A64(uq, d, 64, 64, uint64)
4472 VFP_CONV_FIX(sh, s, 32, 32, int16)
4473 VFP_CONV_FIX(sl, s, 32, 32, int32)
4474 VFP_CONV_FIX_A64(sq, s, 32, 64, int64)
4475 VFP_CONV_FIX(uh, s, 32, 32, uint16)
4476 VFP_CONV_FIX(ul, s, 32, 32, uint32)
4477 VFP_CONV_FIX_A64(uq, s, 32, 64, uint64)
4478 #undef VFP_CONV_FIX
4479 #undef VFP_CONV_FIX_FLOAT
4480 #undef VFP_CONV_FLOAT_FIX_ROUND
4481
4482 /* Set the current fp rounding mode and return the old one.
4483  * The argument is a softfloat float_round_ value.
4484  */
4485 uint32_t HELPER(set_rmode)(uint32_t rmode, CPUARMState *env)
4486 {
4487     float_status *fp_status = &env->vfp.fp_status;
4488
4489     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
4490     set_float_rounding_mode(rmode, fp_status);
4491
4492     return prev_rmode;
4493 }
4494
4495 /* Set the current fp rounding mode in the standard fp status and return
4496  * the old one. This is for NEON instructions that need to change the
4497  * rounding mode but wish to use the standard FPSCR values for everything
4498  * else. Always set the rounding mode back to the correct value after
4499  * modifying it.
4500  * The argument is a softfloat float_round_ value.
4501  */
4502 uint32_t HELPER(set_neon_rmode)(uint32_t rmode, CPUARMState *env)
4503 {
4504     float_status *fp_status = &env->vfp.standard_fp_status;
4505
4506     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
4507     set_float_rounding_mode(rmode, fp_status);
4508
4509     return prev_rmode;
4510 }
4511
4512 /* Half precision conversions.  */
4513 static float32 do_fcvt_f16_to_f32(uint32_t a, CPUARMState *env, float_status *s)
4514 {
4515     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
4516     float32 r = float16_to_float32(make_float16(a), ieee, s);
4517     if (ieee) {
4518         return float32_maybe_silence_nan(r);
4519     }
4520     return r;
4521 }
4522
4523 static uint32_t do_fcvt_f32_to_f16(float32 a, CPUARMState *env, float_status *s)
4524 {
4525     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
4526     float16 r = float32_to_float16(a, ieee, s);
4527     if (ieee) {
4528         r = float16_maybe_silence_nan(r);
4529     }
4530     return float16_val(r);
4531 }
4532
4533 float32 HELPER(neon_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
4534 {
4535     return do_fcvt_f16_to_f32(a, env, &env->vfp.standard_fp_status);
4536 }
4537
4538 uint32_t HELPER(neon_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
4539 {
4540     return do_fcvt_f32_to_f16(a, env, &env->vfp.standard_fp_status);
4541 }
4542
4543 float32 HELPER(vfp_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
4544 {
4545     return do_fcvt_f16_to_f32(a, env, &env->vfp.fp_status);
4546 }
4547
4548 uint32_t HELPER(vfp_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
4549 {
4550     return do_fcvt_f32_to_f16(a, env, &env->vfp.fp_status);
4551 }
4552
4553 float64 HELPER(vfp_fcvt_f16_to_f64)(uint32_t a, CPUARMState *env)
4554 {
4555     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
4556     float64 r = float16_to_float64(make_float16(a), ieee, &env->vfp.fp_status);
4557     if (ieee) {
4558         return float64_maybe_silence_nan(r);
4559     }
4560     return r;
4561 }
4562
4563 uint32_t HELPER(vfp_fcvt_f64_to_f16)(float64 a, CPUARMState *env)
4564 {
4565     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
4566     float16 r = float64_to_float16(a, ieee, &env->vfp.fp_status);
4567     if (ieee) {
4568         r = float16_maybe_silence_nan(r);
4569     }
4570     return float16_val(r);
4571 }
4572
4573 #define float32_two make_float32(0x40000000)
4574 #define float32_three make_float32(0x40400000)
4575 #define float32_one_point_five make_float32(0x3fc00000)
4576
4577 float32 HELPER(recps_f32)(float32 a, float32 b, CPUARMState *env)
4578 {
4579     float_status *s = &env->vfp.standard_fp_status;
4580     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
4581         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
4582         if (!(float32_is_zero(a) || float32_is_zero(b))) {
4583             float_raise(float_flag_input_denormal, s);
4584         }
4585         return float32_two;
4586     }
4587     return float32_sub(float32_two, float32_mul(a, b, s), s);
4588 }
4589
4590 float32 HELPER(rsqrts_f32)(float32 a, float32 b, CPUARMState *env)
4591 {
4592     float_status *s = &env->vfp.standard_fp_status;
4593     float32 product;
4594     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
4595         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
4596         if (!(float32_is_zero(a) || float32_is_zero(b))) {
4597             float_raise(float_flag_input_denormal, s);
4598         }
4599         return float32_one_point_five;
4600     }
4601     product = float32_mul(a, b, s);
4602     return float32_div(float32_sub(float32_three, product, s), float32_two, s);
4603 }
4604
4605 /* NEON helpers.  */
4606
4607 /* Constants 256 and 512 are used in some helpers; we avoid relying on
4608  * int->float conversions at run-time.  */
4609 #define float64_256 make_float64(0x4070000000000000LL)
4610 #define float64_512 make_float64(0x4080000000000000LL)
4611 #define float32_maxnorm make_float32(0x7f7fffff)
4612 #define float64_maxnorm make_float64(0x7fefffffffffffffLL)
4613
4614 /* Reciprocal functions
4615  *
4616  * The algorithm that must be used to calculate the estimate
4617  * is specified by the ARM ARM, see FPRecipEstimate()
4618  */
4619
4620 static float64 recip_estimate(float64 a, float_status *real_fp_status)
4621 {
4622     /* These calculations mustn't set any fp exception flags,
4623      * so we use a local copy of the fp_status.
4624      */
4625     float_status dummy_status = *real_fp_status;
4626     float_status *s = &dummy_status;
4627     /* q = (int)(a * 512.0) */
4628     float64 q = float64_mul(float64_512, a, s);
4629     int64_t q_int = float64_to_int64_round_to_zero(q, s);
4630
4631     /* r = 1.0 / (((double)q + 0.5) / 512.0) */
4632     q = int64_to_float64(q_int, s);
4633     q = float64_add(q, float64_half, s);
4634     q = float64_div(q, float64_512, s);
4635     q = float64_div(float64_one, q, s);
4636
4637     /* s = (int)(256.0 * r + 0.5) */
4638     q = float64_mul(q, float64_256, s);
4639     q = float64_add(q, float64_half, s);
4640     q_int = float64_to_int64_round_to_zero(q, s);
4641
4642     /* return (double)s / 256.0 */
4643     return float64_div(int64_to_float64(q_int, s), float64_256, s);
4644 }
4645
4646 /* Common wrapper to call recip_estimate */
4647 static float64 call_recip_estimate(float64 num, int off, float_status *fpst)
4648 {
4649     uint64_t val64 = float64_val(num);
4650     uint64_t frac = extract64(val64, 0, 52);
4651     int64_t exp = extract64(val64, 52, 11);
4652     uint64_t sbit;
4653     float64 scaled, estimate;
4654
4655     /* Generate the scaled number for the estimate function */
4656     if (exp == 0) {
4657         if (extract64(frac, 51, 1) == 0) {
4658             exp = -1;
4659             frac = extract64(frac, 0, 50) << 2;
4660         } else {
4661             frac = extract64(frac, 0, 51) << 1;
4662         }
4663     }
4664
4665     /* scaled = '0' : '01111111110' : fraction<51:44> : Zeros(44); */
4666     scaled = make_float64((0x3feULL << 52)
4667                           | extract64(frac, 44, 8) << 44);
4668
4669     estimate = recip_estimate(scaled, fpst);
4670
4671     /* Build new result */
4672     val64 = float64_val(estimate);
4673     sbit = 0x8000000000000000ULL & val64;
4674     exp = off - exp;
4675     frac = extract64(val64, 0, 52);
4676
4677     if (exp == 0) {
4678         frac = 1ULL << 51 | extract64(frac, 1, 51);
4679     } else if (exp == -1) {
4680         frac = 1ULL << 50 | extract64(frac, 2, 50);
4681         exp = 0;
4682     }
4683
4684     return make_float64(sbit | (exp << 52) | frac);
4685 }
4686
4687 static bool round_to_inf(float_status *fpst, bool sign_bit)
4688 {
4689     switch (fpst->float_rounding_mode) {
4690     case float_round_nearest_even: /* Round to Nearest */
4691         return true;
4692     case float_round_up: /* Round to +Inf */
4693         return !sign_bit;
4694     case float_round_down: /* Round to -Inf */
4695         return sign_bit;
4696     case float_round_to_zero: /* Round to Zero */
4697         return false;
4698     }
4699
4700     g_assert_not_reached();
4701 }
4702
4703 float32 HELPER(recpe_f32)(float32 input, void *fpstp)
4704 {
4705     float_status *fpst = fpstp;
4706     float32 f32 = float32_squash_input_denormal(input, fpst);
4707     uint32_t f32_val = float32_val(f32);
4708     uint32_t f32_sbit = 0x80000000ULL & f32_val;
4709     int32_t f32_exp = extract32(f32_val, 23, 8);
4710     uint32_t f32_frac = extract32(f32_val, 0, 23);
4711     float64 f64, r64;
4712     uint64_t r64_val;
4713     int64_t r64_exp;
4714     uint64_t r64_frac;
4715
4716     if (float32_is_any_nan(f32)) {
4717         float32 nan = f32;
4718         if (float32_is_signaling_nan(f32)) {
4719             float_raise(float_flag_invalid, fpst);
4720             nan = float32_maybe_silence_nan(f32);
4721         }
4722         if (fpst->default_nan_mode) {
4723             nan =  float32_default_nan;
4724         }
4725         return nan;
4726     } else if (float32_is_infinity(f32)) {
4727         return float32_set_sign(float32_zero, float32_is_neg(f32));
4728     } else if (float32_is_zero(f32)) {
4729         float_raise(float_flag_divbyzero, fpst);
4730         return float32_set_sign(float32_infinity, float32_is_neg(f32));
4731     } else if ((f32_val & ~(1ULL << 31)) < (1ULL << 21)) {
4732         /* Abs(value) < 2.0^-128 */
4733         float_raise(float_flag_overflow | float_flag_inexact, fpst);
4734         if (round_to_inf(fpst, f32_sbit)) {
4735             return float32_set_sign(float32_infinity, float32_is_neg(f32));
4736         } else {
4737             return float32_set_sign(float32_maxnorm, float32_is_neg(f32));
4738         }
4739     } else if (f32_exp >= 253 && fpst->flush_to_zero) {
4740         float_raise(float_flag_underflow, fpst);
4741         return float32_set_sign(float32_zero, float32_is_neg(f32));
4742     }
4743
4744
4745     f64 = make_float64(((int64_t)(f32_exp) << 52) | (int64_t)(f32_frac) << 29);
4746     r64 = call_recip_estimate(f64, 253, fpst);
4747     r64_val = float64_val(r64);
4748     r64_exp = extract64(r64_val, 52, 11);
4749     r64_frac = extract64(r64_val, 0, 52);
4750
4751     /* result = sign : result_exp<7:0> : fraction<51:29>; */
4752     return make_float32(f32_sbit |
4753                         (r64_exp & 0xff) << 23 |
4754                         extract64(r64_frac, 29, 24));
4755 }
4756
4757 float64 HELPER(recpe_f64)(float64 input, void *fpstp)
4758 {
4759     float_status *fpst = fpstp;
4760     float64 f64 = float64_squash_input_denormal(input, fpst);
4761     uint64_t f64_val = float64_val(f64);
4762     uint64_t f64_sbit = 0x8000000000000000ULL & f64_val;
4763     int64_t f64_exp = extract64(f64_val, 52, 11);
4764     float64 r64;
4765     uint64_t r64_val;
4766     int64_t r64_exp;
4767     uint64_t r64_frac;
4768
4769     /* Deal with any special cases */
4770     if (float64_is_any_nan(f64)) {
4771         float64 nan = f64;
4772         if (float64_is_signaling_nan(f64)) {
4773             float_raise(float_flag_invalid, fpst);
4774             nan = float64_maybe_silence_nan(f64);
4775         }
4776         if (fpst->default_nan_mode) {
4777             nan =  float64_default_nan;
4778         }
4779         return nan;
4780     } else if (float64_is_infinity(f64)) {
4781         return float64_set_sign(float64_zero, float64_is_neg(f64));
4782     } else if (float64_is_zero(f64)) {
4783         float_raise(float_flag_divbyzero, fpst);
4784         return float64_set_sign(float64_infinity, float64_is_neg(f64));
4785     } else if ((f64_val & ~(1ULL << 63)) < (1ULL << 50)) {
4786         /* Abs(value) < 2.0^-1024 */
4787         float_raise(float_flag_overflow | float_flag_inexact, fpst);
4788         if (round_to_inf(fpst, f64_sbit)) {
4789             return float64_set_sign(float64_infinity, float64_is_neg(f64));
4790         } else {
4791             return float64_set_sign(float64_maxnorm, float64_is_neg(f64));
4792         }
4793     } else if (f64_exp >= 1023 && fpst->flush_to_zero) {
4794         float_raise(float_flag_underflow, fpst);
4795         return float64_set_sign(float64_zero, float64_is_neg(f64));
4796     }
4797
4798     r64 = call_recip_estimate(f64, 2045, fpst);
4799     r64_val = float64_val(r64);
4800     r64_exp = extract64(r64_val, 52, 11);
4801     r64_frac = extract64(r64_val, 0, 52);
4802
4803     /* result = sign : result_exp<10:0> : fraction<51:0> */
4804     return make_float64(f64_sbit |
4805                         ((r64_exp & 0x7ff) << 52) |
4806                         r64_frac);
4807 }
4808
4809 /* The algorithm that must be used to calculate the estimate
4810  * is specified by the ARM ARM.
4811  */
4812 static float64 recip_sqrt_estimate(float64 a, float_status *real_fp_status)
4813 {
4814     /* These calculations mustn't set any fp exception flags,
4815      * so we use a local copy of the fp_status.
4816      */
4817     float_status dummy_status = *real_fp_status;
4818     float_status *s = &dummy_status;
4819     float64 q;
4820     int64_t q_int;
4821
4822     if (float64_lt(a, float64_half, s)) {
4823         /* range 0.25 <= a < 0.5 */
4824
4825         /* a in units of 1/512 rounded down */
4826         /* q0 = (int)(a * 512.0);  */
4827         q = float64_mul(float64_512, a, s);
4828         q_int = float64_to_int64_round_to_zero(q, s);
4829
4830         /* reciprocal root r */
4831         /* r = 1.0 / sqrt(((double)q0 + 0.5) / 512.0);  */
4832         q = int64_to_float64(q_int, s);
4833         q = float64_add(q, float64_half, s);
4834         q = float64_div(q, float64_512, s);
4835         q = float64_sqrt(q, s);
4836         q = float64_div(float64_one, q, s);
4837     } else {
4838         /* range 0.5 <= a < 1.0 */
4839
4840         /* a in units of 1/256 rounded down */
4841         /* q1 = (int)(a * 256.0); */
4842         q = float64_mul(float64_256, a, s);
4843         int64_t q_int = float64_to_int64_round_to_zero(q, s);
4844
4845         /* reciprocal root r */
4846         /* r = 1.0 /sqrt(((double)q1 + 0.5) / 256); */
4847         q = int64_to_float64(q_int, s);
4848         q = float64_add(q, float64_half, s);
4849         q = float64_div(q, float64_256, s);
4850         q = float64_sqrt(q, s);
4851         q = float64_div(float64_one, q, s);
4852     }
4853     /* r in units of 1/256 rounded to nearest */
4854     /* s = (int)(256.0 * r + 0.5); */
4855
4856     q = float64_mul(q, float64_256,s );
4857     q = float64_add(q, float64_half, s);
4858     q_int = float64_to_int64_round_to_zero(q, s);
4859
4860     /* return (double)s / 256.0;*/
4861     return float64_div(int64_to_float64(q_int, s), float64_256, s);
4862 }
4863
4864 float32 HELPER(rsqrte_f32)(float32 input, void *fpstp)
4865 {
4866     float_status *s = fpstp;
4867     float32 f32 = float32_squash_input_denormal(input, s);
4868     uint32_t val = float32_val(f32);
4869     uint32_t f32_sbit = 0x80000000 & val;
4870     int32_t f32_exp = extract32(val, 23, 8);
4871     uint32_t f32_frac = extract32(val, 0, 23);
4872     uint64_t f64_frac;
4873     uint64_t val64;
4874     int result_exp;
4875     float64 f64;
4876
4877     if (float32_is_any_nan(f32)) {
4878         float32 nan = f32;
4879         if (float32_is_signaling_nan(f32)) {
4880             float_raise(float_flag_invalid, s);
4881             nan = float32_maybe_silence_nan(f32);
4882         }
4883         if (s->default_nan_mode) {
4884             nan =  float32_default_nan;
4885         }
4886         return nan;
4887     } else if (float32_is_zero(f32)) {
4888         float_raise(float_flag_divbyzero, s);
4889         return float32_set_sign(float32_infinity, float32_is_neg(f32));
4890     } else if (float32_is_neg(f32)) {
4891         float_raise(float_flag_invalid, s);
4892         return float32_default_nan;
4893     } else if (float32_is_infinity(f32)) {
4894         return float32_zero;
4895     }
4896
4897     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
4898      * preserving the parity of the exponent.  */
4899
4900     f64_frac = ((uint64_t) f32_frac) << 29;
4901     if (f32_exp == 0) {
4902         while (extract64(f64_frac, 51, 1) == 0) {
4903             f64_frac = f64_frac << 1;
4904             f32_exp = f32_exp-1;
4905         }
4906         f64_frac = extract64(f64_frac, 0, 51) << 1;
4907     }
4908
4909     if (extract64(f32_exp, 0, 1) == 0) {
4910         f64 = make_float64(((uint64_t) f32_sbit) << 32
4911                            | (0x3feULL << 52)
4912                            | f64_frac);
4913     } else {
4914         f64 = make_float64(((uint64_t) f32_sbit) << 32
4915                            | (0x3fdULL << 52)
4916                            | f64_frac);
4917     }
4918
4919     result_exp = (380 - f32_exp) / 2;
4920
4921     f64 = recip_sqrt_estimate(f64, s);
4922
4923     val64 = float64_val(f64);
4924
4925     val = ((result_exp & 0xff) << 23)
4926         | ((val64 >> 29)  & 0x7fffff);
4927     return make_float32(val);
4928 }
4929
4930 float64 HELPER(rsqrte_f64)(float64 input, void *fpstp)
4931 {
4932     float_status *s = fpstp;
4933     float64 f64 = float64_squash_input_denormal(input, s);
4934     uint64_t val = float64_val(f64);
4935     uint64_t f64_sbit = 0x8000000000000000ULL & val;
4936     int64_t f64_exp = extract64(val, 52, 11);
4937     uint64_t f64_frac = extract64(val, 0, 52);
4938     int64_t result_exp;
4939     uint64_t result_frac;
4940
4941     if (float64_is_any_nan(f64)) {
4942         float64 nan = f64;
4943         if (float64_is_signaling_nan(f64)) {
4944             float_raise(float_flag_invalid, s);
4945             nan = float64_maybe_silence_nan(f64);
4946         }
4947         if (s->default_nan_mode) {
4948             nan =  float64_default_nan;
4949         }
4950         return nan;
4951     } else if (float64_is_zero(f64)) {
4952         float_raise(float_flag_divbyzero, s);
4953         return float64_set_sign(float64_infinity, float64_is_neg(f64));
4954     } else if (float64_is_neg(f64)) {
4955         float_raise(float_flag_invalid, s);
4956         return float64_default_nan;
4957     } else if (float64_is_infinity(f64)) {
4958         return float64_zero;
4959     }
4960
4961     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
4962      * preserving the parity of the exponent.  */
4963
4964     if (f64_exp == 0) {
4965         while (extract64(f64_frac, 51, 1) == 0) {
4966             f64_frac = f64_frac << 1;
4967             f64_exp = f64_exp - 1;
4968         }
4969         f64_frac = extract64(f64_frac, 0, 51) << 1;
4970     }
4971
4972     if (extract64(f64_exp, 0, 1) == 0) {
4973         f64 = make_float64(f64_sbit
4974                            | (0x3feULL << 52)
4975                            | f64_frac);
4976     } else {
4977         f64 = make_float64(f64_sbit
4978                            | (0x3fdULL << 52)
4979                            | f64_frac);
4980     }
4981
4982     result_exp = (3068 - f64_exp) / 2;
4983
4984     f64 = recip_sqrt_estimate(f64, s);
4985
4986     result_frac = extract64(float64_val(f64), 0, 52);
4987
4988     return make_float64(f64_sbit |
4989                         ((result_exp & 0x7ff) << 52) |
4990                         result_frac);
4991 }
4992
4993 uint32_t HELPER(recpe_u32)(uint32_t a, void *fpstp)
4994 {
4995     float_status *s = fpstp;
4996     float64 f64;
4997
4998     if ((a & 0x80000000) == 0) {
4999         return 0xffffffff;
5000     }
5001
5002     f64 = make_float64((0x3feULL << 52)
5003                        | ((int64_t)(a & 0x7fffffff) << 21));
5004
5005     f64 = recip_estimate(f64, s);
5006
5007     return 0x80000000 | ((float64_val(f64) >> 21) & 0x7fffffff);
5008 }
5009
5010 uint32_t HELPER(rsqrte_u32)(uint32_t a, void *fpstp)
5011 {
5012     float_status *fpst = fpstp;
5013     float64 f64;
5014
5015     if ((a & 0xc0000000) == 0) {
5016         return 0xffffffff;
5017     }
5018
5019     if (a & 0x80000000) {
5020         f64 = make_float64((0x3feULL << 52)
5021                            | ((uint64_t)(a & 0x7fffffff) << 21));
5022     } else { /* bits 31-30 == '01' */
5023         f64 = make_float64((0x3fdULL << 52)
5024                            | ((uint64_t)(a & 0x3fffffff) << 22));
5025     }
5026
5027     f64 = recip_sqrt_estimate(f64, fpst);
5028
5029     return 0x80000000 | ((float64_val(f64) >> 21) & 0x7fffffff);
5030 }
5031
5032 /* VFPv4 fused multiply-accumulate */
5033 float32 VFP_HELPER(muladd, s)(float32 a, float32 b, float32 c, void *fpstp)
5034 {
5035     float_status *fpst = fpstp;
5036     return float32_muladd(a, b, c, 0, fpst);
5037 }
5038
5039 float64 VFP_HELPER(muladd, d)(float64 a, float64 b, float64 c, void *fpstp)
5040 {
5041     float_status *fpst = fpstp;
5042     return float64_muladd(a, b, c, 0, fpst);
5043 }
5044
5045 /* ARMv8 round to integral */
5046 float32 HELPER(rints_exact)(float32 x, void *fp_status)
5047 {
5048     return float32_round_to_int(x, fp_status);
5049 }
5050
5051 float64 HELPER(rintd_exact)(float64 x, void *fp_status)
5052 {
5053     return float64_round_to_int(x, fp_status);
5054 }
5055
5056 float32 HELPER(rints)(float32 x, void *fp_status)
5057 {
5058     int old_flags = get_float_exception_flags(fp_status), new_flags;
5059     float32 ret;
5060
5061     ret = float32_round_to_int(x, fp_status);
5062
5063     /* Suppress any inexact exceptions the conversion produced */
5064     if (!(old_flags & float_flag_inexact)) {
5065         new_flags = get_float_exception_flags(fp_status);
5066         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
5067     }
5068
5069     return ret;
5070 }
5071
5072 float64 HELPER(rintd)(float64 x, void *fp_status)
5073 {
5074     int old_flags = get_float_exception_flags(fp_status), new_flags;
5075     float64 ret;
5076
5077     ret = float64_round_to_int(x, fp_status);
5078
5079     new_flags = get_float_exception_flags(fp_status);
5080
5081     /* Suppress any inexact exceptions the conversion produced */
5082     if (!(old_flags & float_flag_inexact)) {
5083         new_flags = get_float_exception_flags(fp_status);
5084         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
5085     }
5086
5087     return ret;
5088 }
5089
5090 /* Convert ARM rounding mode to softfloat */
5091 int arm_rmode_to_sf(int rmode)
5092 {
5093     switch (rmode) {
5094     case FPROUNDING_TIEAWAY:
5095         rmode = float_round_ties_away;
5096         break;
5097     case FPROUNDING_ODD:
5098         /* FIXME: add support for TIEAWAY and ODD */
5099         qemu_log_mask(LOG_UNIMP, "arm: unimplemented rounding mode: %d\n",
5100                       rmode);
5101     case FPROUNDING_TIEEVEN:
5102     default:
5103         rmode = float_round_nearest_even;
5104         break;
5105     case FPROUNDING_POSINF:
5106         rmode = float_round_up;
5107         break;
5108     case FPROUNDING_NEGINF:
5109         rmode = float_round_down;
5110         break;
5111     case FPROUNDING_ZERO:
5112         rmode = float_round_to_zero;
5113         break;
5114     }
5115     return rmode;
5116 }
5117
5118 static void crc_init_buffer(uint8_t *buf, uint32_t val, uint32_t bytes)
5119 {
5120     memset(buf, 0, 4);
5121
5122     if (bytes == 1) {
5123         buf[0] = val & 0xff;
5124     } else if (bytes == 2) {
5125         buf[0] = val & 0xff;
5126         buf[1] = (val >> 8) & 0xff;
5127     } else {
5128         buf[0] = val & 0xff;
5129         buf[1] = (val >> 8) & 0xff;
5130         buf[2] = (val >> 16) & 0xff;
5131         buf[3] = (val >> 24) & 0xff;
5132     }
5133 }
5134
5135 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
5136 {
5137     uint8_t buf[4];
5138
5139     crc_init_buffer(buf, val, bytes);
5140
5141     /* zlib crc32 converts the accumulator and output to one's complement.  */
5142     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
5143 }
5144
5145 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
5146 {
5147     uint8_t buf[4];
5148
5149     crc_init_buffer(buf, val, bytes);
5150
5151     /* Linux crc32c converts the output to one's complement.  */
5152     return crc32c(acc, buf, bytes) ^ 0xffffffff;
5153 }