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