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