xref: /openbmc/qemu/target/arm/ptw.c (revision 6e7c96ae)
1 /*
2  * ARM page table walking.
3  *
4  * This code is licensed under the GNU GPL v2 or later.
5  *
6  * SPDX-License-Identifier: GPL-2.0-or-later
7  */
8 
9 #include "qemu/osdep.h"
10 #include "qemu/log.h"
11 #include "qemu/range.h"
12 #include "qemu/main-loop.h"
13 #include "exec/exec-all.h"
14 #include "exec/page-protection.h"
15 #include "cpu.h"
16 #include "internals.h"
17 #include "cpu-features.h"
18 #include "idau.h"
19 #ifdef CONFIG_TCG
20 # include "tcg/oversized-guest.h"
21 #endif
22 
23 typedef struct S1Translate {
24     /*
25      * in_mmu_idx : specifies which TTBR, TCR, etc to use for the walk.
26      * Together with in_space, specifies the architectural translation regime.
27      */
28     ARMMMUIdx in_mmu_idx;
29     /*
30      * in_ptw_idx: specifies which mmuidx to use for the actual
31      * page table descriptor load operations. This will be one of the
32      * ARMMMUIdx_Stage2* or one of the ARMMMUIdx_Phys_* indexes.
33      * If a Secure ptw is "downgraded" to NonSecure by an NSTable bit,
34      * this field is updated accordingly.
35      */
36     ARMMMUIdx in_ptw_idx;
37     /*
38      * in_space: the security space for this walk. This plus
39      * the in_mmu_idx specify the architectural translation regime.
40      * If a Secure ptw is "downgraded" to NonSecure by an NSTable bit,
41      * this field is updated accordingly.
42      *
43      * Note that the security space for the in_ptw_idx may be different
44      * from that for the in_mmu_idx. We do not need to explicitly track
45      * the in_ptw_idx security space because:
46      *  - if the in_ptw_idx is an ARMMMUIdx_Phys_* then the mmuidx
47      *    itself specifies the security space
48      *  - if the in_ptw_idx is an ARMMMUIdx_Stage2* then the security
49      *    space used for ptw reads is the same as that of the security
50      *    space of the stage 1 translation for all cases except where
51      *    stage 1 is Secure; in that case the only possibilities for
52      *    the ptw read are Secure and NonSecure, and the in_ptw_idx
53      *    value being Stage2 vs Stage2_S distinguishes those.
54      */
55     ARMSecuritySpace in_space;
56     /*
57      * in_debug: is this a QEMU debug access (gdbstub, etc)? Debug
58      * accesses will not update the guest page table access flags
59      * and will not change the state of the softmmu TLBs.
60      */
61     bool in_debug;
62     /*
63      * If this is stage 2 of a stage 1+2 page table walk, then this must
64      * be true if stage 1 is an EL0 access; otherwise this is ignored.
65      * Stage 2 is indicated by in_mmu_idx set to ARMMMUIdx_Stage2{,_S}.
66      */
67     bool in_s1_is_el0;
68     bool out_rw;
69     bool out_be;
70     ARMSecuritySpace out_space;
71     hwaddr out_virt;
72     hwaddr out_phys;
73     void *out_host;
74 } S1Translate;
75 
76 static bool get_phys_addr_nogpc(CPUARMState *env, S1Translate *ptw,
77                                 vaddr address,
78                                 MMUAccessType access_type, MemOp memop,
79                                 GetPhysAddrResult *result,
80                                 ARMMMUFaultInfo *fi);
81 
82 static bool get_phys_addr_gpc(CPUARMState *env, S1Translate *ptw,
83                               vaddr address,
84                               MMUAccessType access_type, MemOp memop,
85                               GetPhysAddrResult *result,
86                               ARMMMUFaultInfo *fi);
87 
88 /* This mapping is common between ID_AA64MMFR0.PARANGE and TCR_ELx.{I}PS. */
89 static const uint8_t pamax_map[] = {
90     [0] = 32,
91     [1] = 36,
92     [2] = 40,
93     [3] = 42,
94     [4] = 44,
95     [5] = 48,
96     [6] = 52,
97 };
98 
99 uint8_t round_down_to_parange_index(uint8_t bit_size)
100 {
101     for (int i = ARRAY_SIZE(pamax_map) - 1; i >= 0; i--) {
102         if (pamax_map[i] <= bit_size) {
103             return i;
104         }
105     }
106     g_assert_not_reached();
107 }
108 
109 uint8_t round_down_to_parange_bit_size(uint8_t bit_size)
110 {
111     return pamax_map[round_down_to_parange_index(bit_size)];
112 }
113 
114 /*
115  * The cpu-specific constant value of PAMax; also used by hw/arm/virt.
116  * Note that machvirt_init calls this on a CPU that is inited but not realized!
117  */
118 unsigned int arm_pamax(ARMCPU *cpu)
119 {
120     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
121         unsigned int parange =
122             FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
123 
124         /*
125          * id_aa64mmfr0 is a read-only register so values outside of the
126          * supported mappings can be considered an implementation error.
127          */
128         assert(parange < ARRAY_SIZE(pamax_map));
129         return pamax_map[parange];
130     }
131 
132     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
133         /* v7 or v8 with LPAE */
134         return 40;
135     }
136     /* Anything else */
137     return 32;
138 }
139 
140 /*
141  * Convert a possible stage1+2 MMU index into the appropriate stage 1 MMU index
142  */
143 ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
144 {
145     switch (mmu_idx) {
146     case ARMMMUIdx_E10_0:
147         return ARMMMUIdx_Stage1_E0;
148     case ARMMMUIdx_E10_1:
149         return ARMMMUIdx_Stage1_E1;
150     case ARMMMUIdx_E10_1_PAN:
151         return ARMMMUIdx_Stage1_E1_PAN;
152     default:
153         return mmu_idx;
154     }
155 }
156 
157 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
158 {
159     return stage_1_mmu_idx(arm_mmu_idx(env));
160 }
161 
162 /*
163  * Return where we should do ptw loads from for a stage 2 walk.
164  * This depends on whether the address we are looking up is a
165  * Secure IPA or a NonSecure IPA, which we know from whether this is
166  * Stage2 or Stage2_S.
167  * If this is the Secure EL1&0 regime we need to check the NSW and SW bits.
168  */
169 static ARMMMUIdx ptw_idx_for_stage_2(CPUARMState *env, ARMMMUIdx stage2idx)
170 {
171     bool s2walk_secure;
172 
173     /*
174      * We're OK to check the current state of the CPU here because
175      * (1) we always invalidate all TLBs when the SCR_EL3.NS or SCR_EL3.NSE bit
176      * changes.
177      * (2) there's no way to do a lookup that cares about Stage 2 for a
178      * different security state to the current one for AArch64, and AArch32
179      * never has a secure EL2. (AArch32 ATS12NSO[UP][RW] allow EL3 to do
180      * an NS stage 1+2 lookup while the NS bit is 0.)
181      */
182     if (!arm_el_is_aa64(env, 3)) {
183         return ARMMMUIdx_Phys_NS;
184     }
185 
186     switch (arm_security_space_below_el3(env)) {
187     case ARMSS_NonSecure:
188         return ARMMMUIdx_Phys_NS;
189     case ARMSS_Realm:
190         return ARMMMUIdx_Phys_Realm;
191     case ARMSS_Secure:
192         if (stage2idx == ARMMMUIdx_Stage2_S) {
193             s2walk_secure = !(env->cp15.vstcr_el2 & VSTCR_SW);
194         } else {
195             s2walk_secure = !(env->cp15.vtcr_el2 & VTCR_NSW);
196         }
197         return s2walk_secure ? ARMMMUIdx_Phys_S : ARMMMUIdx_Phys_NS;
198     default:
199         g_assert_not_reached();
200     }
201 }
202 
203 static bool regime_translation_big_endian(CPUARMState *env, ARMMMUIdx mmu_idx)
204 {
205     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
206 }
207 
208 /* Return the TTBR associated with this translation regime */
209 static uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx, int ttbrn)
210 {
211     if (mmu_idx == ARMMMUIdx_Stage2) {
212         return env->cp15.vttbr_el2;
213     }
214     if (mmu_idx == ARMMMUIdx_Stage2_S) {
215         return env->cp15.vsttbr_el2;
216     }
217     if (ttbrn == 0) {
218         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
219     } else {
220         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
221     }
222 }
223 
224 /* Return true if the specified stage of address translation is disabled */
225 static bool regime_translation_disabled(CPUARMState *env, ARMMMUIdx mmu_idx,
226                                         ARMSecuritySpace space)
227 {
228     uint64_t hcr_el2;
229 
230     if (arm_feature(env, ARM_FEATURE_M)) {
231         bool is_secure = arm_space_is_secure(space);
232         switch (env->v7m.mpu_ctrl[is_secure] &
233                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
234         case R_V7M_MPU_CTRL_ENABLE_MASK:
235             /* Enabled, but not for HardFault and NMI */
236             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
237         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
238             /* Enabled for all cases */
239             return false;
240         case 0:
241         default:
242             /*
243              * HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
244              * we warned about that in armv7m_nvic.c when the guest set it.
245              */
246             return true;
247         }
248     }
249 
250 
251     switch (mmu_idx) {
252     case ARMMMUIdx_Stage2:
253     case ARMMMUIdx_Stage2_S:
254         /* HCR.DC means HCR.VM behaves as 1 */
255         hcr_el2 = arm_hcr_el2_eff_secstate(env, space);
256         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
257 
258     case ARMMMUIdx_E10_0:
259     case ARMMMUIdx_E10_1:
260     case ARMMMUIdx_E10_1_PAN:
261         /* TGE means that EL0/1 act as if SCTLR_EL1.M is zero */
262         hcr_el2 = arm_hcr_el2_eff_secstate(env, space);
263         if (hcr_el2 & HCR_TGE) {
264             return true;
265         }
266         break;
267 
268     case ARMMMUIdx_Stage1_E0:
269     case ARMMMUIdx_Stage1_E1:
270     case ARMMMUIdx_Stage1_E1_PAN:
271         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
272         hcr_el2 = arm_hcr_el2_eff_secstate(env, space);
273         if (hcr_el2 & HCR_DC) {
274             return true;
275         }
276         break;
277 
278     case ARMMMUIdx_E20_0:
279     case ARMMMUIdx_E20_2:
280     case ARMMMUIdx_E20_2_PAN:
281     case ARMMMUIdx_E2:
282     case ARMMMUIdx_E3:
283     case ARMMMUIdx_E30_0:
284     case ARMMMUIdx_E30_3_PAN:
285         break;
286 
287     case ARMMMUIdx_Phys_S:
288     case ARMMMUIdx_Phys_NS:
289     case ARMMMUIdx_Phys_Root:
290     case ARMMMUIdx_Phys_Realm:
291         /* No translation for physical address spaces. */
292         return true;
293 
294     default:
295         g_assert_not_reached();
296     }
297 
298     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
299 }
300 
301 static bool granule_protection_check(CPUARMState *env, uint64_t paddress,
302                                      ARMSecuritySpace pspace,
303                                      ARMMMUFaultInfo *fi)
304 {
305     MemTxAttrs attrs = {
306         .secure = true,
307         .space = ARMSS_Root,
308     };
309     ARMCPU *cpu = env_archcpu(env);
310     uint64_t gpccr = env->cp15.gpccr_el3;
311     unsigned pps, pgs, l0gptsz, level = 0;
312     uint64_t tableaddr, pps_mask, align, entry, index;
313     AddressSpace *as;
314     MemTxResult result;
315     int gpi;
316 
317     if (!FIELD_EX64(gpccr, GPCCR, GPC)) {
318         return true;
319     }
320 
321     /*
322      * GPC Priority 1 (R_GMGRR):
323      * R_JWCSM: If the configuration of GPCCR_EL3 is invalid,
324      * the access fails as GPT walk fault at level 0.
325      */
326 
327     /*
328      * Configuration of PPS to a value exceeding the implemented
329      * physical address size is invalid.
330      */
331     pps = FIELD_EX64(gpccr, GPCCR, PPS);
332     if (pps > FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE)) {
333         goto fault_walk;
334     }
335     pps = pamax_map[pps];
336     pps_mask = MAKE_64BIT_MASK(0, pps);
337 
338     switch (FIELD_EX64(gpccr, GPCCR, SH)) {
339     case 0b10: /* outer shareable */
340         break;
341     case 0b00: /* non-shareable */
342     case 0b11: /* inner shareable */
343         /* Inner and Outer non-cacheable requires Outer shareable. */
344         if (FIELD_EX64(gpccr, GPCCR, ORGN) == 0 &&
345             FIELD_EX64(gpccr, GPCCR, IRGN) == 0) {
346             goto fault_walk;
347         }
348         break;
349     default:   /* reserved */
350         goto fault_walk;
351     }
352 
353     switch (FIELD_EX64(gpccr, GPCCR, PGS)) {
354     case 0b00: /* 4KB */
355         pgs = 12;
356         break;
357     case 0b01: /* 64KB */
358         pgs = 16;
359         break;
360     case 0b10: /* 16KB */
361         pgs = 14;
362         break;
363     default: /* reserved */
364         goto fault_walk;
365     }
366 
367     /* Note this field is read-only and fixed at reset. */
368     l0gptsz = 30 + FIELD_EX64(gpccr, GPCCR, L0GPTSZ);
369 
370     /*
371      * GPC Priority 2: Secure, Realm or Root address exceeds PPS.
372      * R_CPDSB: A NonSecure physical address input exceeding PPS
373      * does not experience any fault.
374      */
375     if (paddress & ~pps_mask) {
376         if (pspace == ARMSS_NonSecure) {
377             return true;
378         }
379         goto fault_size;
380     }
381 
382     /* GPC Priority 3: the base address of GPTBR_EL3 exceeds PPS. */
383     tableaddr = env->cp15.gptbr_el3 << 12;
384     if (tableaddr & ~pps_mask) {
385         goto fault_size;
386     }
387 
388     /*
389      * BADDR is aligned per a function of PPS and L0GPTSZ.
390      * These bits of GPTBR_EL3 are RES0, but are not a configuration error,
391      * unlike the RES0 bits of the GPT entries (R_XNKFZ).
392      */
393     align = MAX(pps - l0gptsz + 3, 12);
394     align = MAKE_64BIT_MASK(0, align);
395     tableaddr &= ~align;
396 
397     as = arm_addressspace(env_cpu(env), attrs);
398 
399     /* Level 0 lookup. */
400     index = extract64(paddress, l0gptsz, pps - l0gptsz);
401     tableaddr += index * 8;
402     entry = address_space_ldq_le(as, tableaddr, attrs, &result);
403     if (result != MEMTX_OK) {
404         goto fault_eabt;
405     }
406 
407     switch (extract32(entry, 0, 4)) {
408     case 1: /* block descriptor */
409         if (entry >> 8) {
410             goto fault_walk; /* RES0 bits not 0 */
411         }
412         gpi = extract32(entry, 4, 4);
413         goto found;
414     case 3: /* table descriptor */
415         tableaddr = entry & ~0xf;
416         align = MAX(l0gptsz - pgs - 1, 12);
417         align = MAKE_64BIT_MASK(0, align);
418         if (tableaddr & (~pps_mask | align)) {
419             goto fault_walk; /* RES0 bits not 0 */
420         }
421         break;
422     default: /* invalid */
423         goto fault_walk;
424     }
425 
426     /* Level 1 lookup */
427     level = 1;
428     index = extract64(paddress, pgs + 4, l0gptsz - pgs - 4);
429     tableaddr += index * 8;
430     entry = address_space_ldq_le(as, tableaddr, attrs, &result);
431     if (result != MEMTX_OK) {
432         goto fault_eabt;
433     }
434 
435     switch (extract32(entry, 0, 4)) {
436     case 1: /* contiguous descriptor */
437         if (entry >> 10) {
438             goto fault_walk; /* RES0 bits not 0 */
439         }
440         /*
441          * Because the softmmu tlb only works on units of TARGET_PAGE_SIZE,
442          * and because we cannot invalidate by pa, and thus will always
443          * flush entire tlbs, we don't actually care about the range here
444          * and can simply extract the GPI as the result.
445          */
446         if (extract32(entry, 8, 2) == 0) {
447             goto fault_walk; /* reserved contig */
448         }
449         gpi = extract32(entry, 4, 4);
450         break;
451     default:
452         index = extract64(paddress, pgs, 4);
453         gpi = extract64(entry, index * 4, 4);
454         break;
455     }
456 
457  found:
458     switch (gpi) {
459     case 0b0000: /* no access */
460         break;
461     case 0b1111: /* all access */
462         return true;
463     case 0b1000:
464     case 0b1001:
465     case 0b1010:
466     case 0b1011:
467         if (pspace == (gpi & 3)) {
468             return true;
469         }
470         break;
471     default:
472         goto fault_walk; /* reserved */
473     }
474 
475     fi->gpcf = GPCF_Fail;
476     goto fault_common;
477  fault_eabt:
478     fi->gpcf = GPCF_EABT;
479     goto fault_common;
480  fault_size:
481     fi->gpcf = GPCF_AddressSize;
482     goto fault_common;
483  fault_walk:
484     fi->gpcf = GPCF_Walk;
485  fault_common:
486     fi->level = level;
487     fi->paddr = paddress;
488     fi->paddr_space = pspace;
489     return false;
490 }
491 
492 static bool S1_attrs_are_device(uint8_t attrs)
493 {
494     /*
495      * This slightly under-decodes the MAIR_ELx field:
496      * 0b0000dd01 is Device with FEAT_XS, otherwise UNPREDICTABLE;
497      * 0b0000dd1x is UNPREDICTABLE.
498      */
499     return (attrs & 0xf0) == 0;
500 }
501 
502 static bool S2_attrs_are_device(uint64_t hcr, uint8_t attrs)
503 {
504     /*
505      * For an S1 page table walk, the stage 1 attributes are always
506      * some form of "this is Normal memory". The combined S1+S2
507      * attributes are therefore only Device if stage 2 specifies Device.
508      * With HCR_EL2.FWB == 0 this is when descriptor bits [5:4] are 0b00,
509      * ie when cacheattrs.attrs bits [3:2] are 0b00.
510      * With HCR_EL2.FWB == 1 this is when descriptor bit [4] is 0, ie
511      * when cacheattrs.attrs bit [2] is 0.
512      */
513     if (hcr & HCR_FWB) {
514         return (attrs & 0x4) == 0;
515     } else {
516         return (attrs & 0xc) == 0;
517     }
518 }
519 
520 static ARMSecuritySpace S2_security_space(ARMSecuritySpace s1_space,
521                                           ARMMMUIdx s2_mmu_idx)
522 {
523     /*
524      * Return the security space to use for stage 2 when doing
525      * the S1 page table descriptor load.
526      */
527     if (regime_is_stage2(s2_mmu_idx)) {
528         /*
529          * The security space for ptw reads is almost always the same
530          * as that of the security space of the stage 1 translation.
531          * The only exception is when stage 1 is Secure; in that case
532          * the ptw read might be to the Secure or the NonSecure space
533          * (but never Realm or Root), and the s2_mmu_idx tells us which.
534          * Root translations are always single-stage.
535          */
536         if (s1_space == ARMSS_Secure) {
537             return arm_secure_to_space(s2_mmu_idx == ARMMMUIdx_Stage2_S);
538         } else {
539             assert(s2_mmu_idx != ARMMMUIdx_Stage2_S);
540             assert(s1_space != ARMSS_Root);
541             return s1_space;
542         }
543     } else {
544         /* ptw loads are from phys: the mmu idx itself says which space */
545         return arm_phys_to_space(s2_mmu_idx);
546     }
547 }
548 
549 static bool fault_s1ns(ARMSecuritySpace space, ARMMMUIdx s2_mmu_idx)
550 {
551     /*
552      * For stage 2 faults in Secure EL22, S1NS indicates
553      * whether the faulting IPA is in the Secure or NonSecure
554      * IPA space. For all other kinds of fault, it is false.
555      */
556     return space == ARMSS_Secure && regime_is_stage2(s2_mmu_idx)
557         && s2_mmu_idx == ARMMMUIdx_Stage2_S;
558 }
559 
560 /* Translate a S1 pagetable walk through S2 if needed.  */
561 static bool S1_ptw_translate(CPUARMState *env, S1Translate *ptw,
562                              hwaddr addr, ARMMMUFaultInfo *fi)
563 {
564     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
565     ARMMMUIdx s2_mmu_idx = ptw->in_ptw_idx;
566     uint8_t pte_attrs;
567 
568     ptw->out_virt = addr;
569 
570     if (unlikely(ptw->in_debug)) {
571         /*
572          * From gdbstub, do not use softmmu so that we don't modify the
573          * state of the cpu at all, including softmmu tlb contents.
574          */
575         ARMSecuritySpace s2_space = S2_security_space(ptw->in_space, s2_mmu_idx);
576         S1Translate s2ptw = {
577             .in_mmu_idx = s2_mmu_idx,
578             .in_ptw_idx = ptw_idx_for_stage_2(env, s2_mmu_idx),
579             .in_space = s2_space,
580             .in_debug = true,
581         };
582         GetPhysAddrResult s2 = { };
583 
584         if (get_phys_addr_gpc(env, &s2ptw, addr, MMU_DATA_LOAD, 0, &s2, fi)) {
585             goto fail;
586         }
587 
588         ptw->out_phys = s2.f.phys_addr;
589         pte_attrs = s2.cacheattrs.attrs;
590         ptw->out_host = NULL;
591         ptw->out_rw = false;
592         ptw->out_space = s2.f.attrs.space;
593     } else {
594 #ifdef CONFIG_TCG
595         CPUTLBEntryFull *full;
596         int flags;
597 
598         env->tlb_fi = fi;
599         flags = probe_access_full_mmu(env, addr, 0, MMU_DATA_LOAD,
600                                       arm_to_core_mmu_idx(s2_mmu_idx),
601                                       &ptw->out_host, &full);
602         env->tlb_fi = NULL;
603 
604         if (unlikely(flags & TLB_INVALID_MASK)) {
605             goto fail;
606         }
607         ptw->out_phys = full->phys_addr | (addr & ~TARGET_PAGE_MASK);
608         ptw->out_rw = full->prot & PAGE_WRITE;
609         pte_attrs = full->extra.arm.pte_attrs;
610         ptw->out_space = full->attrs.space;
611 #else
612         g_assert_not_reached();
613 #endif
614     }
615 
616     if (regime_is_stage2(s2_mmu_idx)) {
617         uint64_t hcr = arm_hcr_el2_eff_secstate(env, ptw->in_space);
618 
619         if ((hcr & HCR_PTW) && S2_attrs_are_device(hcr, pte_attrs)) {
620             /*
621              * PTW set and S1 walk touched S2 Device memory:
622              * generate Permission fault.
623              */
624             fi->type = ARMFault_Permission;
625             fi->s2addr = addr;
626             fi->stage2 = true;
627             fi->s1ptw = true;
628             fi->s1ns = fault_s1ns(ptw->in_space, s2_mmu_idx);
629             return false;
630         }
631     }
632 
633     ptw->out_be = regime_translation_big_endian(env, mmu_idx);
634     return true;
635 
636  fail:
637     assert(fi->type != ARMFault_None);
638     if (fi->type == ARMFault_GPCFOnOutput) {
639         fi->type = ARMFault_GPCFOnWalk;
640     }
641     fi->s2addr = addr;
642     fi->stage2 = regime_is_stage2(s2_mmu_idx);
643     fi->s1ptw = fi->stage2;
644     fi->s1ns = fault_s1ns(ptw->in_space, s2_mmu_idx);
645     return false;
646 }
647 
648 /* All loads done in the course of a page table walk go through here. */
649 static uint32_t arm_ldl_ptw(CPUARMState *env, S1Translate *ptw,
650                             ARMMMUFaultInfo *fi)
651 {
652     CPUState *cs = env_cpu(env);
653     void *host = ptw->out_host;
654     uint32_t data;
655 
656     if (likely(host)) {
657         /* Page tables are in RAM, and we have the host address. */
658         data = qatomic_read((uint32_t *)host);
659         if (ptw->out_be) {
660             data = be32_to_cpu(data);
661         } else {
662             data = le32_to_cpu(data);
663         }
664     } else {
665         /* Page tables are in MMIO. */
666         MemTxAttrs attrs = {
667             .space = ptw->out_space,
668             .secure = arm_space_is_secure(ptw->out_space),
669         };
670         AddressSpace *as = arm_addressspace(cs, attrs);
671         MemTxResult result = MEMTX_OK;
672 
673         if (ptw->out_be) {
674             data = address_space_ldl_be(as, ptw->out_phys, attrs, &result);
675         } else {
676             data = address_space_ldl_le(as, ptw->out_phys, attrs, &result);
677         }
678         if (unlikely(result != MEMTX_OK)) {
679             fi->type = ARMFault_SyncExternalOnWalk;
680             fi->ea = arm_extabort_type(result);
681             return 0;
682         }
683     }
684     return data;
685 }
686 
687 static uint64_t arm_ldq_ptw(CPUARMState *env, S1Translate *ptw,
688                             ARMMMUFaultInfo *fi)
689 {
690     CPUState *cs = env_cpu(env);
691     void *host = ptw->out_host;
692     uint64_t data;
693 
694     if (likely(host)) {
695         /* Page tables are in RAM, and we have the host address. */
696 #ifdef CONFIG_ATOMIC64
697         data = qatomic_read__nocheck((uint64_t *)host);
698         if (ptw->out_be) {
699             data = be64_to_cpu(data);
700         } else {
701             data = le64_to_cpu(data);
702         }
703 #else
704         if (ptw->out_be) {
705             data = ldq_be_p(host);
706         } else {
707             data = ldq_le_p(host);
708         }
709 #endif
710     } else {
711         /* Page tables are in MMIO. */
712         MemTxAttrs attrs = {
713             .space = ptw->out_space,
714             .secure = arm_space_is_secure(ptw->out_space),
715         };
716         AddressSpace *as = arm_addressspace(cs, attrs);
717         MemTxResult result = MEMTX_OK;
718 
719         if (ptw->out_be) {
720             data = address_space_ldq_be(as, ptw->out_phys, attrs, &result);
721         } else {
722             data = address_space_ldq_le(as, ptw->out_phys, attrs, &result);
723         }
724         if (unlikely(result != MEMTX_OK)) {
725             fi->type = ARMFault_SyncExternalOnWalk;
726             fi->ea = arm_extabort_type(result);
727             return 0;
728         }
729     }
730     return data;
731 }
732 
733 static uint64_t arm_casq_ptw(CPUARMState *env, uint64_t old_val,
734                              uint64_t new_val, S1Translate *ptw,
735                              ARMMMUFaultInfo *fi)
736 {
737 #if defined(TARGET_AARCH64) && defined(CONFIG_TCG)
738     uint64_t cur_val;
739     void *host = ptw->out_host;
740 
741     if (unlikely(!host)) {
742         /* Page table in MMIO Memory Region */
743         CPUState *cs = env_cpu(env);
744         MemTxAttrs attrs = {
745             .space = ptw->out_space,
746             .secure = arm_space_is_secure(ptw->out_space),
747         };
748         AddressSpace *as = arm_addressspace(cs, attrs);
749         MemTxResult result = MEMTX_OK;
750         bool need_lock = !bql_locked();
751 
752         if (need_lock) {
753             bql_lock();
754         }
755         if (ptw->out_be) {
756             cur_val = address_space_ldq_be(as, ptw->out_phys, attrs, &result);
757             if (unlikely(result != MEMTX_OK)) {
758                 fi->type = ARMFault_SyncExternalOnWalk;
759                 fi->ea = arm_extabort_type(result);
760                 if (need_lock) {
761                     bql_unlock();
762                 }
763                 return old_val;
764             }
765             if (cur_val == old_val) {
766                 address_space_stq_be(as, ptw->out_phys, new_val, attrs, &result);
767                 if (unlikely(result != MEMTX_OK)) {
768                     fi->type = ARMFault_SyncExternalOnWalk;
769                     fi->ea = arm_extabort_type(result);
770                     if (need_lock) {
771                         bql_unlock();
772                     }
773                     return old_val;
774                 }
775                 cur_val = new_val;
776             }
777         } else {
778             cur_val = address_space_ldq_le(as, ptw->out_phys, attrs, &result);
779             if (unlikely(result != MEMTX_OK)) {
780                 fi->type = ARMFault_SyncExternalOnWalk;
781                 fi->ea = arm_extabort_type(result);
782                 if (need_lock) {
783                     bql_unlock();
784                 }
785                 return old_val;
786             }
787             if (cur_val == old_val) {
788                 address_space_stq_le(as, ptw->out_phys, new_val, attrs, &result);
789                 if (unlikely(result != MEMTX_OK)) {
790                     fi->type = ARMFault_SyncExternalOnWalk;
791                     fi->ea = arm_extabort_type(result);
792                     if (need_lock) {
793                         bql_unlock();
794                     }
795                     return old_val;
796                 }
797                 cur_val = new_val;
798             }
799         }
800         if (need_lock) {
801             bql_unlock();
802         }
803         return cur_val;
804     }
805 
806     /*
807      * Raising a stage2 Protection fault for an atomic update to a read-only
808      * page is delayed until it is certain that there is a change to make.
809      */
810     if (unlikely(!ptw->out_rw)) {
811         int flags;
812 
813         env->tlb_fi = fi;
814         flags = probe_access_full_mmu(env, ptw->out_virt, 0,
815                                       MMU_DATA_STORE,
816                                       arm_to_core_mmu_idx(ptw->in_ptw_idx),
817                                       NULL, NULL);
818         env->tlb_fi = NULL;
819 
820         if (unlikely(flags & TLB_INVALID_MASK)) {
821             /*
822              * We know this must be a stage 2 fault because the granule
823              * protection table does not separately track read and write
824              * permission, so all GPC faults are caught in S1_ptw_translate():
825              * we only get here for "readable but not writeable".
826              */
827             assert(fi->type != ARMFault_None);
828             fi->s2addr = ptw->out_virt;
829             fi->stage2 = true;
830             fi->s1ptw = true;
831             fi->s1ns = fault_s1ns(ptw->in_space, ptw->in_ptw_idx);
832             return 0;
833         }
834 
835         /* In case CAS mismatches and we loop, remember writability. */
836         ptw->out_rw = true;
837     }
838 
839 #ifdef CONFIG_ATOMIC64
840     if (ptw->out_be) {
841         old_val = cpu_to_be64(old_val);
842         new_val = cpu_to_be64(new_val);
843         cur_val = qatomic_cmpxchg__nocheck((uint64_t *)host, old_val, new_val);
844         cur_val = be64_to_cpu(cur_val);
845     } else {
846         old_val = cpu_to_le64(old_val);
847         new_val = cpu_to_le64(new_val);
848         cur_val = qatomic_cmpxchg__nocheck((uint64_t *)host, old_val, new_val);
849         cur_val = le64_to_cpu(cur_val);
850     }
851 #else
852     /*
853      * We can't support the full 64-bit atomic cmpxchg on the host.
854      * Because this is only used for FEAT_HAFDBS, which is only for AA64,
855      * we know that TCG_OVERSIZED_GUEST is set, which means that we are
856      * running in round-robin mode and could only race with dma i/o.
857      */
858 #if !TCG_OVERSIZED_GUEST
859 # error "Unexpected configuration"
860 #endif
861     bool locked = bql_locked();
862     if (!locked) {
863         bql_lock();
864     }
865     if (ptw->out_be) {
866         cur_val = ldq_be_p(host);
867         if (cur_val == old_val) {
868             stq_be_p(host, new_val);
869         }
870     } else {
871         cur_val = ldq_le_p(host);
872         if (cur_val == old_val) {
873             stq_le_p(host, new_val);
874         }
875     }
876     if (!locked) {
877         bql_unlock();
878     }
879 #endif
880 
881     return cur_val;
882 #else
883     /* AArch32 does not have FEAT_HADFS; non-TCG guests only use debug-mode. */
884     g_assert_not_reached();
885 #endif
886 }
887 
888 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
889                                      uint32_t *table, uint32_t address)
890 {
891     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
892     uint64_t tcr = regime_tcr(env, mmu_idx);
893     int maskshift = extract32(tcr, 0, 3);
894     uint32_t mask = ~(((uint32_t)0xffffffffu) >> maskshift);
895     uint32_t base_mask;
896 
897     if (address & mask) {
898         if (tcr & TTBCR_PD1) {
899             /* Translation table walk disabled for TTBR1 */
900             return false;
901         }
902         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
903     } else {
904         if (tcr & TTBCR_PD0) {
905             /* Translation table walk disabled for TTBR0 */
906             return false;
907         }
908         base_mask = ~((uint32_t)0x3fffu >> maskshift);
909         *table = regime_ttbr(env, mmu_idx, 0) & base_mask;
910     }
911     *table |= (address >> 18) & 0x3ffc;
912     return true;
913 }
914 
915 /*
916  * Translate section/page access permissions to page R/W protection flags
917  * @env:         CPUARMState
918  * @mmu_idx:     MMU index indicating required translation regime
919  * @ap:          The 3-bit access permissions (AP[2:0])
920  * @domain_prot: The 2-bit domain access permissions
921  * @is_user: TRUE if accessing from PL0
922  */
923 static int ap_to_rw_prot_is_user(CPUARMState *env, ARMMMUIdx mmu_idx,
924                          int ap, int domain_prot, bool is_user)
925 {
926     if (domain_prot == 3) {
927         return PAGE_READ | PAGE_WRITE;
928     }
929 
930     switch (ap) {
931     case 0:
932         if (arm_feature(env, ARM_FEATURE_V7)) {
933             return 0;
934         }
935         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
936         case SCTLR_S:
937             return is_user ? 0 : PAGE_READ;
938         case SCTLR_R:
939             return PAGE_READ;
940         default:
941             return 0;
942         }
943     case 1:
944         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
945     case 2:
946         if (is_user) {
947             return PAGE_READ;
948         } else {
949             return PAGE_READ | PAGE_WRITE;
950         }
951     case 3:
952         return PAGE_READ | PAGE_WRITE;
953     case 4: /* Reserved.  */
954         return 0;
955     case 5:
956         return is_user ? 0 : PAGE_READ;
957     case 6:
958         return PAGE_READ;
959     case 7:
960         if (!arm_feature(env, ARM_FEATURE_V6K)) {
961             return 0;
962         }
963         return PAGE_READ;
964     default:
965         g_assert_not_reached();
966     }
967 }
968 
969 /*
970  * Translate section/page access permissions to page R/W protection flags
971  * @env:         CPUARMState
972  * @mmu_idx:     MMU index indicating required translation regime
973  * @ap:          The 3-bit access permissions (AP[2:0])
974  * @domain_prot: The 2-bit domain access permissions
975  */
976 static int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
977                          int ap, int domain_prot)
978 {
979    return ap_to_rw_prot_is_user(env, mmu_idx, ap, domain_prot,
980                                 regime_is_user(env, mmu_idx));
981 }
982 
983 /*
984  * Translate section/page access permissions to page R/W protection flags.
985  * @ap:      The 2-bit simple AP (AP[2:1])
986  * @is_user: TRUE if accessing from PL0
987  */
988 static int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
989 {
990     switch (ap) {
991     case 0:
992         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
993     case 1:
994         return PAGE_READ | PAGE_WRITE;
995     case 2:
996         return is_user ? 0 : PAGE_READ;
997     case 3:
998         return PAGE_READ;
999     default:
1000         g_assert_not_reached();
1001     }
1002 }
1003 
1004 static int simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
1005 {
1006     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
1007 }
1008 
1009 static bool get_phys_addr_v5(CPUARMState *env, S1Translate *ptw,
1010                              uint32_t address, MMUAccessType access_type,
1011                              GetPhysAddrResult *result, ARMMMUFaultInfo *fi)
1012 {
1013     int level = 1;
1014     uint32_t table;
1015     uint32_t desc;
1016     int type;
1017     int ap;
1018     int domain = 0;
1019     int domain_prot;
1020     hwaddr phys_addr;
1021     uint32_t dacr;
1022 
1023     /* Pagetable walk.  */
1024     /* Lookup l1 descriptor.  */
1025     if (!get_level1_table_address(env, ptw->in_mmu_idx, &table, address)) {
1026         /* Section translation fault if page walk is disabled by PD0 or PD1 */
1027         fi->type = ARMFault_Translation;
1028         goto do_fault;
1029     }
1030     if (!S1_ptw_translate(env, ptw, table, fi)) {
1031         goto do_fault;
1032     }
1033     desc = arm_ldl_ptw(env, ptw, fi);
1034     if (fi->type != ARMFault_None) {
1035         goto do_fault;
1036     }
1037     type = (desc & 3);
1038     domain = (desc >> 5) & 0x0f;
1039     if (regime_el(env, ptw->in_mmu_idx) == 1) {
1040         dacr = env->cp15.dacr_ns;
1041     } else {
1042         dacr = env->cp15.dacr_s;
1043     }
1044     domain_prot = (dacr >> (domain * 2)) & 3;
1045     if (type == 0) {
1046         /* Section translation fault.  */
1047         fi->type = ARMFault_Translation;
1048         goto do_fault;
1049     }
1050     if (type != 2) {
1051         level = 2;
1052     }
1053     if (domain_prot == 0 || domain_prot == 2) {
1054         fi->type = ARMFault_Domain;
1055         goto do_fault;
1056     }
1057     if (type == 2) {
1058         /* 1Mb section.  */
1059         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
1060         ap = (desc >> 10) & 3;
1061         result->f.lg_page_size = 20; /* 1MB */
1062     } else {
1063         /* Lookup l2 entry.  */
1064         if (type == 1) {
1065             /* Coarse pagetable.  */
1066             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
1067         } else {
1068             /* Fine pagetable.  */
1069             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
1070         }
1071         if (!S1_ptw_translate(env, ptw, table, fi)) {
1072             goto do_fault;
1073         }
1074         desc = arm_ldl_ptw(env, ptw, fi);
1075         if (fi->type != ARMFault_None) {
1076             goto do_fault;
1077         }
1078         switch (desc & 3) {
1079         case 0: /* Page translation fault.  */
1080             fi->type = ARMFault_Translation;
1081             goto do_fault;
1082         case 1: /* 64k page.  */
1083             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
1084             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
1085             result->f.lg_page_size = 16;
1086             break;
1087         case 2: /* 4k page.  */
1088             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
1089             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
1090             result->f.lg_page_size = 12;
1091             break;
1092         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
1093             if (type == 1) {
1094                 /* ARMv6/XScale extended small page format */
1095                 if (arm_feature(env, ARM_FEATURE_XSCALE)
1096                     || arm_feature(env, ARM_FEATURE_V6)) {
1097                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
1098                     result->f.lg_page_size = 12;
1099                 } else {
1100                     /*
1101                      * UNPREDICTABLE in ARMv5; we choose to take a
1102                      * page translation fault.
1103                      */
1104                     fi->type = ARMFault_Translation;
1105                     goto do_fault;
1106                 }
1107             } else {
1108                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
1109                 result->f.lg_page_size = 10;
1110             }
1111             ap = (desc >> 4) & 3;
1112             break;
1113         default:
1114             /* Never happens, but compiler isn't smart enough to tell.  */
1115             g_assert_not_reached();
1116         }
1117     }
1118     result->f.prot = ap_to_rw_prot(env, ptw->in_mmu_idx, ap, domain_prot);
1119     result->f.prot |= result->f.prot ? PAGE_EXEC : 0;
1120     if (!(result->f.prot & (1 << access_type))) {
1121         /* Access permission fault.  */
1122         fi->type = ARMFault_Permission;
1123         goto do_fault;
1124     }
1125     result->f.phys_addr = phys_addr;
1126     return false;
1127 do_fault:
1128     fi->domain = domain;
1129     fi->level = level;
1130     return true;
1131 }
1132 
1133 static bool get_phys_addr_v6(CPUARMState *env, S1Translate *ptw,
1134                              uint32_t address, MMUAccessType access_type,
1135                              GetPhysAddrResult *result, ARMMMUFaultInfo *fi)
1136 {
1137     ARMCPU *cpu = env_archcpu(env);
1138     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
1139     int level = 1;
1140     uint32_t table;
1141     uint32_t desc;
1142     uint32_t xn;
1143     uint32_t pxn = 0;
1144     int type;
1145     int ap;
1146     int domain = 0;
1147     int domain_prot;
1148     hwaddr phys_addr;
1149     uint32_t dacr;
1150     bool ns;
1151     int user_prot;
1152 
1153     /* Pagetable walk.  */
1154     /* Lookup l1 descriptor.  */
1155     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
1156         /* Section translation fault if page walk is disabled by PD0 or PD1 */
1157         fi->type = ARMFault_Translation;
1158         goto do_fault;
1159     }
1160     if (!S1_ptw_translate(env, ptw, table, fi)) {
1161         goto do_fault;
1162     }
1163     desc = arm_ldl_ptw(env, ptw, fi);
1164     if (fi->type != ARMFault_None) {
1165         goto do_fault;
1166     }
1167     type = (desc & 3);
1168     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
1169         /* Section translation fault, or attempt to use the encoding
1170          * which is Reserved on implementations without PXN.
1171          */
1172         fi->type = ARMFault_Translation;
1173         goto do_fault;
1174     }
1175     if ((type == 1) || !(desc & (1 << 18))) {
1176         /* Page or Section.  */
1177         domain = (desc >> 5) & 0x0f;
1178     }
1179     if (regime_el(env, mmu_idx) == 1) {
1180         dacr = env->cp15.dacr_ns;
1181     } else {
1182         dacr = env->cp15.dacr_s;
1183     }
1184     if (type == 1) {
1185         level = 2;
1186     }
1187     domain_prot = (dacr >> (domain * 2)) & 3;
1188     if (domain_prot == 0 || domain_prot == 2) {
1189         /* Section or Page domain fault */
1190         fi->type = ARMFault_Domain;
1191         goto do_fault;
1192     }
1193     if (type != 1) {
1194         if (desc & (1 << 18)) {
1195             /* Supersection.  */
1196             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
1197             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
1198             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
1199             result->f.lg_page_size = 24;  /* 16MB */
1200         } else {
1201             /* Section.  */
1202             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
1203             result->f.lg_page_size = 20;  /* 1MB */
1204         }
1205         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
1206         xn = desc & (1 << 4);
1207         pxn = desc & 1;
1208         ns = extract32(desc, 19, 1);
1209     } else {
1210         if (cpu_isar_feature(aa32_pxn, cpu)) {
1211             pxn = (desc >> 2) & 1;
1212         }
1213         ns = extract32(desc, 3, 1);
1214         /* Lookup l2 entry.  */
1215         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
1216         if (!S1_ptw_translate(env, ptw, table, fi)) {
1217             goto do_fault;
1218         }
1219         desc = arm_ldl_ptw(env, ptw, fi);
1220         if (fi->type != ARMFault_None) {
1221             goto do_fault;
1222         }
1223         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
1224         switch (desc & 3) {
1225         case 0: /* Page translation fault.  */
1226             fi->type = ARMFault_Translation;
1227             goto do_fault;
1228         case 1: /* 64k page.  */
1229             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
1230             xn = desc & (1 << 15);
1231             result->f.lg_page_size = 16;
1232             break;
1233         case 2: case 3: /* 4k page.  */
1234             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
1235             xn = desc & 1;
1236             result->f.lg_page_size = 12;
1237             break;
1238         default:
1239             /* Never happens, but compiler isn't smart enough to tell.  */
1240             g_assert_not_reached();
1241         }
1242     }
1243     if (domain_prot == 3) {
1244         result->f.prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
1245     } else {
1246         if (pxn && !regime_is_user(env, mmu_idx)) {
1247             xn = 1;
1248         }
1249         if (xn && access_type == MMU_INST_FETCH) {
1250             fi->type = ARMFault_Permission;
1251             goto do_fault;
1252         }
1253 
1254         if (arm_feature(env, ARM_FEATURE_V6K) &&
1255                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
1256             /* The simplified model uses AP[0] as an access control bit.  */
1257             if ((ap & 1) == 0) {
1258                 /* Access flag fault.  */
1259                 fi->type = ARMFault_AccessFlag;
1260                 goto do_fault;
1261             }
1262             result->f.prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
1263             user_prot = simple_ap_to_rw_prot_is_user(ap >> 1, 1);
1264         } else {
1265             result->f.prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
1266             user_prot = ap_to_rw_prot_is_user(env, mmu_idx, ap, domain_prot, 1);
1267         }
1268         if (result->f.prot && !xn) {
1269             result->f.prot |= PAGE_EXEC;
1270         }
1271         if (!(result->f.prot & (1 << access_type))) {
1272             /* Access permission fault.  */
1273             fi->type = ARMFault_Permission;
1274             goto do_fault;
1275         }
1276         if (regime_is_pan(env, mmu_idx) &&
1277             !regime_is_user(env, mmu_idx) &&
1278             user_prot &&
1279             access_type != MMU_INST_FETCH) {
1280             /* Privileged Access Never fault */
1281             fi->type = ARMFault_Permission;
1282             goto do_fault;
1283         }
1284     }
1285     if (ns) {
1286         /* The NS bit will (as required by the architecture) have no effect if
1287          * the CPU doesn't support TZ or this is a non-secure translation
1288          * regime, because the attribute will already be non-secure.
1289          */
1290         result->f.attrs.secure = false;
1291         result->f.attrs.space = ARMSS_NonSecure;
1292     }
1293     result->f.phys_addr = phys_addr;
1294     return false;
1295 do_fault:
1296     fi->domain = domain;
1297     fi->level = level;
1298     return true;
1299 }
1300 
1301 /*
1302  * Translate S2 section/page access permissions to protection flags
1303  * @env:     CPUARMState
1304  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
1305  * @xn:      XN (execute-never) bits
1306  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
1307  */
1308 static int get_S2prot_noexecute(int s2ap)
1309 {
1310     int prot = 0;
1311 
1312     if (s2ap & 1) {
1313         prot |= PAGE_READ;
1314     }
1315     if (s2ap & 2) {
1316         prot |= PAGE_WRITE;
1317     }
1318     return prot;
1319 }
1320 
1321 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
1322 {
1323     int prot = get_S2prot_noexecute(s2ap);
1324 
1325     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
1326         switch (xn) {
1327         case 0:
1328             prot |= PAGE_EXEC;
1329             break;
1330         case 1:
1331             if (s1_is_el0) {
1332                 prot |= PAGE_EXEC;
1333             }
1334             break;
1335         case 2:
1336             break;
1337         case 3:
1338             if (!s1_is_el0) {
1339                 prot |= PAGE_EXEC;
1340             }
1341             break;
1342         default:
1343             g_assert_not_reached();
1344         }
1345     } else {
1346         if (!extract32(xn, 1, 1)) {
1347             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
1348                 prot |= PAGE_EXEC;
1349             }
1350         }
1351     }
1352     return prot;
1353 }
1354 
1355 /*
1356  * Translate section/page access permissions to protection flags
1357  * @env:     CPUARMState
1358  * @mmu_idx: MMU index indicating required translation regime
1359  * @is_aa64: TRUE if AArch64
1360  * @ap:      The 2-bit simple AP (AP[2:1])
1361  * @xn:      XN (execute-never) bit
1362  * @pxn:     PXN (privileged execute-never) bit
1363  * @in_pa:   The original input pa space
1364  * @out_pa:  The output pa space, modified by NSTable, NS, and NSE
1365  */
1366 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
1367                       int ap, int xn, int pxn,
1368                       ARMSecuritySpace in_pa, ARMSecuritySpace out_pa)
1369 {
1370     ARMCPU *cpu = env_archcpu(env);
1371     bool is_user = regime_is_user(env, mmu_idx);
1372     int prot_rw, user_rw;
1373     bool have_wxn;
1374     int wxn = 0;
1375 
1376     assert(!regime_is_stage2(mmu_idx));
1377 
1378     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
1379     if (is_user) {
1380         prot_rw = user_rw;
1381     } else {
1382         /*
1383          * PAN controls can forbid data accesses but don't affect insn fetch.
1384          * Plain PAN forbids data accesses if EL0 has data permissions;
1385          * PAN3 forbids data accesses if EL0 has either data or exec perms.
1386          * Note that for AArch64 the 'user can exec' case is exactly !xn.
1387          * We make the IMPDEF choices that SCR_EL3.SIF and Realm EL2&0
1388          * do not affect EPAN.
1389          */
1390         if (user_rw && regime_is_pan(env, mmu_idx)) {
1391             prot_rw = 0;
1392         } else if (cpu_isar_feature(aa64_pan3, cpu) && is_aa64 &&
1393                    regime_is_pan(env, mmu_idx) &&
1394                    (regime_sctlr(env, mmu_idx) & SCTLR_EPAN) && !xn) {
1395             prot_rw = 0;
1396         } else {
1397             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
1398         }
1399     }
1400 
1401     if (in_pa != out_pa) {
1402         switch (in_pa) {
1403         case ARMSS_Root:
1404             /*
1405              * R_ZWRVD: permission fault for insn fetched from non-Root,
1406              * I_WWBFB: SIF has no effect in EL3.
1407              */
1408             return prot_rw;
1409         case ARMSS_Realm:
1410             /*
1411              * R_PKTDS: permission fault for insn fetched from non-Realm,
1412              * for Realm EL2 or EL2&0.  The corresponding fault for EL1&0
1413              * happens during any stage2 translation.
1414              */
1415             switch (mmu_idx) {
1416             case ARMMMUIdx_E2:
1417             case ARMMMUIdx_E20_0:
1418             case ARMMMUIdx_E20_2:
1419             case ARMMMUIdx_E20_2_PAN:
1420                 return prot_rw;
1421             default:
1422                 break;
1423             }
1424             break;
1425         case ARMSS_Secure:
1426             if (env->cp15.scr_el3 & SCR_SIF) {
1427                 return prot_rw;
1428             }
1429             break;
1430         default:
1431             /* Input NonSecure must have output NonSecure. */
1432             g_assert_not_reached();
1433         }
1434     }
1435 
1436     /* TODO have_wxn should be replaced with
1437      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
1438      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
1439      * compatible processors have EL2, which is required for [U]WXN.
1440      */
1441     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
1442 
1443     if (have_wxn) {
1444         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
1445     }
1446 
1447     if (is_aa64) {
1448         if (regime_has_2_ranges(mmu_idx) && !is_user) {
1449             xn = pxn || (user_rw & PAGE_WRITE);
1450         }
1451     } else if (arm_feature(env, ARM_FEATURE_V7)) {
1452         switch (regime_el(env, mmu_idx)) {
1453         case 1:
1454         case 3:
1455             if (is_user) {
1456                 xn = xn || !(user_rw & PAGE_READ);
1457             } else {
1458                 int uwxn = 0;
1459                 if (have_wxn) {
1460                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
1461                 }
1462                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
1463                      (uwxn && (user_rw & PAGE_WRITE));
1464             }
1465             break;
1466         case 2:
1467             break;
1468         }
1469     } else {
1470         xn = wxn = 0;
1471     }
1472 
1473     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
1474         return prot_rw;
1475     }
1476     return prot_rw | PAGE_EXEC;
1477 }
1478 
1479 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
1480                                           ARMMMUIdx mmu_idx)
1481 {
1482     uint64_t tcr = regime_tcr(env, mmu_idx);
1483     uint32_t el = regime_el(env, mmu_idx);
1484     int select, tsz;
1485     bool epd, hpd;
1486 
1487     assert(mmu_idx != ARMMMUIdx_Stage2_S);
1488 
1489     if (mmu_idx == ARMMMUIdx_Stage2) {
1490         /* VTCR */
1491         bool sext = extract32(tcr, 4, 1);
1492         bool sign = extract32(tcr, 3, 1);
1493 
1494         /*
1495          * If the sign-extend bit is not the same as t0sz[3], the result
1496          * is unpredictable. Flag this as a guest error.
1497          */
1498         if (sign != sext) {
1499             qemu_log_mask(LOG_GUEST_ERROR,
1500                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
1501         }
1502         tsz = sextract32(tcr, 0, 4) + 8;
1503         select = 0;
1504         hpd = false;
1505         epd = false;
1506     } else if (el == 2) {
1507         /* HTCR */
1508         tsz = extract32(tcr, 0, 3);
1509         select = 0;
1510         hpd = extract64(tcr, 24, 1);
1511         epd = false;
1512     } else {
1513         int t0sz = extract32(tcr, 0, 3);
1514         int t1sz = extract32(tcr, 16, 3);
1515 
1516         if (t1sz == 0) {
1517             select = va > (0xffffffffu >> t0sz);
1518         } else {
1519             /* Note that we will detect errors later.  */
1520             select = va >= ~(0xffffffffu >> t1sz);
1521         }
1522         if (!select) {
1523             tsz = t0sz;
1524             epd = extract32(tcr, 7, 1);
1525             hpd = extract64(tcr, 41, 1);
1526         } else {
1527             tsz = t1sz;
1528             epd = extract32(tcr, 23, 1);
1529             hpd = extract64(tcr, 42, 1);
1530         }
1531         /* For aarch32, hpd0 is not enabled without t2e as well.  */
1532         hpd &= extract32(tcr, 6, 1);
1533     }
1534 
1535     return (ARMVAParameters) {
1536         .tsz = tsz,
1537         .select = select,
1538         .epd = epd,
1539         .hpd = hpd,
1540     };
1541 }
1542 
1543 /*
1544  * check_s2_mmu_setup
1545  * @cpu:        ARMCPU
1546  * @is_aa64:    True if the translation regime is in AArch64 state
1547  * @tcr:        VTCR_EL2 or VSTCR_EL2
1548  * @ds:         Effective value of TCR.DS.
1549  * @iasize:     Bitsize of IPAs
1550  * @stride:     Page-table stride (See the ARM ARM)
1551  *
1552  * Decode the starting level of the S2 lookup, returning INT_MIN if
1553  * the configuration is invalid.
1554  */
1555 static int check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, uint64_t tcr,
1556                               bool ds, int iasize, int stride)
1557 {
1558     int sl0, sl2, startlevel, granulebits, levels;
1559     int s1_min_iasize, s1_max_iasize;
1560 
1561     sl0 = extract32(tcr, 6, 2);
1562     if (is_aa64) {
1563         /*
1564          * AArch64.S2InvalidSL: Interpretation of SL depends on the page size,
1565          * so interleave AArch64.S2StartLevel.
1566          */
1567         switch (stride) {
1568         case 9: /* 4KB */
1569             /* SL2 is RES0 unless DS=1 & 4KB granule. */
1570             sl2 = extract64(tcr, 33, 1);
1571             if (ds && sl2) {
1572                 if (sl0 != 0) {
1573                     goto fail;
1574                 }
1575                 startlevel = -1;
1576             } else {
1577                 startlevel = 2 - sl0;
1578                 switch (sl0) {
1579                 case 2:
1580                     if (arm_pamax(cpu) < 44) {
1581                         goto fail;
1582                     }
1583                     break;
1584                 case 3:
1585                     if (!cpu_isar_feature(aa64_st, cpu)) {
1586                         goto fail;
1587                     }
1588                     startlevel = 3;
1589                     break;
1590                 }
1591             }
1592             break;
1593         case 11: /* 16KB */
1594             switch (sl0) {
1595             case 2:
1596                 if (arm_pamax(cpu) < 42) {
1597                     goto fail;
1598                 }
1599                 break;
1600             case 3:
1601                 if (!ds) {
1602                     goto fail;
1603                 }
1604                 break;
1605             }
1606             startlevel = 3 - sl0;
1607             break;
1608         case 13: /* 64KB */
1609             switch (sl0) {
1610             case 2:
1611                 if (arm_pamax(cpu) < 44) {
1612                     goto fail;
1613                 }
1614                 break;
1615             case 3:
1616                 goto fail;
1617             }
1618             startlevel = 3 - sl0;
1619             break;
1620         default:
1621             g_assert_not_reached();
1622         }
1623     } else {
1624         /*
1625          * Things are simpler for AArch32 EL2, with only 4k pages.
1626          * There is no separate S2InvalidSL function, but AArch32.S2Walk
1627          * begins with walkparms.sl0 in {'1x'}.
1628          */
1629         assert(stride == 9);
1630         if (sl0 >= 2) {
1631             goto fail;
1632         }
1633         startlevel = 2 - sl0;
1634     }
1635 
1636     /* AArch{64,32}.S2InconsistentSL are functionally equivalent.  */
1637     levels = 3 - startlevel;
1638     granulebits = stride + 3;
1639 
1640     s1_min_iasize = levels * stride + granulebits + 1;
1641     s1_max_iasize = s1_min_iasize + (stride - 1) + 4;
1642 
1643     if (iasize >= s1_min_iasize && iasize <= s1_max_iasize) {
1644         return startlevel;
1645     }
1646 
1647  fail:
1648     return INT_MIN;
1649 }
1650 
1651 static bool lpae_block_desc_valid(ARMCPU *cpu, bool ds,
1652                                   ARMGranuleSize gran, int level)
1653 {
1654     /*
1655      * See pseudocode AArch46.BlockDescSupported(): block descriptors
1656      * are not valid at all levels, depending on the page size.
1657      */
1658     switch (gran) {
1659     case Gran4K:
1660         return (level == 0 && ds) || level == 1 || level == 2;
1661     case Gran16K:
1662         return (level == 1 && ds) || level == 2;
1663     case Gran64K:
1664         return (level == 1 && arm_pamax(cpu) == 52) || level == 2;
1665     default:
1666         g_assert_not_reached();
1667     }
1668 }
1669 
1670 static bool nv_nv1_enabled(CPUARMState *env, S1Translate *ptw)
1671 {
1672     uint64_t hcr = arm_hcr_el2_eff_secstate(env, ptw->in_space);
1673     return (hcr & (HCR_NV | HCR_NV1)) == (HCR_NV | HCR_NV1);
1674 }
1675 
1676 /**
1677  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
1678  *
1679  * Returns false if the translation was successful. Otherwise, phys_ptr,
1680  * attrs, prot and page_size may not be filled in, and the populated fsr
1681  * value provides information on why the translation aborted, in the format
1682  * of a long-format DFSR/IFSR fault register, with the following caveat:
1683  * the WnR bit is never set (the caller must do this).
1684  *
1685  * @env: CPUARMState
1686  * @ptw: Current and next stage parameters for the walk.
1687  * @address: virtual address to get physical address for
1688  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
1689  * @memop: memory operation feeding this access, or 0 for none
1690  * @result: set on translation success,
1691  * @fi: set to fault info if the translation fails
1692  */
1693 static bool get_phys_addr_lpae(CPUARMState *env, S1Translate *ptw,
1694                                uint64_t address,
1695                                MMUAccessType access_type, MemOp memop,
1696                                GetPhysAddrResult *result, ARMMMUFaultInfo *fi)
1697 {
1698     ARMCPU *cpu = env_archcpu(env);
1699     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
1700     int32_t level;
1701     ARMVAParameters param;
1702     uint64_t ttbr;
1703     hwaddr descaddr, indexmask, indexmask_grainsize;
1704     uint32_t tableattrs;
1705     target_ulong page_size;
1706     uint64_t attrs;
1707     int32_t stride;
1708     int addrsize, inputsize, outputsize;
1709     uint64_t tcr = regime_tcr(env, mmu_idx);
1710     int ap, xn, pxn;
1711     uint32_t el = regime_el(env, mmu_idx);
1712     uint64_t descaddrmask;
1713     bool aarch64 = arm_el_is_aa64(env, el);
1714     uint64_t descriptor, new_descriptor;
1715     ARMSecuritySpace out_space;
1716     bool device;
1717 
1718     /* TODO: This code does not support shareability levels. */
1719     if (aarch64) {
1720         int ps;
1721 
1722         param = aa64_va_parameters(env, address, mmu_idx,
1723                                    access_type != MMU_INST_FETCH,
1724                                    !arm_el_is_aa64(env, 1));
1725         level = 0;
1726 
1727         /*
1728          * If TxSZ is programmed to a value larger than the maximum,
1729          * or smaller than the effective minimum, it is IMPLEMENTATION
1730          * DEFINED whether we behave as if the field were programmed
1731          * within bounds, or if a level 0 Translation fault is generated.
1732          *
1733          * With FEAT_LVA, fault on less than minimum becomes required,
1734          * so our choice is to always raise the fault.
1735          */
1736         if (param.tsz_oob) {
1737             goto do_translation_fault;
1738         }
1739 
1740         addrsize = 64 - 8 * param.tbi;
1741         inputsize = 64 - param.tsz;
1742 
1743         /*
1744          * Bound PS by PARANGE to find the effective output address size.
1745          * ID_AA64MMFR0 is a read-only register so values outside of the
1746          * supported mappings can be considered an implementation error.
1747          */
1748         ps = FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
1749         ps = MIN(ps, param.ps);
1750         assert(ps < ARRAY_SIZE(pamax_map));
1751         outputsize = pamax_map[ps];
1752 
1753         /*
1754          * With LPA2, the effective output address (OA) size is at most 48 bits
1755          * unless TCR.DS == 1
1756          */
1757         if (!param.ds && param.gran != Gran64K) {
1758             outputsize = MIN(outputsize, 48);
1759         }
1760     } else {
1761         param = aa32_va_parameters(env, address, mmu_idx);
1762         level = 1;
1763         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
1764         inputsize = addrsize - param.tsz;
1765         outputsize = 40;
1766     }
1767 
1768     /*
1769      * We determined the region when collecting the parameters, but we
1770      * have not yet validated that the address is valid for the region.
1771      * Extract the top bits and verify that they all match select.
1772      *
1773      * For aa32, if inputsize == addrsize, then we have selected the
1774      * region by exclusion in aa32_va_parameters and there is no more
1775      * validation to do here.
1776      */
1777     if (inputsize < addrsize) {
1778         target_ulong top_bits = sextract64(address, inputsize,
1779                                            addrsize - inputsize);
1780         if (-top_bits != param.select) {
1781             /* The gap between the two regions is a Translation fault */
1782             goto do_translation_fault;
1783         }
1784     }
1785 
1786     stride = arm_granule_bits(param.gran) - 3;
1787 
1788     /*
1789      * Note that QEMU ignores shareability and cacheability attributes,
1790      * so we don't need to do anything with the SH, ORGN, IRGN fields
1791      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
1792      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
1793      * implement any ASID-like capability so we can ignore it (instead
1794      * we will always flush the TLB any time the ASID is changed).
1795      */
1796     ttbr = regime_ttbr(env, mmu_idx, param.select);
1797 
1798     /*
1799      * Here we should have set up all the parameters for the translation:
1800      * inputsize, ttbr, epd, stride, tbi
1801      */
1802 
1803     if (param.epd) {
1804         /*
1805          * Translation table walk disabled => Translation fault on TLB miss
1806          * Note: This is always 0 on 64-bit EL2 and EL3.
1807          */
1808         goto do_translation_fault;
1809     }
1810 
1811     if (!regime_is_stage2(mmu_idx)) {
1812         /*
1813          * The starting level depends on the virtual address size (which can
1814          * be up to 48 bits) and the translation granule size. It indicates
1815          * the number of strides (stride bits at a time) needed to
1816          * consume the bits of the input address. In the pseudocode this is:
1817          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
1818          * where their 'inputsize' is our 'inputsize', 'grainsize' is
1819          * our 'stride + 3' and 'stride' is our 'stride'.
1820          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
1821          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
1822          * = 4 - (inputsize - 4) / stride;
1823          */
1824         level = 4 - (inputsize - 4) / stride;
1825     } else {
1826         int startlevel = check_s2_mmu_setup(cpu, aarch64, tcr, param.ds,
1827                                             inputsize, stride);
1828         if (startlevel == INT_MIN) {
1829             level = 0;
1830             goto do_translation_fault;
1831         }
1832         level = startlevel;
1833     }
1834 
1835     indexmask_grainsize = MAKE_64BIT_MASK(0, stride + 3);
1836     indexmask = MAKE_64BIT_MASK(0, inputsize - (stride * (4 - level)));
1837 
1838     /* Now we can extract the actual base address from the TTBR */
1839     descaddr = extract64(ttbr, 0, 48);
1840 
1841     /*
1842      * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [5:2] of TTBR.
1843      *
1844      * Otherwise, if the base address is out of range, raise AddressSizeFault.
1845      * In the pseudocode, this is !IsZero(baseregister<47:outputsize>),
1846      * but we've just cleared the bits above 47, so simplify the test.
1847      */
1848     if (outputsize > 48) {
1849         descaddr |= extract64(ttbr, 2, 4) << 48;
1850     } else if (descaddr >> outputsize) {
1851         level = 0;
1852         fi->type = ARMFault_AddressSize;
1853         goto do_fault;
1854     }
1855 
1856     /*
1857      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
1858      * and also to mask out CnP (bit 0) which could validly be non-zero.
1859      */
1860     descaddr &= ~indexmask;
1861 
1862     /*
1863      * For AArch32, the address field in the descriptor goes up to bit 39
1864      * for both v7 and v8.  However, for v8 the SBZ bits [47:40] must be 0
1865      * or an AddressSize fault is raised.  So for v8 we extract those SBZ
1866      * bits as part of the address, which will be checked via outputsize.
1867      * For AArch64, the address field goes up to bit 47, or 49 with FEAT_LPA2;
1868      * the highest bits of a 52-bit output are placed elsewhere.
1869      */
1870     if (param.ds) {
1871         descaddrmask = MAKE_64BIT_MASK(0, 50);
1872     } else if (arm_feature(env, ARM_FEATURE_V8)) {
1873         descaddrmask = MAKE_64BIT_MASK(0, 48);
1874     } else {
1875         descaddrmask = MAKE_64BIT_MASK(0, 40);
1876     }
1877     descaddrmask &= ~indexmask_grainsize;
1878     tableattrs = 0;
1879 
1880  next_level:
1881     descaddr |= (address >> (stride * (4 - level))) & indexmask;
1882     descaddr &= ~7ULL;
1883 
1884     /*
1885      * Process the NSTable bit from the previous level.  This changes
1886      * the table address space and the output space from Secure to
1887      * NonSecure.  With RME, the EL3 translation regime does not change
1888      * from Root to NonSecure.
1889      */
1890     if (ptw->in_space == ARMSS_Secure
1891         && !regime_is_stage2(mmu_idx)
1892         && extract32(tableattrs, 4, 1)) {
1893         /*
1894          * Stage2_S -> Stage2 or Phys_S -> Phys_NS
1895          * Assert the relative order of the secure/non-secure indexes.
1896          */
1897         QEMU_BUILD_BUG_ON(ARMMMUIdx_Phys_S + 1 != ARMMMUIdx_Phys_NS);
1898         QEMU_BUILD_BUG_ON(ARMMMUIdx_Stage2_S + 1 != ARMMMUIdx_Stage2);
1899         ptw->in_ptw_idx += 1;
1900         ptw->in_space = ARMSS_NonSecure;
1901     }
1902 
1903     if (!S1_ptw_translate(env, ptw, descaddr, fi)) {
1904         goto do_fault;
1905     }
1906     descriptor = arm_ldq_ptw(env, ptw, fi);
1907     if (fi->type != ARMFault_None) {
1908         goto do_fault;
1909     }
1910     new_descriptor = descriptor;
1911 
1912  restart_atomic_update:
1913     if (!(descriptor & 1) ||
1914         (!(descriptor & 2) &&
1915          !lpae_block_desc_valid(cpu, param.ds, param.gran, level))) {
1916         /* Invalid, or a block descriptor at an invalid level */
1917         goto do_translation_fault;
1918     }
1919 
1920     descaddr = descriptor & descaddrmask;
1921 
1922     /*
1923      * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [15:12]
1924      * of descriptor.  For FEAT_LPA2 and effective DS, bits [51:50] of
1925      * descaddr are in [9:8].  Otherwise, if descaddr is out of range,
1926      * raise AddressSizeFault.
1927      */
1928     if (outputsize > 48) {
1929         if (param.ds) {
1930             descaddr |= extract64(descriptor, 8, 2) << 50;
1931         } else {
1932             descaddr |= extract64(descriptor, 12, 4) << 48;
1933         }
1934     } else if (descaddr >> outputsize) {
1935         fi->type = ARMFault_AddressSize;
1936         goto do_fault;
1937     }
1938 
1939     if ((descriptor & 2) && (level < 3)) {
1940         /*
1941          * Table entry. The top five bits are attributes which may
1942          * propagate down through lower levels of the table (and
1943          * which are all arranged so that 0 means "no effect", so
1944          * we can gather them up by ORing in the bits at each level).
1945          */
1946         tableattrs |= extract64(descriptor, 59, 5);
1947         level++;
1948         indexmask = indexmask_grainsize;
1949         goto next_level;
1950     }
1951 
1952     /*
1953      * Block entry at level 1 or 2, or page entry at level 3.
1954      * These are basically the same thing, although the number
1955      * of bits we pull in from the vaddr varies. Note that although
1956      * descaddrmask masks enough of the low bits of the descriptor
1957      * to give a correct page or table address, the address field
1958      * in a block descriptor is smaller; so we need to explicitly
1959      * clear the lower bits here before ORing in the low vaddr bits.
1960      *
1961      * Afterward, descaddr is the final physical address.
1962      */
1963     page_size = (1ULL << ((stride * (4 - level)) + 3));
1964     descaddr &= ~(hwaddr)(page_size - 1);
1965     descaddr |= (address & (page_size - 1));
1966 
1967     if (likely(!ptw->in_debug)) {
1968         /*
1969          * Access flag.
1970          * If HA is enabled, prepare to update the descriptor below.
1971          * Otherwise, pass the access fault on to software.
1972          */
1973         if (!(descriptor & (1 << 10))) {
1974             if (param.ha) {
1975                 new_descriptor |= 1 << 10; /* AF */
1976             } else {
1977                 fi->type = ARMFault_AccessFlag;
1978                 goto do_fault;
1979             }
1980         }
1981 
1982         /*
1983          * Dirty Bit.
1984          * If HD is enabled, pre-emptively set/clear the appropriate AP/S2AP
1985          * bit for writeback. The actual write protection test may still be
1986          * overridden by tableattrs, to be merged below.
1987          */
1988         if (param.hd
1989             && extract64(descriptor, 51, 1)  /* DBM */
1990             && access_type == MMU_DATA_STORE) {
1991             if (regime_is_stage2(mmu_idx)) {
1992                 new_descriptor |= 1ull << 7;    /* set S2AP[1] */
1993             } else {
1994                 new_descriptor &= ~(1ull << 7); /* clear AP[2] */
1995             }
1996         }
1997     }
1998 
1999     /*
2000      * Extract attributes from the (modified) descriptor, and apply
2001      * table descriptors. Stage 2 table descriptors do not include
2002      * any attribute fields. HPD disables all the table attributes
2003      * except NSTable (which we have already handled).
2004      */
2005     attrs = new_descriptor & (MAKE_64BIT_MASK(2, 10) | MAKE_64BIT_MASK(50, 14));
2006     if (!regime_is_stage2(mmu_idx)) {
2007         if (!param.hpd) {
2008             attrs |= extract64(tableattrs, 0, 2) << 53;     /* XN, PXN */
2009             /*
2010              * The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
2011              * means "force PL1 access only", which means forcing AP[1] to 0.
2012              */
2013             attrs &= ~(extract64(tableattrs, 2, 1) << 6); /* !APT[0] => AP[1] */
2014             attrs |= extract32(tableattrs, 3, 1) << 7;    /* APT[1] => AP[2] */
2015         }
2016     }
2017 
2018     ap = extract32(attrs, 6, 2);
2019     out_space = ptw->in_space;
2020     if (regime_is_stage2(mmu_idx)) {
2021         /*
2022          * R_GYNXY: For stage2 in Realm security state, bit 55 is NS.
2023          * The bit remains ignored for other security states.
2024          * R_YMCSL: Executing an insn fetched from non-Realm causes
2025          * a stage2 permission fault.
2026          */
2027         if (out_space == ARMSS_Realm && extract64(attrs, 55, 1)) {
2028             out_space = ARMSS_NonSecure;
2029             result->f.prot = get_S2prot_noexecute(ap);
2030         } else {
2031             xn = extract64(attrs, 53, 2);
2032             result->f.prot = get_S2prot(env, ap, xn, ptw->in_s1_is_el0);
2033         }
2034 
2035         result->cacheattrs.is_s2_format = true;
2036         result->cacheattrs.attrs = extract32(attrs, 2, 4);
2037         /*
2038          * Security state does not really affect HCR_EL2.FWB;
2039          * we only need to filter FWB for aa32 or other FEAT.
2040          */
2041         device = S2_attrs_are_device(arm_hcr_el2_eff(env),
2042                                      result->cacheattrs.attrs);
2043     } else {
2044         int nse, ns = extract32(attrs, 5, 1);
2045         uint8_t attrindx;
2046         uint64_t mair;
2047 
2048         switch (out_space) {
2049         case ARMSS_Root:
2050             /*
2051              * R_GVZML: Bit 11 becomes the NSE field in the EL3 regime.
2052              * R_XTYPW: NSE and NS together select the output pa space.
2053              */
2054             nse = extract32(attrs, 11, 1);
2055             out_space = (nse << 1) | ns;
2056             if (out_space == ARMSS_Secure &&
2057                 !cpu_isar_feature(aa64_sel2, cpu)) {
2058                 out_space = ARMSS_NonSecure;
2059             }
2060             break;
2061         case ARMSS_Secure:
2062             if (ns) {
2063                 out_space = ARMSS_NonSecure;
2064             }
2065             break;
2066         case ARMSS_Realm:
2067             switch (mmu_idx) {
2068             case ARMMMUIdx_Stage1_E0:
2069             case ARMMMUIdx_Stage1_E1:
2070             case ARMMMUIdx_Stage1_E1_PAN:
2071                 /* I_CZPRF: For Realm EL1&0 stage1, NS bit is RES0. */
2072                 break;
2073             case ARMMMUIdx_E2:
2074             case ARMMMUIdx_E20_0:
2075             case ARMMMUIdx_E20_2:
2076             case ARMMMUIdx_E20_2_PAN:
2077                 /*
2078                  * R_LYKFZ, R_WGRZN: For Realm EL2 and EL2&1,
2079                  * NS changes the output to non-secure space.
2080                  */
2081                 if (ns) {
2082                     out_space = ARMSS_NonSecure;
2083                 }
2084                 break;
2085             default:
2086                 g_assert_not_reached();
2087             }
2088             break;
2089         case ARMSS_NonSecure:
2090             /* R_QRMFF: For NonSecure state, the NS bit is RES0. */
2091             break;
2092         default:
2093             g_assert_not_reached();
2094         }
2095         xn = extract64(attrs, 54, 1);
2096         pxn = extract64(attrs, 53, 1);
2097 
2098         if (el == 1 && nv_nv1_enabled(env, ptw)) {
2099             /*
2100              * With FEAT_NV, when HCR_EL2.{NV,NV1} == {1,1}, the block/page
2101              * descriptor bit 54 holds PXN, 53 is RES0, and the effective value
2102              * of UXN is 0. Similarly for bits 59 and 60 in table descriptors
2103              * (which we have already folded into bits 53 and 54 of attrs).
2104              * AP[1] (descriptor bit 6, our ap bit 0) is treated as 0.
2105              * Similarly, APTable[0] from the table descriptor is treated as 0;
2106              * we already folded this into AP[1] and squashing that to 0 does
2107              * the right thing.
2108              */
2109             pxn = xn;
2110             xn = 0;
2111             ap &= ~1;
2112         }
2113         /*
2114          * Note that we modified ptw->in_space earlier for NSTable, but
2115          * result->f.attrs retains a copy of the original security space.
2116          */
2117         result->f.prot = get_S1prot(env, mmu_idx, aarch64, ap, xn, pxn,
2118                                     result->f.attrs.space, out_space);
2119 
2120         /* Index into MAIR registers for cache attributes */
2121         attrindx = extract32(attrs, 2, 3);
2122         mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
2123         assert(attrindx <= 7);
2124         result->cacheattrs.is_s2_format = false;
2125         result->cacheattrs.attrs = extract64(mair, attrindx * 8, 8);
2126 
2127         /* When in aarch64 mode, and BTI is enabled, remember GP in the TLB. */
2128         if (aarch64 && cpu_isar_feature(aa64_bti, cpu)) {
2129             result->f.extra.arm.guarded = extract64(attrs, 50, 1); /* GP */
2130         }
2131         device = S1_attrs_are_device(result->cacheattrs.attrs);
2132     }
2133 
2134     /*
2135      * Enable alignment checks on Device memory.
2136      *
2137      * Per R_XCHFJ, the correct ordering for alignment, permission,
2138      * and stage 2 faults is:
2139      *    - Alignment fault caused by the memory type
2140      *    - Permission fault
2141      *    - A stage 2 fault on the memory access
2142      * Perform the alignment check now, so that we recognize it in
2143      * the correct order.  Set TLB_CHECK_ALIGNED so that any subsequent
2144      * softmmu tlb hit will also check the alignment; clear along the
2145      * non-device path so that tlb_fill_flags is consistent in the
2146      * event of restart_atomic_update.
2147      *
2148      * In v7, for a CPU without the Virtualization Extensions this
2149      * access is UNPREDICTABLE; we choose to make it take the alignment
2150      * fault as is required for a v7VE CPU. (QEMU doesn't emulate any
2151      * CPUs with ARM_FEATURE_LPAE but not ARM_FEATURE_V7VE anyway.)
2152      */
2153     if (device) {
2154         unsigned a_bits = memop_atomicity_bits(memop);
2155         if (address & ((1 << a_bits) - 1)) {
2156             fi->type = ARMFault_Alignment;
2157             goto do_fault;
2158         }
2159         result->f.tlb_fill_flags = TLB_CHECK_ALIGNED;
2160     } else {
2161         result->f.tlb_fill_flags = 0;
2162     }
2163 
2164     if (!(result->f.prot & (1 << access_type))) {
2165         fi->type = ARMFault_Permission;
2166         goto do_fault;
2167     }
2168 
2169     /* If FEAT_HAFDBS has made changes, update the PTE. */
2170     if (new_descriptor != descriptor) {
2171         new_descriptor = arm_casq_ptw(env, descriptor, new_descriptor, ptw, fi);
2172         if (fi->type != ARMFault_None) {
2173             goto do_fault;
2174         }
2175         /*
2176          * I_YZSVV says that if the in-memory descriptor has changed,
2177          * then we must use the information in that new value
2178          * (which might include a different output address, different
2179          * attributes, or generate a fault).
2180          * Restart the handling of the descriptor value from scratch.
2181          */
2182         if (new_descriptor != descriptor) {
2183             descriptor = new_descriptor;
2184             goto restart_atomic_update;
2185         }
2186     }
2187 
2188     result->f.attrs.space = out_space;
2189     result->f.attrs.secure = arm_space_is_secure(out_space);
2190 
2191     /*
2192      * For FEAT_LPA2 and effective DS, the SH field in the attributes
2193      * was re-purposed for output address bits.  The SH attribute in
2194      * that case comes from TCR_ELx, which we extracted earlier.
2195      */
2196     if (param.ds) {
2197         result->cacheattrs.shareability = param.sh;
2198     } else {
2199         result->cacheattrs.shareability = extract32(attrs, 8, 2);
2200     }
2201 
2202     result->f.phys_addr = descaddr;
2203     result->f.lg_page_size = ctz64(page_size);
2204     return false;
2205 
2206  do_translation_fault:
2207     fi->type = ARMFault_Translation;
2208  do_fault:
2209     if (fi->s1ptw) {
2210         /* Retain the existing stage 2 fi->level */
2211         assert(fi->stage2);
2212     } else {
2213         fi->level = level;
2214         fi->stage2 = regime_is_stage2(mmu_idx);
2215     }
2216     fi->s1ns = fault_s1ns(ptw->in_space, mmu_idx);
2217     return true;
2218 }
2219 
2220 static bool get_phys_addr_pmsav5(CPUARMState *env,
2221                                  S1Translate *ptw,
2222                                  uint32_t address,
2223                                  MMUAccessType access_type,
2224                                  GetPhysAddrResult *result,
2225                                  ARMMMUFaultInfo *fi)
2226 {
2227     int n;
2228     uint32_t mask;
2229     uint32_t base;
2230     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
2231     bool is_user = regime_is_user(env, mmu_idx);
2232 
2233     if (regime_translation_disabled(env, mmu_idx, ptw->in_space)) {
2234         /* MPU disabled.  */
2235         result->f.phys_addr = address;
2236         result->f.prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
2237         return false;
2238     }
2239 
2240     result->f.phys_addr = address;
2241     for (n = 7; n >= 0; n--) {
2242         base = env->cp15.c6_region[n];
2243         if ((base & 1) == 0) {
2244             continue;
2245         }
2246         mask = 1 << ((base >> 1) & 0x1f);
2247         /* Keep this shift separate from the above to avoid an
2248            (undefined) << 32.  */
2249         mask = (mask << 1) - 1;
2250         if (((base ^ address) & ~mask) == 0) {
2251             break;
2252         }
2253     }
2254     if (n < 0) {
2255         fi->type = ARMFault_Background;
2256         return true;
2257     }
2258 
2259     if (access_type == MMU_INST_FETCH) {
2260         mask = env->cp15.pmsav5_insn_ap;
2261     } else {
2262         mask = env->cp15.pmsav5_data_ap;
2263     }
2264     mask = (mask >> (n * 4)) & 0xf;
2265     switch (mask) {
2266     case 0:
2267         fi->type = ARMFault_Permission;
2268         fi->level = 1;
2269         return true;
2270     case 1:
2271         if (is_user) {
2272             fi->type = ARMFault_Permission;
2273             fi->level = 1;
2274             return true;
2275         }
2276         result->f.prot = PAGE_READ | PAGE_WRITE;
2277         break;
2278     case 2:
2279         result->f.prot = PAGE_READ;
2280         if (!is_user) {
2281             result->f.prot |= PAGE_WRITE;
2282         }
2283         break;
2284     case 3:
2285         result->f.prot = PAGE_READ | PAGE_WRITE;
2286         break;
2287     case 5:
2288         if (is_user) {
2289             fi->type = ARMFault_Permission;
2290             fi->level = 1;
2291             return true;
2292         }
2293         result->f.prot = PAGE_READ;
2294         break;
2295     case 6:
2296         result->f.prot = PAGE_READ;
2297         break;
2298     default:
2299         /* Bad permission.  */
2300         fi->type = ARMFault_Permission;
2301         fi->level = 1;
2302         return true;
2303     }
2304     result->f.prot |= PAGE_EXEC;
2305     return false;
2306 }
2307 
2308 static void get_phys_addr_pmsav7_default(CPUARMState *env, ARMMMUIdx mmu_idx,
2309                                          int32_t address, uint8_t *prot)
2310 {
2311     if (!arm_feature(env, ARM_FEATURE_M)) {
2312         *prot = PAGE_READ | PAGE_WRITE;
2313         switch (address) {
2314         case 0xF0000000 ... 0xFFFFFFFF:
2315             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
2316                 /* hivecs execing is ok */
2317                 *prot |= PAGE_EXEC;
2318             }
2319             break;
2320         case 0x00000000 ... 0x7FFFFFFF:
2321             *prot |= PAGE_EXEC;
2322             break;
2323         }
2324     } else {
2325         /* Default system address map for M profile cores.
2326          * The architecture specifies which regions are execute-never;
2327          * at the MPU level no other checks are defined.
2328          */
2329         switch (address) {
2330         case 0x00000000 ... 0x1fffffff: /* ROM */
2331         case 0x20000000 ... 0x3fffffff: /* SRAM */
2332         case 0x60000000 ... 0x7fffffff: /* RAM */
2333         case 0x80000000 ... 0x9fffffff: /* RAM */
2334             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
2335             break;
2336         case 0x40000000 ... 0x5fffffff: /* Peripheral */
2337         case 0xa0000000 ... 0xbfffffff: /* Device */
2338         case 0xc0000000 ... 0xdfffffff: /* Device */
2339         case 0xe0000000 ... 0xffffffff: /* System */
2340             *prot = PAGE_READ | PAGE_WRITE;
2341             break;
2342         default:
2343             g_assert_not_reached();
2344         }
2345     }
2346 }
2347 
2348 static bool m_is_ppb_region(CPUARMState *env, uint32_t address)
2349 {
2350     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
2351     return arm_feature(env, ARM_FEATURE_M) &&
2352         extract32(address, 20, 12) == 0xe00;
2353 }
2354 
2355 static bool m_is_system_region(CPUARMState *env, uint32_t address)
2356 {
2357     /*
2358      * True if address is in the M profile system region
2359      * 0xe0000000 - 0xffffffff
2360      */
2361     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
2362 }
2363 
2364 static bool pmsav7_use_background_region(ARMCPU *cpu, ARMMMUIdx mmu_idx,
2365                                          bool is_secure, bool is_user)
2366 {
2367     /*
2368      * Return true if we should use the default memory map as a
2369      * "background" region if there are no hits against any MPU regions.
2370      */
2371     CPUARMState *env = &cpu->env;
2372 
2373     if (is_user) {
2374         return false;
2375     }
2376 
2377     if (arm_feature(env, ARM_FEATURE_M)) {
2378         return env->v7m.mpu_ctrl[is_secure] & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
2379     }
2380 
2381     if (mmu_idx == ARMMMUIdx_Stage2) {
2382         return false;
2383     }
2384 
2385     return regime_sctlr(env, mmu_idx) & SCTLR_BR;
2386 }
2387 
2388 static bool get_phys_addr_pmsav7(CPUARMState *env,
2389                                  S1Translate *ptw,
2390                                  uint32_t address,
2391                                  MMUAccessType access_type,
2392                                  GetPhysAddrResult *result,
2393                                  ARMMMUFaultInfo *fi)
2394 {
2395     ARMCPU *cpu = env_archcpu(env);
2396     int n;
2397     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
2398     bool is_user = regime_is_user(env, mmu_idx);
2399     bool secure = arm_space_is_secure(ptw->in_space);
2400 
2401     result->f.phys_addr = address;
2402     result->f.lg_page_size = TARGET_PAGE_BITS;
2403     result->f.prot = 0;
2404 
2405     if (regime_translation_disabled(env, mmu_idx, ptw->in_space) ||
2406         m_is_ppb_region(env, address)) {
2407         /*
2408          * MPU disabled or M profile PPB access: use default memory map.
2409          * The other case which uses the default memory map in the
2410          * v7M ARM ARM pseudocode is exception vector reads from the vector
2411          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
2412          * which always does a direct read using address_space_ldl(), rather
2413          * than going via this function, so we don't need to check that here.
2414          */
2415         get_phys_addr_pmsav7_default(env, mmu_idx, address, &result->f.prot);
2416     } else { /* MPU enabled */
2417         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
2418             /* region search */
2419             uint32_t base = env->pmsav7.drbar[n];
2420             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
2421             uint32_t rmask;
2422             bool srdis = false;
2423 
2424             if (!(env->pmsav7.drsr[n] & 0x1)) {
2425                 continue;
2426             }
2427 
2428             if (!rsize) {
2429                 qemu_log_mask(LOG_GUEST_ERROR,
2430                               "DRSR[%d]: Rsize field cannot be 0\n", n);
2431                 continue;
2432             }
2433             rsize++;
2434             rmask = (1ull << rsize) - 1;
2435 
2436             if (base & rmask) {
2437                 qemu_log_mask(LOG_GUEST_ERROR,
2438                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
2439                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
2440                               n, base, rmask);
2441                 continue;
2442             }
2443 
2444             if (address < base || address > base + rmask) {
2445                 /*
2446                  * Address not in this region. We must check whether the
2447                  * region covers addresses in the same page as our address.
2448                  * In that case we must not report a size that covers the
2449                  * whole page for a subsequent hit against a different MPU
2450                  * region or the background region, because it would result in
2451                  * incorrect TLB hits for subsequent accesses to addresses that
2452                  * are in this MPU region.
2453                  */
2454                 if (ranges_overlap(base, rmask,
2455                                    address & TARGET_PAGE_MASK,
2456                                    TARGET_PAGE_SIZE)) {
2457                     result->f.lg_page_size = 0;
2458                 }
2459                 continue;
2460             }
2461 
2462             /* Region matched */
2463 
2464             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
2465                 int i, snd;
2466                 uint32_t srdis_mask;
2467 
2468                 rsize -= 3; /* sub region size (power of 2) */
2469                 snd = ((address - base) >> rsize) & 0x7;
2470                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
2471 
2472                 srdis_mask = srdis ? 0x3 : 0x0;
2473                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
2474                     /*
2475                      * This will check in groups of 2, 4 and then 8, whether
2476                      * the subregion bits are consistent. rsize is incremented
2477                      * back up to give the region size, considering consistent
2478                      * adjacent subregions as one region. Stop testing if rsize
2479                      * is already big enough for an entire QEMU page.
2480                      */
2481                     int snd_rounded = snd & ~(i - 1);
2482                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
2483                                                      snd_rounded + 8, i);
2484                     if (srdis_mask ^ srdis_multi) {
2485                         break;
2486                     }
2487                     srdis_mask = (srdis_mask << i) | srdis_mask;
2488                     rsize++;
2489                 }
2490             }
2491             if (srdis) {
2492                 continue;
2493             }
2494             if (rsize < TARGET_PAGE_BITS) {
2495                 result->f.lg_page_size = rsize;
2496             }
2497             break;
2498         }
2499 
2500         if (n == -1) { /* no hits */
2501             if (!pmsav7_use_background_region(cpu, mmu_idx, secure, is_user)) {
2502                 /* background fault */
2503                 fi->type = ARMFault_Background;
2504                 return true;
2505             }
2506             get_phys_addr_pmsav7_default(env, mmu_idx, address,
2507                                          &result->f.prot);
2508         } else { /* a MPU hit! */
2509             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
2510             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
2511 
2512             if (m_is_system_region(env, address)) {
2513                 /* System space is always execute never */
2514                 xn = 1;
2515             }
2516 
2517             if (is_user) { /* User mode AP bit decoding */
2518                 switch (ap) {
2519                 case 0:
2520                 case 1:
2521                 case 5:
2522                     break; /* no access */
2523                 case 3:
2524                     result->f.prot |= PAGE_WRITE;
2525                     /* fall through */
2526                 case 2:
2527                 case 6:
2528                     result->f.prot |= PAGE_READ | PAGE_EXEC;
2529                     break;
2530                 case 7:
2531                     /* for v7M, same as 6; for R profile a reserved value */
2532                     if (arm_feature(env, ARM_FEATURE_M)) {
2533                         result->f.prot |= PAGE_READ | PAGE_EXEC;
2534                         break;
2535                     }
2536                     /* fall through */
2537                 default:
2538                     qemu_log_mask(LOG_GUEST_ERROR,
2539                                   "DRACR[%d]: Bad value for AP bits: 0x%"
2540                                   PRIx32 "\n", n, ap);
2541                 }
2542             } else { /* Priv. mode AP bits decoding */
2543                 switch (ap) {
2544                 case 0:
2545                     break; /* no access */
2546                 case 1:
2547                 case 2:
2548                 case 3:
2549                     result->f.prot |= PAGE_WRITE;
2550                     /* fall through */
2551                 case 5:
2552                 case 6:
2553                     result->f.prot |= PAGE_READ | PAGE_EXEC;
2554                     break;
2555                 case 7:
2556                     /* for v7M, same as 6; for R profile a reserved value */
2557                     if (arm_feature(env, ARM_FEATURE_M)) {
2558                         result->f.prot |= PAGE_READ | PAGE_EXEC;
2559                         break;
2560                     }
2561                     /* fall through */
2562                 default:
2563                     qemu_log_mask(LOG_GUEST_ERROR,
2564                                   "DRACR[%d]: Bad value for AP bits: 0x%"
2565                                   PRIx32 "\n", n, ap);
2566                 }
2567             }
2568 
2569             /* execute never */
2570             if (xn) {
2571                 result->f.prot &= ~PAGE_EXEC;
2572             }
2573         }
2574     }
2575 
2576     fi->type = ARMFault_Permission;
2577     fi->level = 1;
2578     return !(result->f.prot & (1 << access_type));
2579 }
2580 
2581 static uint32_t *regime_rbar(CPUARMState *env, ARMMMUIdx mmu_idx,
2582                              uint32_t secure)
2583 {
2584     if (regime_el(env, mmu_idx) == 2) {
2585         return env->pmsav8.hprbar;
2586     } else {
2587         return env->pmsav8.rbar[secure];
2588     }
2589 }
2590 
2591 static uint32_t *regime_rlar(CPUARMState *env, ARMMMUIdx mmu_idx,
2592                              uint32_t secure)
2593 {
2594     if (regime_el(env, mmu_idx) == 2) {
2595         return env->pmsav8.hprlar;
2596     } else {
2597         return env->pmsav8.rlar[secure];
2598     }
2599 }
2600 
2601 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
2602                        MMUAccessType access_type, ARMMMUIdx mmu_idx,
2603                        bool secure, GetPhysAddrResult *result,
2604                        ARMMMUFaultInfo *fi, uint32_t *mregion)
2605 {
2606     /*
2607      * Perform a PMSAv8 MPU lookup (without also doing the SAU check
2608      * that a full phys-to-virt translation does).
2609      * mregion is (if not NULL) set to the region number which matched,
2610      * or -1 if no region number is returned (MPU off, address did not
2611      * hit a region, address hit in multiple regions).
2612      * If the region hit doesn't cover the entire TARGET_PAGE the address
2613      * is within, then we set the result page_size to 1 to force the
2614      * memory system to use a subpage.
2615      */
2616     ARMCPU *cpu = env_archcpu(env);
2617     bool is_user = regime_is_user(env, mmu_idx);
2618     int n;
2619     int matchregion = -1;
2620     bool hit = false;
2621     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
2622     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
2623     int region_counter;
2624 
2625     if (regime_el(env, mmu_idx) == 2) {
2626         region_counter = cpu->pmsav8r_hdregion;
2627     } else {
2628         region_counter = cpu->pmsav7_dregion;
2629     }
2630 
2631     result->f.lg_page_size = TARGET_PAGE_BITS;
2632     result->f.phys_addr = address;
2633     result->f.prot = 0;
2634     if (mregion) {
2635         *mregion = -1;
2636     }
2637 
2638     if (mmu_idx == ARMMMUIdx_Stage2) {
2639         fi->stage2 = true;
2640     }
2641 
2642     /*
2643      * Unlike the ARM ARM pseudocode, we don't need to check whether this
2644      * was an exception vector read from the vector table (which is always
2645      * done using the default system address map), because those accesses
2646      * are done in arm_v7m_load_vector(), which always does a direct
2647      * read using address_space_ldl(), rather than going via this function.
2648      */
2649     if (regime_translation_disabled(env, mmu_idx, arm_secure_to_space(secure))) {
2650         /* MPU disabled */
2651         hit = true;
2652     } else if (m_is_ppb_region(env, address)) {
2653         hit = true;
2654     } else {
2655         if (pmsav7_use_background_region(cpu, mmu_idx, secure, is_user)) {
2656             hit = true;
2657         }
2658 
2659         uint32_t bitmask;
2660         if (arm_feature(env, ARM_FEATURE_M)) {
2661             bitmask = 0x1f;
2662         } else {
2663             bitmask = 0x3f;
2664             fi->level = 0;
2665         }
2666 
2667         for (n = region_counter - 1; n >= 0; n--) {
2668             /* region search */
2669             /*
2670              * Note that the base address is bits [31:x] from the register
2671              * with bits [x-1:0] all zeroes, but the limit address is bits
2672              * [31:x] from the register with bits [x:0] all ones. Where x is
2673              * 5 for Cortex-M and 6 for Cortex-R
2674              */
2675             uint32_t base = regime_rbar(env, mmu_idx, secure)[n] & ~bitmask;
2676             uint32_t limit = regime_rlar(env, mmu_idx, secure)[n] | bitmask;
2677 
2678             if (!(regime_rlar(env, mmu_idx, secure)[n] & 0x1)) {
2679                 /* Region disabled */
2680                 continue;
2681             }
2682 
2683             if (address < base || address > limit) {
2684                 /*
2685                  * Address not in this region. We must check whether the
2686                  * region covers addresses in the same page as our address.
2687                  * In that case we must not report a size that covers the
2688                  * whole page for a subsequent hit against a different MPU
2689                  * region or the background region, because it would result in
2690                  * incorrect TLB hits for subsequent accesses to addresses that
2691                  * are in this MPU region.
2692                  */
2693                 if (limit >= base &&
2694                     ranges_overlap(base, limit - base + 1,
2695                                    addr_page_base,
2696                                    TARGET_PAGE_SIZE)) {
2697                     result->f.lg_page_size = 0;
2698                 }
2699                 continue;
2700             }
2701 
2702             if (base > addr_page_base || limit < addr_page_limit) {
2703                 result->f.lg_page_size = 0;
2704             }
2705 
2706             if (matchregion != -1) {
2707                 /*
2708                  * Multiple regions match -- always a failure (unlike
2709                  * PMSAv7 where highest-numbered-region wins)
2710                  */
2711                 fi->type = ARMFault_Permission;
2712                 if (arm_feature(env, ARM_FEATURE_M)) {
2713                     fi->level = 1;
2714                 }
2715                 return true;
2716             }
2717 
2718             matchregion = n;
2719             hit = true;
2720         }
2721     }
2722 
2723     if (!hit) {
2724         if (arm_feature(env, ARM_FEATURE_M)) {
2725             fi->type = ARMFault_Background;
2726         } else {
2727             fi->type = ARMFault_Permission;
2728         }
2729         return true;
2730     }
2731 
2732     if (matchregion == -1) {
2733         /* hit using the background region */
2734         get_phys_addr_pmsav7_default(env, mmu_idx, address, &result->f.prot);
2735     } else {
2736         uint32_t matched_rbar = regime_rbar(env, mmu_idx, secure)[matchregion];
2737         uint32_t matched_rlar = regime_rlar(env, mmu_idx, secure)[matchregion];
2738         uint32_t ap = extract32(matched_rbar, 1, 2);
2739         uint32_t xn = extract32(matched_rbar, 0, 1);
2740         bool pxn = false;
2741 
2742         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
2743             pxn = extract32(matched_rlar, 4, 1);
2744         }
2745 
2746         if (m_is_system_region(env, address)) {
2747             /* System space is always execute never */
2748             xn = 1;
2749         }
2750 
2751         if (regime_el(env, mmu_idx) == 2) {
2752             result->f.prot = simple_ap_to_rw_prot_is_user(ap,
2753                                             mmu_idx != ARMMMUIdx_E2);
2754         } else {
2755             result->f.prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
2756         }
2757 
2758         if (!arm_feature(env, ARM_FEATURE_M)) {
2759             uint8_t attrindx = extract32(matched_rlar, 1, 3);
2760             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
2761             uint8_t sh = extract32(matched_rlar, 3, 2);
2762 
2763             if (regime_sctlr(env, mmu_idx) & SCTLR_WXN &&
2764                 result->f.prot & PAGE_WRITE && mmu_idx != ARMMMUIdx_Stage2) {
2765                 xn = 0x1;
2766             }
2767 
2768             if ((regime_el(env, mmu_idx) == 1) &&
2769                 regime_sctlr(env, mmu_idx) & SCTLR_UWXN && ap == 0x1) {
2770                 pxn = 0x1;
2771             }
2772 
2773             result->cacheattrs.is_s2_format = false;
2774             result->cacheattrs.attrs = extract64(mair, attrindx * 8, 8);
2775             result->cacheattrs.shareability = sh;
2776         }
2777 
2778         if (result->f.prot && !xn && !(pxn && !is_user)) {
2779             result->f.prot |= PAGE_EXEC;
2780         }
2781 
2782         if (mregion) {
2783             *mregion = matchregion;
2784         }
2785     }
2786 
2787     fi->type = ARMFault_Permission;
2788     if (arm_feature(env, ARM_FEATURE_M)) {
2789         fi->level = 1;
2790     }
2791     return !(result->f.prot & (1 << access_type));
2792 }
2793 
2794 static bool v8m_is_sau_exempt(CPUARMState *env,
2795                               uint32_t address, MMUAccessType access_type)
2796 {
2797     /*
2798      * The architecture specifies that certain address ranges are
2799      * exempt from v8M SAU/IDAU checks.
2800      */
2801     return
2802         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
2803         (address >= 0xe0000000 && address <= 0xe0002fff) ||
2804         (address >= 0xe000e000 && address <= 0xe000efff) ||
2805         (address >= 0xe002e000 && address <= 0xe002efff) ||
2806         (address >= 0xe0040000 && address <= 0xe0041fff) ||
2807         (address >= 0xe00ff000 && address <= 0xe00fffff);
2808 }
2809 
2810 void v8m_security_lookup(CPUARMState *env, uint32_t address,
2811                          MMUAccessType access_type, ARMMMUIdx mmu_idx,
2812                          bool is_secure, V8M_SAttributes *sattrs)
2813 {
2814     /*
2815      * Look up the security attributes for this address. Compare the
2816      * pseudocode SecurityCheck() function.
2817      * We assume the caller has zero-initialized *sattrs.
2818      */
2819     ARMCPU *cpu = env_archcpu(env);
2820     int r;
2821     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
2822     int idau_region = IREGION_NOTVALID;
2823     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
2824     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
2825 
2826     if (cpu->idau) {
2827         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
2828         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
2829 
2830         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
2831                    &idau_nsc);
2832     }
2833 
2834     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
2835         /* 0xf0000000..0xffffffff is always S for insn fetches */
2836         return;
2837     }
2838 
2839     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
2840         sattrs->ns = !is_secure;
2841         return;
2842     }
2843 
2844     if (idau_region != IREGION_NOTVALID) {
2845         sattrs->irvalid = true;
2846         sattrs->iregion = idau_region;
2847     }
2848 
2849     switch (env->sau.ctrl & 3) {
2850     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
2851         break;
2852     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
2853         sattrs->ns = true;
2854         break;
2855     default: /* SAU.ENABLE == 1 */
2856         for (r = 0; r < cpu->sau_sregion; r++) {
2857             if (env->sau.rlar[r] & 1) {
2858                 uint32_t base = env->sau.rbar[r] & ~0x1f;
2859                 uint32_t limit = env->sau.rlar[r] | 0x1f;
2860 
2861                 if (base <= address && limit >= address) {
2862                     if (base > addr_page_base || limit < addr_page_limit) {
2863                         sattrs->subpage = true;
2864                     }
2865                     if (sattrs->srvalid) {
2866                         /*
2867                          * If we hit in more than one region then we must report
2868                          * as Secure, not NS-Callable, with no valid region
2869                          * number info.
2870                          */
2871                         sattrs->ns = false;
2872                         sattrs->nsc = false;
2873                         sattrs->sregion = 0;
2874                         sattrs->srvalid = false;
2875                         break;
2876                     } else {
2877                         if (env->sau.rlar[r] & 2) {
2878                             sattrs->nsc = true;
2879                         } else {
2880                             sattrs->ns = true;
2881                         }
2882                         sattrs->srvalid = true;
2883                         sattrs->sregion = r;
2884                     }
2885                 } else {
2886                     /*
2887                      * Address not in this region. We must check whether the
2888                      * region covers addresses in the same page as our address.
2889                      * In that case we must not report a size that covers the
2890                      * whole page for a subsequent hit against a different MPU
2891                      * region or the background region, because it would result
2892                      * in incorrect TLB hits for subsequent accesses to
2893                      * addresses that are in this MPU region.
2894                      */
2895                     if (limit >= base &&
2896                         ranges_overlap(base, limit - base + 1,
2897                                        addr_page_base,
2898                                        TARGET_PAGE_SIZE)) {
2899                         sattrs->subpage = true;
2900                     }
2901                 }
2902             }
2903         }
2904         break;
2905     }
2906 
2907     /*
2908      * The IDAU will override the SAU lookup results if it specifies
2909      * higher security than the SAU does.
2910      */
2911     if (!idau_ns) {
2912         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
2913             sattrs->ns = false;
2914             sattrs->nsc = idau_nsc;
2915         }
2916     }
2917 }
2918 
2919 static bool get_phys_addr_pmsav8(CPUARMState *env,
2920                                  S1Translate *ptw,
2921                                  uint32_t address,
2922                                  MMUAccessType access_type,
2923                                  GetPhysAddrResult *result,
2924                                  ARMMMUFaultInfo *fi)
2925 {
2926     V8M_SAttributes sattrs = {};
2927     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
2928     bool secure = arm_space_is_secure(ptw->in_space);
2929     bool ret;
2930 
2931     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
2932         v8m_security_lookup(env, address, access_type, mmu_idx,
2933                             secure, &sattrs);
2934         if (access_type == MMU_INST_FETCH) {
2935             /*
2936              * Instruction fetches always use the MMU bank and the
2937              * transaction attribute determined by the fetch address,
2938              * regardless of CPU state. This is painful for QEMU
2939              * to handle, because it would mean we need to encode
2940              * into the mmu_idx not just the (user, negpri) information
2941              * for the current security state but also that for the
2942              * other security state, which would balloon the number
2943              * of mmu_idx values needed alarmingly.
2944              * Fortunately we can avoid this because it's not actually
2945              * possible to arbitrarily execute code from memory with
2946              * the wrong security attribute: it will always generate
2947              * an exception of some kind or another, apart from the
2948              * special case of an NS CPU executing an SG instruction
2949              * in S&NSC memory. So we always just fail the translation
2950              * here and sort things out in the exception handler
2951              * (including possibly emulating an SG instruction).
2952              */
2953             if (sattrs.ns != !secure) {
2954                 if (sattrs.nsc) {
2955                     fi->type = ARMFault_QEMU_NSCExec;
2956                 } else {
2957                     fi->type = ARMFault_QEMU_SFault;
2958                 }
2959                 result->f.lg_page_size = sattrs.subpage ? 0 : TARGET_PAGE_BITS;
2960                 result->f.phys_addr = address;
2961                 result->f.prot = 0;
2962                 return true;
2963             }
2964         } else {
2965             /*
2966              * For data accesses we always use the MMU bank indicated
2967              * by the current CPU state, but the security attributes
2968              * might downgrade a secure access to nonsecure.
2969              */
2970             if (sattrs.ns) {
2971                 result->f.attrs.secure = false;
2972                 result->f.attrs.space = ARMSS_NonSecure;
2973             } else if (!secure) {
2974                 /*
2975                  * NS access to S memory must fault.
2976                  * Architecturally we should first check whether the
2977                  * MPU information for this address indicates that we
2978                  * are doing an unaligned access to Device memory, which
2979                  * should generate a UsageFault instead. QEMU does not
2980                  * currently check for that kind of unaligned access though.
2981                  * If we added it we would need to do so as a special case
2982                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
2983                  */
2984                 fi->type = ARMFault_QEMU_SFault;
2985                 result->f.lg_page_size = sattrs.subpage ? 0 : TARGET_PAGE_BITS;
2986                 result->f.phys_addr = address;
2987                 result->f.prot = 0;
2988                 return true;
2989             }
2990         }
2991     }
2992 
2993     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, secure,
2994                             result, fi, NULL);
2995     if (sattrs.subpage) {
2996         result->f.lg_page_size = 0;
2997     }
2998     return ret;
2999 }
3000 
3001 /*
3002  * Translate from the 4-bit stage 2 representation of
3003  * memory attributes (without cache-allocation hints) to
3004  * the 8-bit representation of the stage 1 MAIR registers
3005  * (which includes allocation hints).
3006  *
3007  * ref: shared/translation/attrs/S2AttrDecode()
3008  *      .../S2ConvertAttrsHints()
3009  */
3010 static uint8_t convert_stage2_attrs(uint64_t hcr, uint8_t s2attrs)
3011 {
3012     uint8_t hiattr = extract32(s2attrs, 2, 2);
3013     uint8_t loattr = extract32(s2attrs, 0, 2);
3014     uint8_t hihint = 0, lohint = 0;
3015 
3016     if (hiattr != 0) { /* normal memory */
3017         if (hcr & HCR_CD) { /* cache disabled */
3018             hiattr = loattr = 1; /* non-cacheable */
3019         } else {
3020             if (hiattr != 1) { /* Write-through or write-back */
3021                 hihint = 3; /* RW allocate */
3022             }
3023             if (loattr != 1) { /* Write-through or write-back */
3024                 lohint = 3; /* RW allocate */
3025             }
3026         }
3027     }
3028 
3029     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
3030 }
3031 
3032 /*
3033  * Combine either inner or outer cacheability attributes for normal
3034  * memory, according to table D4-42 and pseudocode procedure
3035  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
3036  *
3037  * NB: only stage 1 includes allocation hints (RW bits), leading to
3038  * some asymmetry.
3039  */
3040 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
3041 {
3042     if (s1 == 4 || s2 == 4) {
3043         /* non-cacheable has precedence */
3044         return 4;
3045     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
3046         /* stage 1 write-through takes precedence */
3047         return s1;
3048     } else if (extract32(s2, 2, 2) == 2) {
3049         /* stage 2 write-through takes precedence, but the allocation hint
3050          * is still taken from stage 1
3051          */
3052         return (2 << 2) | extract32(s1, 0, 2);
3053     } else { /* write-back */
3054         return s1;
3055     }
3056 }
3057 
3058 /*
3059  * Combine the memory type and cacheability attributes of
3060  * s1 and s2 for the HCR_EL2.FWB == 0 case, returning the
3061  * combined attributes in MAIR_EL1 format.
3062  */
3063 static uint8_t combined_attrs_nofwb(uint64_t hcr,
3064                                     ARMCacheAttrs s1, ARMCacheAttrs s2)
3065 {
3066     uint8_t s1lo, s2lo, s1hi, s2hi, s2_mair_attrs, ret_attrs;
3067 
3068     if (s2.is_s2_format) {
3069         s2_mair_attrs = convert_stage2_attrs(hcr, s2.attrs);
3070     } else {
3071         s2_mair_attrs = s2.attrs;
3072     }
3073 
3074     s1lo = extract32(s1.attrs, 0, 4);
3075     s2lo = extract32(s2_mair_attrs, 0, 4);
3076     s1hi = extract32(s1.attrs, 4, 4);
3077     s2hi = extract32(s2_mair_attrs, 4, 4);
3078 
3079     /* Combine memory type and cacheability attributes */
3080     if (s1hi == 0 || s2hi == 0) {
3081         /* Device has precedence over normal */
3082         if (s1lo == 0 || s2lo == 0) {
3083             /* nGnRnE has precedence over anything */
3084             ret_attrs = 0;
3085         } else if (s1lo == 4 || s2lo == 4) {
3086             /* non-Reordering has precedence over Reordering */
3087             ret_attrs = 4;  /* nGnRE */
3088         } else if (s1lo == 8 || s2lo == 8) {
3089             /* non-Gathering has precedence over Gathering */
3090             ret_attrs = 8;  /* nGRE */
3091         } else {
3092             ret_attrs = 0xc; /* GRE */
3093         }
3094     } else { /* Normal memory */
3095         /* Outer/inner cacheability combine independently */
3096         ret_attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
3097                   | combine_cacheattr_nibble(s1lo, s2lo);
3098     }
3099     return ret_attrs;
3100 }
3101 
3102 static uint8_t force_cacheattr_nibble_wb(uint8_t attr)
3103 {
3104     /*
3105      * Given the 4 bits specifying the outer or inner cacheability
3106      * in MAIR format, return a value specifying Normal Write-Back,
3107      * with the allocation and transient hints taken from the input
3108      * if the input specified some kind of cacheable attribute.
3109      */
3110     if (attr == 0 || attr == 4) {
3111         /*
3112          * 0 == an UNPREDICTABLE encoding
3113          * 4 == Non-cacheable
3114          * Either way, force Write-Back RW allocate non-transient
3115          */
3116         return 0xf;
3117     }
3118     /* Change WriteThrough to WriteBack, keep allocation and transient hints */
3119     return attr | 4;
3120 }
3121 
3122 /*
3123  * Combine the memory type and cacheability attributes of
3124  * s1 and s2 for the HCR_EL2.FWB == 1 case, returning the
3125  * combined attributes in MAIR_EL1 format.
3126  */
3127 static uint8_t combined_attrs_fwb(ARMCacheAttrs s1, ARMCacheAttrs s2)
3128 {
3129     assert(s2.is_s2_format && !s1.is_s2_format);
3130 
3131     switch (s2.attrs) {
3132     case 7:
3133         /* Use stage 1 attributes */
3134         return s1.attrs;
3135     case 6:
3136         /*
3137          * Force Normal Write-Back. Note that if S1 is Normal cacheable
3138          * then we take the allocation hints from it; otherwise it is
3139          * RW allocate, non-transient.
3140          */
3141         if ((s1.attrs & 0xf0) == 0) {
3142             /* S1 is Device */
3143             return 0xff;
3144         }
3145         /* Need to check the Inner and Outer nibbles separately */
3146         return force_cacheattr_nibble_wb(s1.attrs & 0xf) |
3147             force_cacheattr_nibble_wb(s1.attrs >> 4) << 4;
3148     case 5:
3149         /* If S1 attrs are Device, use them; otherwise Normal Non-cacheable */
3150         if ((s1.attrs & 0xf0) == 0) {
3151             return s1.attrs;
3152         }
3153         return 0x44;
3154     case 0 ... 3:
3155         /* Force Device, of subtype specified by S2 */
3156         return s2.attrs << 2;
3157     default:
3158         /*
3159          * RESERVED values (including RES0 descriptor bit [5] being nonzero);
3160          * arbitrarily force Device.
3161          */
3162         return 0;
3163     }
3164 }
3165 
3166 /*
3167  * Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
3168  * and CombineS1S2Desc()
3169  *
3170  * @env:     CPUARMState
3171  * @s1:      Attributes from stage 1 walk
3172  * @s2:      Attributes from stage 2 walk
3173  */
3174 static ARMCacheAttrs combine_cacheattrs(uint64_t hcr,
3175                                         ARMCacheAttrs s1, ARMCacheAttrs s2)
3176 {
3177     ARMCacheAttrs ret;
3178     bool tagged = false;
3179 
3180     assert(!s1.is_s2_format);
3181     ret.is_s2_format = false;
3182 
3183     if (s1.attrs == 0xf0) {
3184         tagged = true;
3185         s1.attrs = 0xff;
3186     }
3187 
3188     /* Combine shareability attributes (table D4-43) */
3189     if (s1.shareability == 2 || s2.shareability == 2) {
3190         /* if either are outer-shareable, the result is outer-shareable */
3191         ret.shareability = 2;
3192     } else if (s1.shareability == 3 || s2.shareability == 3) {
3193         /* if either are inner-shareable, the result is inner-shareable */
3194         ret.shareability = 3;
3195     } else {
3196         /* both non-shareable */
3197         ret.shareability = 0;
3198     }
3199 
3200     /* Combine memory type and cacheability attributes */
3201     if (hcr & HCR_FWB) {
3202         ret.attrs = combined_attrs_fwb(s1, s2);
3203     } else {
3204         ret.attrs = combined_attrs_nofwb(hcr, s1, s2);
3205     }
3206 
3207     /*
3208      * Any location for which the resultant memory type is any
3209      * type of Device memory is always treated as Outer Shareable.
3210      * Any location for which the resultant memory type is Normal
3211      * Inner Non-cacheable, Outer Non-cacheable is always treated
3212      * as Outer Shareable.
3213      * TODO: FEAT_XS adds another value (0x40) also meaning iNCoNC
3214      */
3215     if ((ret.attrs & 0xf0) == 0 || ret.attrs == 0x44) {
3216         ret.shareability = 2;
3217     }
3218 
3219     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
3220     if (tagged && ret.attrs == 0xff) {
3221         ret.attrs = 0xf0;
3222     }
3223 
3224     return ret;
3225 }
3226 
3227 /*
3228  * MMU disabled.  S1 addresses within aa64 translation regimes are
3229  * still checked for bounds -- see AArch64.S1DisabledOutput().
3230  */
3231 static bool get_phys_addr_disabled(CPUARMState *env,
3232                                    S1Translate *ptw,
3233                                    vaddr address,
3234                                    MMUAccessType access_type,
3235                                    GetPhysAddrResult *result,
3236                                    ARMMMUFaultInfo *fi)
3237 {
3238     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
3239     uint8_t memattr = 0x00;    /* Device nGnRnE */
3240     uint8_t shareability = 0;  /* non-shareable */
3241     int r_el;
3242 
3243     switch (mmu_idx) {
3244     case ARMMMUIdx_Stage2:
3245     case ARMMMUIdx_Stage2_S:
3246     case ARMMMUIdx_Phys_S:
3247     case ARMMMUIdx_Phys_NS:
3248     case ARMMMUIdx_Phys_Root:
3249     case ARMMMUIdx_Phys_Realm:
3250         break;
3251 
3252     default:
3253         r_el = regime_el(env, mmu_idx);
3254         if (arm_el_is_aa64(env, r_el)) {
3255             int pamax = arm_pamax(env_archcpu(env));
3256             uint64_t tcr = env->cp15.tcr_el[r_el];
3257             int addrtop, tbi;
3258 
3259             tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
3260             if (access_type == MMU_INST_FETCH) {
3261                 tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
3262             }
3263             tbi = (tbi >> extract64(address, 55, 1)) & 1;
3264             addrtop = (tbi ? 55 : 63);
3265 
3266             if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
3267                 fi->type = ARMFault_AddressSize;
3268                 fi->level = 0;
3269                 fi->stage2 = false;
3270                 return 1;
3271             }
3272 
3273             /*
3274              * When TBI is disabled, we've just validated that all of the
3275              * bits above PAMax are zero, so logically we only need to
3276              * clear the top byte for TBI.  But it's clearer to follow
3277              * the pseudocode set of addrdesc.paddress.
3278              */
3279             address = extract64(address, 0, 52);
3280         }
3281 
3282         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
3283         if (r_el == 1) {
3284             uint64_t hcr = arm_hcr_el2_eff_secstate(env, ptw->in_space);
3285             if (hcr & HCR_DC) {
3286                 if (hcr & HCR_DCT) {
3287                     memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
3288                 } else {
3289                     memattr = 0xff;  /* Normal, WB, RWA */
3290                 }
3291             }
3292         }
3293         if (memattr == 0) {
3294             if (access_type == MMU_INST_FETCH) {
3295                 if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
3296                     memattr = 0xee;  /* Normal, WT, RA, NT */
3297                 } else {
3298                     memattr = 0x44;  /* Normal, NC, No */
3299                 }
3300             }
3301             shareability = 2; /* outer shareable */
3302         }
3303         result->cacheattrs.is_s2_format = false;
3304         break;
3305     }
3306 
3307     result->f.phys_addr = address;
3308     result->f.prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
3309     result->f.lg_page_size = TARGET_PAGE_BITS;
3310     result->cacheattrs.shareability = shareability;
3311     result->cacheattrs.attrs = memattr;
3312     return false;
3313 }
3314 
3315 static bool get_phys_addr_twostage(CPUARMState *env, S1Translate *ptw,
3316                                    vaddr address,
3317                                    MMUAccessType access_type, MemOp memop,
3318                                    GetPhysAddrResult *result,
3319                                    ARMMMUFaultInfo *fi)
3320 {
3321     hwaddr ipa;
3322     int s1_prot, s1_lgpgsz;
3323     ARMSecuritySpace in_space = ptw->in_space;
3324     bool ret, ipa_secure, s1_guarded;
3325     ARMCacheAttrs cacheattrs1;
3326     ARMSecuritySpace ipa_space;
3327     uint64_t hcr;
3328 
3329     ret = get_phys_addr_nogpc(env, ptw, address, access_type,
3330                               memop, result, fi);
3331 
3332     /* If S1 fails, return early.  */
3333     if (ret) {
3334         return ret;
3335     }
3336 
3337     ipa = result->f.phys_addr;
3338     ipa_secure = result->f.attrs.secure;
3339     ipa_space = result->f.attrs.space;
3340 
3341     ptw->in_s1_is_el0 = ptw->in_mmu_idx == ARMMMUIdx_Stage1_E0;
3342     ptw->in_mmu_idx = ipa_secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
3343     ptw->in_space = ipa_space;
3344     ptw->in_ptw_idx = ptw_idx_for_stage_2(env, ptw->in_mmu_idx);
3345 
3346     /*
3347      * S1 is done, now do S2 translation.
3348      * Save the stage1 results so that we may merge prot and cacheattrs later.
3349      */
3350     s1_prot = result->f.prot;
3351     s1_lgpgsz = result->f.lg_page_size;
3352     s1_guarded = result->f.extra.arm.guarded;
3353     cacheattrs1 = result->cacheattrs;
3354     memset(result, 0, sizeof(*result));
3355 
3356     ret = get_phys_addr_nogpc(env, ptw, ipa, access_type,
3357                               memop, result, fi);
3358     fi->s2addr = ipa;
3359 
3360     /* Combine the S1 and S2 perms.  */
3361     result->f.prot &= s1_prot;
3362 
3363     /* If S2 fails, return early.  */
3364     if (ret) {
3365         return ret;
3366     }
3367 
3368     /*
3369      * If either S1 or S2 returned a result smaller than TARGET_PAGE_SIZE,
3370      * this means "don't put this in the TLB"; in this case, return a
3371      * result with lg_page_size == 0 to achieve that. Otherwise,
3372      * use the maximum of the S1 & S2 page size, so that invalidation
3373      * of pages > TARGET_PAGE_SIZE works correctly. (This works even though
3374      * we know the combined result permissions etc only cover the minimum
3375      * of the S1 and S2 page size, because we know that the common TLB code
3376      * never actually creates TLB entries bigger than TARGET_PAGE_SIZE,
3377      * and passing a larger page size value only affects invalidations.)
3378      */
3379     if (result->f.lg_page_size < TARGET_PAGE_BITS ||
3380         s1_lgpgsz < TARGET_PAGE_BITS) {
3381         result->f.lg_page_size = 0;
3382     } else if (result->f.lg_page_size < s1_lgpgsz) {
3383         result->f.lg_page_size = s1_lgpgsz;
3384     }
3385 
3386     /* Combine the S1 and S2 cache attributes. */
3387     hcr = arm_hcr_el2_eff_secstate(env, in_space);
3388     if (hcr & HCR_DC) {
3389         /*
3390          * HCR.DC forces the first stage attributes to
3391          *  Normal Non-Shareable,
3392          *  Inner Write-Back Read-Allocate Write-Allocate,
3393          *  Outer Write-Back Read-Allocate Write-Allocate.
3394          * Do not overwrite Tagged within attrs.
3395          */
3396         if (cacheattrs1.attrs != 0xf0) {
3397             cacheattrs1.attrs = 0xff;
3398         }
3399         cacheattrs1.shareability = 0;
3400     }
3401     result->cacheattrs = combine_cacheattrs(hcr, cacheattrs1,
3402                                             result->cacheattrs);
3403 
3404     /* No BTI GP information in stage 2, we just use the S1 value */
3405     result->f.extra.arm.guarded = s1_guarded;
3406 
3407     /*
3408      * Check if IPA translates to secure or non-secure PA space.
3409      * Note that VSTCR overrides VTCR and {N}SW overrides {N}SA.
3410      */
3411     if (in_space == ARMSS_Secure) {
3412         result->f.attrs.secure =
3413             !(env->cp15.vstcr_el2 & (VSTCR_SA | VSTCR_SW))
3414             && (ipa_secure
3415                 || !(env->cp15.vtcr_el2 & (VTCR_NSA | VTCR_NSW)));
3416         result->f.attrs.space = arm_secure_to_space(result->f.attrs.secure);
3417     }
3418 
3419     return false;
3420 }
3421 
3422 static bool get_phys_addr_nogpc(CPUARMState *env, S1Translate *ptw,
3423                                       vaddr address,
3424                                       MMUAccessType access_type, MemOp memop,
3425                                       GetPhysAddrResult *result,
3426                                       ARMMMUFaultInfo *fi)
3427 {
3428     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
3429     ARMMMUIdx s1_mmu_idx;
3430 
3431     /*
3432      * The page table entries may downgrade Secure to NonSecure, but
3433      * cannot upgrade a NonSecure translation regime's attributes
3434      * to Secure or Realm.
3435      */
3436     result->f.attrs.space = ptw->in_space;
3437     result->f.attrs.secure = arm_space_is_secure(ptw->in_space);
3438 
3439     switch (mmu_idx) {
3440     case ARMMMUIdx_Phys_S:
3441     case ARMMMUIdx_Phys_NS:
3442     case ARMMMUIdx_Phys_Root:
3443     case ARMMMUIdx_Phys_Realm:
3444         /* Checking Phys early avoids special casing later vs regime_el. */
3445         return get_phys_addr_disabled(env, ptw, address, access_type,
3446                                       result, fi);
3447 
3448     case ARMMMUIdx_Stage1_E0:
3449     case ARMMMUIdx_Stage1_E1:
3450     case ARMMMUIdx_Stage1_E1_PAN:
3451         /*
3452          * First stage lookup uses second stage for ptw; only
3453          * Secure has both S and NS IPA and starts with Stage2_S.
3454          */
3455         ptw->in_ptw_idx = (ptw->in_space == ARMSS_Secure) ?
3456             ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
3457         break;
3458 
3459     case ARMMMUIdx_Stage2:
3460     case ARMMMUIdx_Stage2_S:
3461         /*
3462          * Second stage lookup uses physical for ptw; whether this is S or
3463          * NS may depend on the SW/NSW bits if this is a stage 2 lookup for
3464          * the Secure EL2&0 regime.
3465          */
3466         ptw->in_ptw_idx = ptw_idx_for_stage_2(env, mmu_idx);
3467         break;
3468 
3469     case ARMMMUIdx_E10_0:
3470         s1_mmu_idx = ARMMMUIdx_Stage1_E0;
3471         goto do_twostage;
3472     case ARMMMUIdx_E10_1:
3473         s1_mmu_idx = ARMMMUIdx_Stage1_E1;
3474         goto do_twostage;
3475     case ARMMMUIdx_E10_1_PAN:
3476         s1_mmu_idx = ARMMMUIdx_Stage1_E1_PAN;
3477     do_twostage:
3478         /*
3479          * Call ourselves recursively to do the stage 1 and then stage 2
3480          * translations if mmu_idx is a two-stage regime, and EL2 present.
3481          * Otherwise, a stage1+stage2 translation is just stage 1.
3482          */
3483         ptw->in_mmu_idx = mmu_idx = s1_mmu_idx;
3484         if (arm_feature(env, ARM_FEATURE_EL2) &&
3485             !regime_translation_disabled(env, ARMMMUIdx_Stage2, ptw->in_space)) {
3486             return get_phys_addr_twostage(env, ptw, address, access_type,
3487                                           memop, result, fi);
3488         }
3489         /* fall through */
3490 
3491     default:
3492         /* Single stage uses physical for ptw. */
3493         ptw->in_ptw_idx = arm_space_to_phys(ptw->in_space);
3494         break;
3495     }
3496 
3497     result->f.attrs.user = regime_is_user(env, mmu_idx);
3498 
3499     /*
3500      * Fast Context Switch Extension. This doesn't exist at all in v8.
3501      * In v7 and earlier it affects all stage 1 translations.
3502      */
3503     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
3504         && !arm_feature(env, ARM_FEATURE_V8)) {
3505         if (regime_el(env, mmu_idx) == 3) {
3506             address += env->cp15.fcseidr_s;
3507         } else {
3508             address += env->cp15.fcseidr_ns;
3509         }
3510     }
3511 
3512     if (arm_feature(env, ARM_FEATURE_PMSA)) {
3513         bool ret;
3514         result->f.lg_page_size = TARGET_PAGE_BITS;
3515 
3516         if (arm_feature(env, ARM_FEATURE_V8)) {
3517             /* PMSAv8 */
3518             ret = get_phys_addr_pmsav8(env, ptw, address, access_type,
3519                                        result, fi);
3520         } else if (arm_feature(env, ARM_FEATURE_V7)) {
3521             /* PMSAv7 */
3522             ret = get_phys_addr_pmsav7(env, ptw, address, access_type,
3523                                        result, fi);
3524         } else {
3525             /* Pre-v7 MPU */
3526             ret = get_phys_addr_pmsav5(env, ptw, address, access_type,
3527                                        result, fi);
3528         }
3529         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
3530                       " mmu_idx %u -> %s (prot %c%c%c)\n",
3531                       access_type == MMU_DATA_LOAD ? "reading" :
3532                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
3533                       (uint32_t)address, mmu_idx,
3534                       ret ? "Miss" : "Hit",
3535                       result->f.prot & PAGE_READ ? 'r' : '-',
3536                       result->f.prot & PAGE_WRITE ? 'w' : '-',
3537                       result->f.prot & PAGE_EXEC ? 'x' : '-');
3538 
3539         return ret;
3540     }
3541 
3542     /* Definitely a real MMU, not an MPU */
3543 
3544     if (regime_translation_disabled(env, mmu_idx, ptw->in_space)) {
3545         return get_phys_addr_disabled(env, ptw, address, access_type,
3546                                       result, fi);
3547     }
3548 
3549     if (regime_using_lpae_format(env, mmu_idx)) {
3550         return get_phys_addr_lpae(env, ptw, address, access_type,
3551                                   memop, result, fi);
3552     } else if (arm_feature(env, ARM_FEATURE_V7) ||
3553                regime_sctlr(env, mmu_idx) & SCTLR_XP) {
3554         return get_phys_addr_v6(env, ptw, address, access_type, result, fi);
3555     } else {
3556         return get_phys_addr_v5(env, ptw, address, access_type, result, fi);
3557     }
3558 }
3559 
3560 static bool get_phys_addr_gpc(CPUARMState *env, S1Translate *ptw,
3561                               vaddr address,
3562                               MMUAccessType access_type, MemOp memop,
3563                               GetPhysAddrResult *result,
3564                               ARMMMUFaultInfo *fi)
3565 {
3566     if (get_phys_addr_nogpc(env, ptw, address, access_type,
3567                             memop, result, fi)) {
3568         return true;
3569     }
3570     if (!granule_protection_check(env, result->f.phys_addr,
3571                                   result->f.attrs.space, fi)) {
3572         fi->type = ARMFault_GPCFOnOutput;
3573         return true;
3574     }
3575     return false;
3576 }
3577 
3578 bool get_phys_addr_with_space_nogpc(CPUARMState *env, vaddr address,
3579                                     MMUAccessType access_type, MemOp memop,
3580                                     ARMMMUIdx mmu_idx, ARMSecuritySpace space,
3581                                     GetPhysAddrResult *result,
3582                                     ARMMMUFaultInfo *fi)
3583 {
3584     S1Translate ptw = {
3585         .in_mmu_idx = mmu_idx,
3586         .in_space = space,
3587     };
3588     return get_phys_addr_nogpc(env, &ptw, address, access_type,
3589                                memop, result, fi);
3590 }
3591 
3592 bool get_phys_addr(CPUARMState *env, vaddr address,
3593                    MMUAccessType access_type, MemOp memop, ARMMMUIdx mmu_idx,
3594                    GetPhysAddrResult *result, ARMMMUFaultInfo *fi)
3595 {
3596     S1Translate ptw = {
3597         .in_mmu_idx = mmu_idx,
3598     };
3599     ARMSecuritySpace ss;
3600 
3601     switch (mmu_idx) {
3602     case ARMMMUIdx_E10_0:
3603     case ARMMMUIdx_E10_1:
3604     case ARMMMUIdx_E10_1_PAN:
3605     case ARMMMUIdx_E20_0:
3606     case ARMMMUIdx_E20_2:
3607     case ARMMMUIdx_E20_2_PAN:
3608     case ARMMMUIdx_Stage1_E0:
3609     case ARMMMUIdx_Stage1_E1:
3610     case ARMMMUIdx_Stage1_E1_PAN:
3611     case ARMMMUIdx_E2:
3612         ss = arm_security_space_below_el3(env);
3613         break;
3614     case ARMMMUIdx_Stage2:
3615         /*
3616          * For Secure EL2, we need this index to be NonSecure;
3617          * otherwise this will already be NonSecure or Realm.
3618          */
3619         ss = arm_security_space_below_el3(env);
3620         if (ss == ARMSS_Secure) {
3621             ss = ARMSS_NonSecure;
3622         }
3623         break;
3624     case ARMMMUIdx_Phys_NS:
3625     case ARMMMUIdx_MPrivNegPri:
3626     case ARMMMUIdx_MUserNegPri:
3627     case ARMMMUIdx_MPriv:
3628     case ARMMMUIdx_MUser:
3629         ss = ARMSS_NonSecure;
3630         break;
3631     case ARMMMUIdx_Stage2_S:
3632     case ARMMMUIdx_Phys_S:
3633     case ARMMMUIdx_MSPrivNegPri:
3634     case ARMMMUIdx_MSUserNegPri:
3635     case ARMMMUIdx_MSPriv:
3636     case ARMMMUIdx_MSUser:
3637         ss = ARMSS_Secure;
3638         break;
3639     case ARMMMUIdx_E3:
3640     case ARMMMUIdx_E30_0:
3641     case ARMMMUIdx_E30_3_PAN:
3642         if (arm_feature(env, ARM_FEATURE_AARCH64) &&
3643             cpu_isar_feature(aa64_rme, env_archcpu(env))) {
3644             ss = ARMSS_Root;
3645         } else {
3646             ss = ARMSS_Secure;
3647         }
3648         break;
3649     case ARMMMUIdx_Phys_Root:
3650         ss = ARMSS_Root;
3651         break;
3652     case ARMMMUIdx_Phys_Realm:
3653         ss = ARMSS_Realm;
3654         break;
3655     default:
3656         g_assert_not_reached();
3657     }
3658 
3659     ptw.in_space = ss;
3660     return get_phys_addr_gpc(env, &ptw, address, access_type,
3661                              memop, result, fi);
3662 }
3663 
3664 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
3665                                          MemTxAttrs *attrs)
3666 {
3667     ARMCPU *cpu = ARM_CPU(cs);
3668     CPUARMState *env = &cpu->env;
3669     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
3670     ARMSecuritySpace ss = arm_security_space(env);
3671     S1Translate ptw = {
3672         .in_mmu_idx = mmu_idx,
3673         .in_space = ss,
3674         .in_debug = true,
3675     };
3676     GetPhysAddrResult res = {};
3677     ARMMMUFaultInfo fi = {};
3678     bool ret;
3679 
3680     ret = get_phys_addr_gpc(env, &ptw, addr, MMU_DATA_LOAD, 0, &res, &fi);
3681     *attrs = res.f.attrs;
3682 
3683     if (ret) {
3684         return -1;
3685     }
3686     return res.f.phys_addr;
3687 }
3688