xref: /openbmc/qemu/target/arm/ptw.c (revision 64bda5106c56faa19a31e091aef3a08249cc4ad0)
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     if (!(result->f.prot & (1 << access_type))) {
2133         fi->type = ARMFault_Permission;
2134         goto do_fault;
2135     }
2136 
2137     /* If FEAT_HAFDBS has made changes, update the PTE. */
2138     if (new_descriptor != descriptor) {
2139         new_descriptor = arm_casq_ptw(env, descriptor, new_descriptor, ptw, fi);
2140         if (fi->type != ARMFault_None) {
2141             goto do_fault;
2142         }
2143         /*
2144          * I_YZSVV says that if the in-memory descriptor has changed,
2145          * then we must use the information in that new value
2146          * (which might include a different output address, different
2147          * attributes, or generate a fault).
2148          * Restart the handling of the descriptor value from scratch.
2149          */
2150         if (new_descriptor != descriptor) {
2151             descriptor = new_descriptor;
2152             goto restart_atomic_update;
2153         }
2154     }
2155 
2156     result->f.attrs.space = out_space;
2157     result->f.attrs.secure = arm_space_is_secure(out_space);
2158 
2159     /*
2160      * Enable alignment checks on Device memory.
2161      *
2162      * Per R_XCHFJ, this check is mis-ordered. The correct ordering
2163      * for alignment, permission, and stage 2 faults should be:
2164      *    - Alignment fault caused by the memory type
2165      *    - Permission fault
2166      *    - A stage 2 fault on the memory access
2167      * but due to the way the TCG softmmu TLB operates, we will have
2168      * implicitly done the permission check and the stage2 lookup in
2169      * finding the TLB entry, so the alignment check cannot be done sooner.
2170      *
2171      * In v7, for a CPU without the Virtualization Extensions this
2172      * access is UNPREDICTABLE; we choose to make it take the alignment
2173      * fault as is required for a v7VE CPU. (QEMU doesn't emulate any
2174      * CPUs with ARM_FEATURE_LPAE but not ARM_FEATURE_V7VE anyway.)
2175      */
2176     if (device) {
2177         result->f.tlb_fill_flags |= TLB_CHECK_ALIGNED;
2178     }
2179 
2180     /*
2181      * For FEAT_LPA2 and effective DS, the SH field in the attributes
2182      * was re-purposed for output address bits.  The SH attribute in
2183      * that case comes from TCR_ELx, which we extracted earlier.
2184      */
2185     if (param.ds) {
2186         result->cacheattrs.shareability = param.sh;
2187     } else {
2188         result->cacheattrs.shareability = extract32(attrs, 8, 2);
2189     }
2190 
2191     result->f.phys_addr = descaddr;
2192     result->f.lg_page_size = ctz64(page_size);
2193     return false;
2194 
2195  do_translation_fault:
2196     fi->type = ARMFault_Translation;
2197  do_fault:
2198     if (fi->s1ptw) {
2199         /* Retain the existing stage 2 fi->level */
2200         assert(fi->stage2);
2201     } else {
2202         fi->level = level;
2203         fi->stage2 = regime_is_stage2(mmu_idx);
2204     }
2205     fi->s1ns = fault_s1ns(ptw->in_space, mmu_idx);
2206     return true;
2207 }
2208 
2209 static bool get_phys_addr_pmsav5(CPUARMState *env,
2210                                  S1Translate *ptw,
2211                                  uint32_t address,
2212                                  MMUAccessType access_type,
2213                                  GetPhysAddrResult *result,
2214                                  ARMMMUFaultInfo *fi)
2215 {
2216     int n;
2217     uint32_t mask;
2218     uint32_t base;
2219     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
2220     bool is_user = regime_is_user(env, mmu_idx);
2221 
2222     if (regime_translation_disabled(env, mmu_idx, ptw->in_space)) {
2223         /* MPU disabled.  */
2224         result->f.phys_addr = address;
2225         result->f.prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
2226         return false;
2227     }
2228 
2229     result->f.phys_addr = address;
2230     for (n = 7; n >= 0; n--) {
2231         base = env->cp15.c6_region[n];
2232         if ((base & 1) == 0) {
2233             continue;
2234         }
2235         mask = 1 << ((base >> 1) & 0x1f);
2236         /* Keep this shift separate from the above to avoid an
2237            (undefined) << 32.  */
2238         mask = (mask << 1) - 1;
2239         if (((base ^ address) & ~mask) == 0) {
2240             break;
2241         }
2242     }
2243     if (n < 0) {
2244         fi->type = ARMFault_Background;
2245         return true;
2246     }
2247 
2248     if (access_type == MMU_INST_FETCH) {
2249         mask = env->cp15.pmsav5_insn_ap;
2250     } else {
2251         mask = env->cp15.pmsav5_data_ap;
2252     }
2253     mask = (mask >> (n * 4)) & 0xf;
2254     switch (mask) {
2255     case 0:
2256         fi->type = ARMFault_Permission;
2257         fi->level = 1;
2258         return true;
2259     case 1:
2260         if (is_user) {
2261             fi->type = ARMFault_Permission;
2262             fi->level = 1;
2263             return true;
2264         }
2265         result->f.prot = PAGE_READ | PAGE_WRITE;
2266         break;
2267     case 2:
2268         result->f.prot = PAGE_READ;
2269         if (!is_user) {
2270             result->f.prot |= PAGE_WRITE;
2271         }
2272         break;
2273     case 3:
2274         result->f.prot = PAGE_READ | PAGE_WRITE;
2275         break;
2276     case 5:
2277         if (is_user) {
2278             fi->type = ARMFault_Permission;
2279             fi->level = 1;
2280             return true;
2281         }
2282         result->f.prot = PAGE_READ;
2283         break;
2284     case 6:
2285         result->f.prot = PAGE_READ;
2286         break;
2287     default:
2288         /* Bad permission.  */
2289         fi->type = ARMFault_Permission;
2290         fi->level = 1;
2291         return true;
2292     }
2293     result->f.prot |= PAGE_EXEC;
2294     return false;
2295 }
2296 
2297 static void get_phys_addr_pmsav7_default(CPUARMState *env, ARMMMUIdx mmu_idx,
2298                                          int32_t address, uint8_t *prot)
2299 {
2300     if (!arm_feature(env, ARM_FEATURE_M)) {
2301         *prot = PAGE_READ | PAGE_WRITE;
2302         switch (address) {
2303         case 0xF0000000 ... 0xFFFFFFFF:
2304             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
2305                 /* hivecs execing is ok */
2306                 *prot |= PAGE_EXEC;
2307             }
2308             break;
2309         case 0x00000000 ... 0x7FFFFFFF:
2310             *prot |= PAGE_EXEC;
2311             break;
2312         }
2313     } else {
2314         /* Default system address map for M profile cores.
2315          * The architecture specifies which regions are execute-never;
2316          * at the MPU level no other checks are defined.
2317          */
2318         switch (address) {
2319         case 0x00000000 ... 0x1fffffff: /* ROM */
2320         case 0x20000000 ... 0x3fffffff: /* SRAM */
2321         case 0x60000000 ... 0x7fffffff: /* RAM */
2322         case 0x80000000 ... 0x9fffffff: /* RAM */
2323             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
2324             break;
2325         case 0x40000000 ... 0x5fffffff: /* Peripheral */
2326         case 0xa0000000 ... 0xbfffffff: /* Device */
2327         case 0xc0000000 ... 0xdfffffff: /* Device */
2328         case 0xe0000000 ... 0xffffffff: /* System */
2329             *prot = PAGE_READ | PAGE_WRITE;
2330             break;
2331         default:
2332             g_assert_not_reached();
2333         }
2334     }
2335 }
2336 
2337 static bool m_is_ppb_region(CPUARMState *env, uint32_t address)
2338 {
2339     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
2340     return arm_feature(env, ARM_FEATURE_M) &&
2341         extract32(address, 20, 12) == 0xe00;
2342 }
2343 
2344 static bool m_is_system_region(CPUARMState *env, uint32_t address)
2345 {
2346     /*
2347      * True if address is in the M profile system region
2348      * 0xe0000000 - 0xffffffff
2349      */
2350     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
2351 }
2352 
2353 static bool pmsav7_use_background_region(ARMCPU *cpu, ARMMMUIdx mmu_idx,
2354                                          bool is_secure, bool is_user)
2355 {
2356     /*
2357      * Return true if we should use the default memory map as a
2358      * "background" region if there are no hits against any MPU regions.
2359      */
2360     CPUARMState *env = &cpu->env;
2361 
2362     if (is_user) {
2363         return false;
2364     }
2365 
2366     if (arm_feature(env, ARM_FEATURE_M)) {
2367         return env->v7m.mpu_ctrl[is_secure] & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
2368     }
2369 
2370     if (mmu_idx == ARMMMUIdx_Stage2) {
2371         return false;
2372     }
2373 
2374     return regime_sctlr(env, mmu_idx) & SCTLR_BR;
2375 }
2376 
2377 static bool get_phys_addr_pmsav7(CPUARMState *env,
2378                                  S1Translate *ptw,
2379                                  uint32_t address,
2380                                  MMUAccessType access_type,
2381                                  GetPhysAddrResult *result,
2382                                  ARMMMUFaultInfo *fi)
2383 {
2384     ARMCPU *cpu = env_archcpu(env);
2385     int n;
2386     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
2387     bool is_user = regime_is_user(env, mmu_idx);
2388     bool secure = arm_space_is_secure(ptw->in_space);
2389 
2390     result->f.phys_addr = address;
2391     result->f.lg_page_size = TARGET_PAGE_BITS;
2392     result->f.prot = 0;
2393 
2394     if (regime_translation_disabled(env, mmu_idx, ptw->in_space) ||
2395         m_is_ppb_region(env, address)) {
2396         /*
2397          * MPU disabled or M profile PPB access: use default memory map.
2398          * The other case which uses the default memory map in the
2399          * v7M ARM ARM pseudocode is exception vector reads from the vector
2400          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
2401          * which always does a direct read using address_space_ldl(), rather
2402          * than going via this function, so we don't need to check that here.
2403          */
2404         get_phys_addr_pmsav7_default(env, mmu_idx, address, &result->f.prot);
2405     } else { /* MPU enabled */
2406         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
2407             /* region search */
2408             uint32_t base = env->pmsav7.drbar[n];
2409             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
2410             uint32_t rmask;
2411             bool srdis = false;
2412 
2413             if (!(env->pmsav7.drsr[n] & 0x1)) {
2414                 continue;
2415             }
2416 
2417             if (!rsize) {
2418                 qemu_log_mask(LOG_GUEST_ERROR,
2419                               "DRSR[%d]: Rsize field cannot be 0\n", n);
2420                 continue;
2421             }
2422             rsize++;
2423             rmask = (1ull << rsize) - 1;
2424 
2425             if (base & rmask) {
2426                 qemu_log_mask(LOG_GUEST_ERROR,
2427                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
2428                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
2429                               n, base, rmask);
2430                 continue;
2431             }
2432 
2433             if (address < base || address > base + rmask) {
2434                 /*
2435                  * Address not in this region. We must check whether the
2436                  * region covers addresses in the same page as our address.
2437                  * In that case we must not report a size that covers the
2438                  * whole page for a subsequent hit against a different MPU
2439                  * region or the background region, because it would result in
2440                  * incorrect TLB hits for subsequent accesses to addresses that
2441                  * are in this MPU region.
2442                  */
2443                 if (ranges_overlap(base, rmask,
2444                                    address & TARGET_PAGE_MASK,
2445                                    TARGET_PAGE_SIZE)) {
2446                     result->f.lg_page_size = 0;
2447                 }
2448                 continue;
2449             }
2450 
2451             /* Region matched */
2452 
2453             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
2454                 int i, snd;
2455                 uint32_t srdis_mask;
2456 
2457                 rsize -= 3; /* sub region size (power of 2) */
2458                 snd = ((address - base) >> rsize) & 0x7;
2459                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
2460 
2461                 srdis_mask = srdis ? 0x3 : 0x0;
2462                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
2463                     /*
2464                      * This will check in groups of 2, 4 and then 8, whether
2465                      * the subregion bits are consistent. rsize is incremented
2466                      * back up to give the region size, considering consistent
2467                      * adjacent subregions as one region. Stop testing if rsize
2468                      * is already big enough for an entire QEMU page.
2469                      */
2470                     int snd_rounded = snd & ~(i - 1);
2471                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
2472                                                      snd_rounded + 8, i);
2473                     if (srdis_mask ^ srdis_multi) {
2474                         break;
2475                     }
2476                     srdis_mask = (srdis_mask << i) | srdis_mask;
2477                     rsize++;
2478                 }
2479             }
2480             if (srdis) {
2481                 continue;
2482             }
2483             if (rsize < TARGET_PAGE_BITS) {
2484                 result->f.lg_page_size = rsize;
2485             }
2486             break;
2487         }
2488 
2489         if (n == -1) { /* no hits */
2490             if (!pmsav7_use_background_region(cpu, mmu_idx, secure, is_user)) {
2491                 /* background fault */
2492                 fi->type = ARMFault_Background;
2493                 return true;
2494             }
2495             get_phys_addr_pmsav7_default(env, mmu_idx, address,
2496                                          &result->f.prot);
2497         } else { /* a MPU hit! */
2498             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
2499             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
2500 
2501             if (m_is_system_region(env, address)) {
2502                 /* System space is always execute never */
2503                 xn = 1;
2504             }
2505 
2506             if (is_user) { /* User mode AP bit decoding */
2507                 switch (ap) {
2508                 case 0:
2509                 case 1:
2510                 case 5:
2511                     break; /* no access */
2512                 case 3:
2513                     result->f.prot |= PAGE_WRITE;
2514                     /* fall through */
2515                 case 2:
2516                 case 6:
2517                     result->f.prot |= PAGE_READ | PAGE_EXEC;
2518                     break;
2519                 case 7:
2520                     /* for v7M, same as 6; for R profile a reserved value */
2521                     if (arm_feature(env, ARM_FEATURE_M)) {
2522                         result->f.prot |= PAGE_READ | PAGE_EXEC;
2523                         break;
2524                     }
2525                     /* fall through */
2526                 default:
2527                     qemu_log_mask(LOG_GUEST_ERROR,
2528                                   "DRACR[%d]: Bad value for AP bits: 0x%"
2529                                   PRIx32 "\n", n, ap);
2530                 }
2531             } else { /* Priv. mode AP bits decoding */
2532                 switch (ap) {
2533                 case 0:
2534                     break; /* no access */
2535                 case 1:
2536                 case 2:
2537                 case 3:
2538                     result->f.prot |= PAGE_WRITE;
2539                     /* fall through */
2540                 case 5:
2541                 case 6:
2542                     result->f.prot |= PAGE_READ | PAGE_EXEC;
2543                     break;
2544                 case 7:
2545                     /* for v7M, same as 6; for R profile a reserved value */
2546                     if (arm_feature(env, ARM_FEATURE_M)) {
2547                         result->f.prot |= PAGE_READ | PAGE_EXEC;
2548                         break;
2549                     }
2550                     /* fall through */
2551                 default:
2552                     qemu_log_mask(LOG_GUEST_ERROR,
2553                                   "DRACR[%d]: Bad value for AP bits: 0x%"
2554                                   PRIx32 "\n", n, ap);
2555                 }
2556             }
2557 
2558             /* execute never */
2559             if (xn) {
2560                 result->f.prot &= ~PAGE_EXEC;
2561             }
2562         }
2563     }
2564 
2565     fi->type = ARMFault_Permission;
2566     fi->level = 1;
2567     return !(result->f.prot & (1 << access_type));
2568 }
2569 
2570 static uint32_t *regime_rbar(CPUARMState *env, ARMMMUIdx mmu_idx,
2571                              uint32_t secure)
2572 {
2573     if (regime_el(env, mmu_idx) == 2) {
2574         return env->pmsav8.hprbar;
2575     } else {
2576         return env->pmsav8.rbar[secure];
2577     }
2578 }
2579 
2580 static uint32_t *regime_rlar(CPUARMState *env, ARMMMUIdx mmu_idx,
2581                              uint32_t secure)
2582 {
2583     if (regime_el(env, mmu_idx) == 2) {
2584         return env->pmsav8.hprlar;
2585     } else {
2586         return env->pmsav8.rlar[secure];
2587     }
2588 }
2589 
2590 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
2591                        MMUAccessType access_type, ARMMMUIdx mmu_idx,
2592                        bool secure, GetPhysAddrResult *result,
2593                        ARMMMUFaultInfo *fi, uint32_t *mregion)
2594 {
2595     /*
2596      * Perform a PMSAv8 MPU lookup (without also doing the SAU check
2597      * that a full phys-to-virt translation does).
2598      * mregion is (if not NULL) set to the region number which matched,
2599      * or -1 if no region number is returned (MPU off, address did not
2600      * hit a region, address hit in multiple regions).
2601      * If the region hit doesn't cover the entire TARGET_PAGE the address
2602      * is within, then we set the result page_size to 1 to force the
2603      * memory system to use a subpage.
2604      */
2605     ARMCPU *cpu = env_archcpu(env);
2606     bool is_user = regime_is_user(env, mmu_idx);
2607     int n;
2608     int matchregion = -1;
2609     bool hit = false;
2610     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
2611     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
2612     int region_counter;
2613 
2614     if (regime_el(env, mmu_idx) == 2) {
2615         region_counter = cpu->pmsav8r_hdregion;
2616     } else {
2617         region_counter = cpu->pmsav7_dregion;
2618     }
2619 
2620     result->f.lg_page_size = TARGET_PAGE_BITS;
2621     result->f.phys_addr = address;
2622     result->f.prot = 0;
2623     if (mregion) {
2624         *mregion = -1;
2625     }
2626 
2627     if (mmu_idx == ARMMMUIdx_Stage2) {
2628         fi->stage2 = true;
2629     }
2630 
2631     /*
2632      * Unlike the ARM ARM pseudocode, we don't need to check whether this
2633      * was an exception vector read from the vector table (which is always
2634      * done using the default system address map), because those accesses
2635      * are done in arm_v7m_load_vector(), which always does a direct
2636      * read using address_space_ldl(), rather than going via this function.
2637      */
2638     if (regime_translation_disabled(env, mmu_idx, arm_secure_to_space(secure))) {
2639         /* MPU disabled */
2640         hit = true;
2641     } else if (m_is_ppb_region(env, address)) {
2642         hit = true;
2643     } else {
2644         if (pmsav7_use_background_region(cpu, mmu_idx, secure, is_user)) {
2645             hit = true;
2646         }
2647 
2648         uint32_t bitmask;
2649         if (arm_feature(env, ARM_FEATURE_M)) {
2650             bitmask = 0x1f;
2651         } else {
2652             bitmask = 0x3f;
2653             fi->level = 0;
2654         }
2655 
2656         for (n = region_counter - 1; n >= 0; n--) {
2657             /* region search */
2658             /*
2659              * Note that the base address is bits [31:x] from the register
2660              * with bits [x-1:0] all zeroes, but the limit address is bits
2661              * [31:x] from the register with bits [x:0] all ones. Where x is
2662              * 5 for Cortex-M and 6 for Cortex-R
2663              */
2664             uint32_t base = regime_rbar(env, mmu_idx, secure)[n] & ~bitmask;
2665             uint32_t limit = regime_rlar(env, mmu_idx, secure)[n] | bitmask;
2666 
2667             if (!(regime_rlar(env, mmu_idx, secure)[n] & 0x1)) {
2668                 /* Region disabled */
2669                 continue;
2670             }
2671 
2672             if (address < base || address > limit) {
2673                 /*
2674                  * Address not in this region. We must check whether the
2675                  * region covers addresses in the same page as our address.
2676                  * In that case we must not report a size that covers the
2677                  * whole page for a subsequent hit against a different MPU
2678                  * region or the background region, because it would result in
2679                  * incorrect TLB hits for subsequent accesses to addresses that
2680                  * are in this MPU region.
2681                  */
2682                 if (limit >= base &&
2683                     ranges_overlap(base, limit - base + 1,
2684                                    addr_page_base,
2685                                    TARGET_PAGE_SIZE)) {
2686                     result->f.lg_page_size = 0;
2687                 }
2688                 continue;
2689             }
2690 
2691             if (base > addr_page_base || limit < addr_page_limit) {
2692                 result->f.lg_page_size = 0;
2693             }
2694 
2695             if (matchregion != -1) {
2696                 /*
2697                  * Multiple regions match -- always a failure (unlike
2698                  * PMSAv7 where highest-numbered-region wins)
2699                  */
2700                 fi->type = ARMFault_Permission;
2701                 if (arm_feature(env, ARM_FEATURE_M)) {
2702                     fi->level = 1;
2703                 }
2704                 return true;
2705             }
2706 
2707             matchregion = n;
2708             hit = true;
2709         }
2710     }
2711 
2712     if (!hit) {
2713         if (arm_feature(env, ARM_FEATURE_M)) {
2714             fi->type = ARMFault_Background;
2715         } else {
2716             fi->type = ARMFault_Permission;
2717         }
2718         return true;
2719     }
2720 
2721     if (matchregion == -1) {
2722         /* hit using the background region */
2723         get_phys_addr_pmsav7_default(env, mmu_idx, address, &result->f.prot);
2724     } else {
2725         uint32_t matched_rbar = regime_rbar(env, mmu_idx, secure)[matchregion];
2726         uint32_t matched_rlar = regime_rlar(env, mmu_idx, secure)[matchregion];
2727         uint32_t ap = extract32(matched_rbar, 1, 2);
2728         uint32_t xn = extract32(matched_rbar, 0, 1);
2729         bool pxn = false;
2730 
2731         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
2732             pxn = extract32(matched_rlar, 4, 1);
2733         }
2734 
2735         if (m_is_system_region(env, address)) {
2736             /* System space is always execute never */
2737             xn = 1;
2738         }
2739 
2740         if (regime_el(env, mmu_idx) == 2) {
2741             result->f.prot = simple_ap_to_rw_prot_is_user(ap,
2742                                             mmu_idx != ARMMMUIdx_E2);
2743         } else {
2744             result->f.prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
2745         }
2746 
2747         if (!arm_feature(env, ARM_FEATURE_M)) {
2748             uint8_t attrindx = extract32(matched_rlar, 1, 3);
2749             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
2750             uint8_t sh = extract32(matched_rlar, 3, 2);
2751 
2752             if (regime_sctlr(env, mmu_idx) & SCTLR_WXN &&
2753                 result->f.prot & PAGE_WRITE && mmu_idx != ARMMMUIdx_Stage2) {
2754                 xn = 0x1;
2755             }
2756 
2757             if ((regime_el(env, mmu_idx) == 1) &&
2758                 regime_sctlr(env, mmu_idx) & SCTLR_UWXN && ap == 0x1) {
2759                 pxn = 0x1;
2760             }
2761 
2762             result->cacheattrs.is_s2_format = false;
2763             result->cacheattrs.attrs = extract64(mair, attrindx * 8, 8);
2764             result->cacheattrs.shareability = sh;
2765         }
2766 
2767         if (result->f.prot && !xn && !(pxn && !is_user)) {
2768             result->f.prot |= PAGE_EXEC;
2769         }
2770 
2771         if (mregion) {
2772             *mregion = matchregion;
2773         }
2774     }
2775 
2776     fi->type = ARMFault_Permission;
2777     if (arm_feature(env, ARM_FEATURE_M)) {
2778         fi->level = 1;
2779     }
2780     return !(result->f.prot & (1 << access_type));
2781 }
2782 
2783 static bool v8m_is_sau_exempt(CPUARMState *env,
2784                               uint32_t address, MMUAccessType access_type)
2785 {
2786     /*
2787      * The architecture specifies that certain address ranges are
2788      * exempt from v8M SAU/IDAU checks.
2789      */
2790     return
2791         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
2792         (address >= 0xe0000000 && address <= 0xe0002fff) ||
2793         (address >= 0xe000e000 && address <= 0xe000efff) ||
2794         (address >= 0xe002e000 && address <= 0xe002efff) ||
2795         (address >= 0xe0040000 && address <= 0xe0041fff) ||
2796         (address >= 0xe00ff000 && address <= 0xe00fffff);
2797 }
2798 
2799 void v8m_security_lookup(CPUARMState *env, uint32_t address,
2800                          MMUAccessType access_type, ARMMMUIdx mmu_idx,
2801                          bool is_secure, V8M_SAttributes *sattrs)
2802 {
2803     /*
2804      * Look up the security attributes for this address. Compare the
2805      * pseudocode SecurityCheck() function.
2806      * We assume the caller has zero-initialized *sattrs.
2807      */
2808     ARMCPU *cpu = env_archcpu(env);
2809     int r;
2810     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
2811     int idau_region = IREGION_NOTVALID;
2812     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
2813     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
2814 
2815     if (cpu->idau) {
2816         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
2817         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
2818 
2819         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
2820                    &idau_nsc);
2821     }
2822 
2823     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
2824         /* 0xf0000000..0xffffffff is always S for insn fetches */
2825         return;
2826     }
2827 
2828     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
2829         sattrs->ns = !is_secure;
2830         return;
2831     }
2832 
2833     if (idau_region != IREGION_NOTVALID) {
2834         sattrs->irvalid = true;
2835         sattrs->iregion = idau_region;
2836     }
2837 
2838     switch (env->sau.ctrl & 3) {
2839     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
2840         break;
2841     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
2842         sattrs->ns = true;
2843         break;
2844     default: /* SAU.ENABLE == 1 */
2845         for (r = 0; r < cpu->sau_sregion; r++) {
2846             if (env->sau.rlar[r] & 1) {
2847                 uint32_t base = env->sau.rbar[r] & ~0x1f;
2848                 uint32_t limit = env->sau.rlar[r] | 0x1f;
2849 
2850                 if (base <= address && limit >= address) {
2851                     if (base > addr_page_base || limit < addr_page_limit) {
2852                         sattrs->subpage = true;
2853                     }
2854                     if (sattrs->srvalid) {
2855                         /*
2856                          * If we hit in more than one region then we must report
2857                          * as Secure, not NS-Callable, with no valid region
2858                          * number info.
2859                          */
2860                         sattrs->ns = false;
2861                         sattrs->nsc = false;
2862                         sattrs->sregion = 0;
2863                         sattrs->srvalid = false;
2864                         break;
2865                     } else {
2866                         if (env->sau.rlar[r] & 2) {
2867                             sattrs->nsc = true;
2868                         } else {
2869                             sattrs->ns = true;
2870                         }
2871                         sattrs->srvalid = true;
2872                         sattrs->sregion = r;
2873                     }
2874                 } else {
2875                     /*
2876                      * Address not in this region. We must check whether the
2877                      * region covers addresses in the same page as our address.
2878                      * In that case we must not report a size that covers the
2879                      * whole page for a subsequent hit against a different MPU
2880                      * region or the background region, because it would result
2881                      * in incorrect TLB hits for subsequent accesses to
2882                      * addresses that are in this MPU region.
2883                      */
2884                     if (limit >= base &&
2885                         ranges_overlap(base, limit - base + 1,
2886                                        addr_page_base,
2887                                        TARGET_PAGE_SIZE)) {
2888                         sattrs->subpage = true;
2889                     }
2890                 }
2891             }
2892         }
2893         break;
2894     }
2895 
2896     /*
2897      * The IDAU will override the SAU lookup results if it specifies
2898      * higher security than the SAU does.
2899      */
2900     if (!idau_ns) {
2901         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
2902             sattrs->ns = false;
2903             sattrs->nsc = idau_nsc;
2904         }
2905     }
2906 }
2907 
2908 static bool get_phys_addr_pmsav8(CPUARMState *env,
2909                                  S1Translate *ptw,
2910                                  uint32_t address,
2911                                  MMUAccessType access_type,
2912                                  GetPhysAddrResult *result,
2913                                  ARMMMUFaultInfo *fi)
2914 {
2915     V8M_SAttributes sattrs = {};
2916     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
2917     bool secure = arm_space_is_secure(ptw->in_space);
2918     bool ret;
2919 
2920     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
2921         v8m_security_lookup(env, address, access_type, mmu_idx,
2922                             secure, &sattrs);
2923         if (access_type == MMU_INST_FETCH) {
2924             /*
2925              * Instruction fetches always use the MMU bank and the
2926              * transaction attribute determined by the fetch address,
2927              * regardless of CPU state. This is painful for QEMU
2928              * to handle, because it would mean we need to encode
2929              * into the mmu_idx not just the (user, negpri) information
2930              * for the current security state but also that for the
2931              * other security state, which would balloon the number
2932              * of mmu_idx values needed alarmingly.
2933              * Fortunately we can avoid this because it's not actually
2934              * possible to arbitrarily execute code from memory with
2935              * the wrong security attribute: it will always generate
2936              * an exception of some kind or another, apart from the
2937              * special case of an NS CPU executing an SG instruction
2938              * in S&NSC memory. So we always just fail the translation
2939              * here and sort things out in the exception handler
2940              * (including possibly emulating an SG instruction).
2941              */
2942             if (sattrs.ns != !secure) {
2943                 if (sattrs.nsc) {
2944                     fi->type = ARMFault_QEMU_NSCExec;
2945                 } else {
2946                     fi->type = ARMFault_QEMU_SFault;
2947                 }
2948                 result->f.lg_page_size = sattrs.subpage ? 0 : TARGET_PAGE_BITS;
2949                 result->f.phys_addr = address;
2950                 result->f.prot = 0;
2951                 return true;
2952             }
2953         } else {
2954             /*
2955              * For data accesses we always use the MMU bank indicated
2956              * by the current CPU state, but the security attributes
2957              * might downgrade a secure access to nonsecure.
2958              */
2959             if (sattrs.ns) {
2960                 result->f.attrs.secure = false;
2961                 result->f.attrs.space = ARMSS_NonSecure;
2962             } else if (!secure) {
2963                 /*
2964                  * NS access to S memory must fault.
2965                  * Architecturally we should first check whether the
2966                  * MPU information for this address indicates that we
2967                  * are doing an unaligned access to Device memory, which
2968                  * should generate a UsageFault instead. QEMU does not
2969                  * currently check for that kind of unaligned access though.
2970                  * If we added it we would need to do so as a special case
2971                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
2972                  */
2973                 fi->type = ARMFault_QEMU_SFault;
2974                 result->f.lg_page_size = sattrs.subpage ? 0 : TARGET_PAGE_BITS;
2975                 result->f.phys_addr = address;
2976                 result->f.prot = 0;
2977                 return true;
2978             }
2979         }
2980     }
2981 
2982     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, secure,
2983                             result, fi, NULL);
2984     if (sattrs.subpage) {
2985         result->f.lg_page_size = 0;
2986     }
2987     return ret;
2988 }
2989 
2990 /*
2991  * Translate from the 4-bit stage 2 representation of
2992  * memory attributes (without cache-allocation hints) to
2993  * the 8-bit representation of the stage 1 MAIR registers
2994  * (which includes allocation hints).
2995  *
2996  * ref: shared/translation/attrs/S2AttrDecode()
2997  *      .../S2ConvertAttrsHints()
2998  */
2999 static uint8_t convert_stage2_attrs(uint64_t hcr, uint8_t s2attrs)
3000 {
3001     uint8_t hiattr = extract32(s2attrs, 2, 2);
3002     uint8_t loattr = extract32(s2attrs, 0, 2);
3003     uint8_t hihint = 0, lohint = 0;
3004 
3005     if (hiattr != 0) { /* normal memory */
3006         if (hcr & HCR_CD) { /* cache disabled */
3007             hiattr = loattr = 1; /* non-cacheable */
3008         } else {
3009             if (hiattr != 1) { /* Write-through or write-back */
3010                 hihint = 3; /* RW allocate */
3011             }
3012             if (loattr != 1) { /* Write-through or write-back */
3013                 lohint = 3; /* RW allocate */
3014             }
3015         }
3016     }
3017 
3018     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
3019 }
3020 
3021 /*
3022  * Combine either inner or outer cacheability attributes for normal
3023  * memory, according to table D4-42 and pseudocode procedure
3024  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
3025  *
3026  * NB: only stage 1 includes allocation hints (RW bits), leading to
3027  * some asymmetry.
3028  */
3029 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
3030 {
3031     if (s1 == 4 || s2 == 4) {
3032         /* non-cacheable has precedence */
3033         return 4;
3034     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
3035         /* stage 1 write-through takes precedence */
3036         return s1;
3037     } else if (extract32(s2, 2, 2) == 2) {
3038         /* stage 2 write-through takes precedence, but the allocation hint
3039          * is still taken from stage 1
3040          */
3041         return (2 << 2) | extract32(s1, 0, 2);
3042     } else { /* write-back */
3043         return s1;
3044     }
3045 }
3046 
3047 /*
3048  * Combine the memory type and cacheability attributes of
3049  * s1 and s2 for the HCR_EL2.FWB == 0 case, returning the
3050  * combined attributes in MAIR_EL1 format.
3051  */
3052 static uint8_t combined_attrs_nofwb(uint64_t hcr,
3053                                     ARMCacheAttrs s1, ARMCacheAttrs s2)
3054 {
3055     uint8_t s1lo, s2lo, s1hi, s2hi, s2_mair_attrs, ret_attrs;
3056 
3057     if (s2.is_s2_format) {
3058         s2_mair_attrs = convert_stage2_attrs(hcr, s2.attrs);
3059     } else {
3060         s2_mair_attrs = s2.attrs;
3061     }
3062 
3063     s1lo = extract32(s1.attrs, 0, 4);
3064     s2lo = extract32(s2_mair_attrs, 0, 4);
3065     s1hi = extract32(s1.attrs, 4, 4);
3066     s2hi = extract32(s2_mair_attrs, 4, 4);
3067 
3068     /* Combine memory type and cacheability attributes */
3069     if (s1hi == 0 || s2hi == 0) {
3070         /* Device has precedence over normal */
3071         if (s1lo == 0 || s2lo == 0) {
3072             /* nGnRnE has precedence over anything */
3073             ret_attrs = 0;
3074         } else if (s1lo == 4 || s2lo == 4) {
3075             /* non-Reordering has precedence over Reordering */
3076             ret_attrs = 4;  /* nGnRE */
3077         } else if (s1lo == 8 || s2lo == 8) {
3078             /* non-Gathering has precedence over Gathering */
3079             ret_attrs = 8;  /* nGRE */
3080         } else {
3081             ret_attrs = 0xc; /* GRE */
3082         }
3083     } else { /* Normal memory */
3084         /* Outer/inner cacheability combine independently */
3085         ret_attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
3086                   | combine_cacheattr_nibble(s1lo, s2lo);
3087     }
3088     return ret_attrs;
3089 }
3090 
3091 static uint8_t force_cacheattr_nibble_wb(uint8_t attr)
3092 {
3093     /*
3094      * Given the 4 bits specifying the outer or inner cacheability
3095      * in MAIR format, return a value specifying Normal Write-Back,
3096      * with the allocation and transient hints taken from the input
3097      * if the input specified some kind of cacheable attribute.
3098      */
3099     if (attr == 0 || attr == 4) {
3100         /*
3101          * 0 == an UNPREDICTABLE encoding
3102          * 4 == Non-cacheable
3103          * Either way, force Write-Back RW allocate non-transient
3104          */
3105         return 0xf;
3106     }
3107     /* Change WriteThrough to WriteBack, keep allocation and transient hints */
3108     return attr | 4;
3109 }
3110 
3111 /*
3112  * Combine the memory type and cacheability attributes of
3113  * s1 and s2 for the HCR_EL2.FWB == 1 case, returning the
3114  * combined attributes in MAIR_EL1 format.
3115  */
3116 static uint8_t combined_attrs_fwb(ARMCacheAttrs s1, ARMCacheAttrs s2)
3117 {
3118     assert(s2.is_s2_format && !s1.is_s2_format);
3119 
3120     switch (s2.attrs) {
3121     case 7:
3122         /* Use stage 1 attributes */
3123         return s1.attrs;
3124     case 6:
3125         /*
3126          * Force Normal Write-Back. Note that if S1 is Normal cacheable
3127          * then we take the allocation hints from it; otherwise it is
3128          * RW allocate, non-transient.
3129          */
3130         if ((s1.attrs & 0xf0) == 0) {
3131             /* S1 is Device */
3132             return 0xff;
3133         }
3134         /* Need to check the Inner and Outer nibbles separately */
3135         return force_cacheattr_nibble_wb(s1.attrs & 0xf) |
3136             force_cacheattr_nibble_wb(s1.attrs >> 4) << 4;
3137     case 5:
3138         /* If S1 attrs are Device, use them; otherwise Normal Non-cacheable */
3139         if ((s1.attrs & 0xf0) == 0) {
3140             return s1.attrs;
3141         }
3142         return 0x44;
3143     case 0 ... 3:
3144         /* Force Device, of subtype specified by S2 */
3145         return s2.attrs << 2;
3146     default:
3147         /*
3148          * RESERVED values (including RES0 descriptor bit [5] being nonzero);
3149          * arbitrarily force Device.
3150          */
3151         return 0;
3152     }
3153 }
3154 
3155 /*
3156  * Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
3157  * and CombineS1S2Desc()
3158  *
3159  * @env:     CPUARMState
3160  * @s1:      Attributes from stage 1 walk
3161  * @s2:      Attributes from stage 2 walk
3162  */
3163 static ARMCacheAttrs combine_cacheattrs(uint64_t hcr,
3164                                         ARMCacheAttrs s1, ARMCacheAttrs s2)
3165 {
3166     ARMCacheAttrs ret;
3167     bool tagged = false;
3168 
3169     assert(!s1.is_s2_format);
3170     ret.is_s2_format = false;
3171 
3172     if (s1.attrs == 0xf0) {
3173         tagged = true;
3174         s1.attrs = 0xff;
3175     }
3176 
3177     /* Combine shareability attributes (table D4-43) */
3178     if (s1.shareability == 2 || s2.shareability == 2) {
3179         /* if either are outer-shareable, the result is outer-shareable */
3180         ret.shareability = 2;
3181     } else if (s1.shareability == 3 || s2.shareability == 3) {
3182         /* if either are inner-shareable, the result is inner-shareable */
3183         ret.shareability = 3;
3184     } else {
3185         /* both non-shareable */
3186         ret.shareability = 0;
3187     }
3188 
3189     /* Combine memory type and cacheability attributes */
3190     if (hcr & HCR_FWB) {
3191         ret.attrs = combined_attrs_fwb(s1, s2);
3192     } else {
3193         ret.attrs = combined_attrs_nofwb(hcr, s1, s2);
3194     }
3195 
3196     /*
3197      * Any location for which the resultant memory type is any
3198      * type of Device memory is always treated as Outer Shareable.
3199      * Any location for which the resultant memory type is Normal
3200      * Inner Non-cacheable, Outer Non-cacheable is always treated
3201      * as Outer Shareable.
3202      * TODO: FEAT_XS adds another value (0x40) also meaning iNCoNC
3203      */
3204     if ((ret.attrs & 0xf0) == 0 || ret.attrs == 0x44) {
3205         ret.shareability = 2;
3206     }
3207 
3208     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
3209     if (tagged && ret.attrs == 0xff) {
3210         ret.attrs = 0xf0;
3211     }
3212 
3213     return ret;
3214 }
3215 
3216 /*
3217  * MMU disabled.  S1 addresses within aa64 translation regimes are
3218  * still checked for bounds -- see AArch64.S1DisabledOutput().
3219  */
3220 static bool get_phys_addr_disabled(CPUARMState *env,
3221                                    S1Translate *ptw,
3222                                    vaddr address,
3223                                    MMUAccessType access_type,
3224                                    GetPhysAddrResult *result,
3225                                    ARMMMUFaultInfo *fi)
3226 {
3227     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
3228     uint8_t memattr = 0x00;    /* Device nGnRnE */
3229     uint8_t shareability = 0;  /* non-shareable */
3230     int r_el;
3231 
3232     switch (mmu_idx) {
3233     case ARMMMUIdx_Stage2:
3234     case ARMMMUIdx_Stage2_S:
3235     case ARMMMUIdx_Phys_S:
3236     case ARMMMUIdx_Phys_NS:
3237     case ARMMMUIdx_Phys_Root:
3238     case ARMMMUIdx_Phys_Realm:
3239         break;
3240 
3241     default:
3242         r_el = regime_el(env, mmu_idx);
3243         if (arm_el_is_aa64(env, r_el)) {
3244             int pamax = arm_pamax(env_archcpu(env));
3245             uint64_t tcr = env->cp15.tcr_el[r_el];
3246             int addrtop, tbi;
3247 
3248             tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
3249             if (access_type == MMU_INST_FETCH) {
3250                 tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
3251             }
3252             tbi = (tbi >> extract64(address, 55, 1)) & 1;
3253             addrtop = (tbi ? 55 : 63);
3254 
3255             if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
3256                 fi->type = ARMFault_AddressSize;
3257                 fi->level = 0;
3258                 fi->stage2 = false;
3259                 return 1;
3260             }
3261 
3262             /*
3263              * When TBI is disabled, we've just validated that all of the
3264              * bits above PAMax are zero, so logically we only need to
3265              * clear the top byte for TBI.  But it's clearer to follow
3266              * the pseudocode set of addrdesc.paddress.
3267              */
3268             address = extract64(address, 0, 52);
3269         }
3270 
3271         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
3272         if (r_el == 1) {
3273             uint64_t hcr = arm_hcr_el2_eff_secstate(env, ptw->in_space);
3274             if (hcr & HCR_DC) {
3275                 if (hcr & HCR_DCT) {
3276                     memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
3277                 } else {
3278                     memattr = 0xff;  /* Normal, WB, RWA */
3279                 }
3280             }
3281         }
3282         if (memattr == 0) {
3283             if (access_type == MMU_INST_FETCH) {
3284                 if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
3285                     memattr = 0xee;  /* Normal, WT, RA, NT */
3286                 } else {
3287                     memattr = 0x44;  /* Normal, NC, No */
3288                 }
3289             }
3290             shareability = 2; /* outer shareable */
3291         }
3292         result->cacheattrs.is_s2_format = false;
3293         break;
3294     }
3295 
3296     result->f.phys_addr = address;
3297     result->f.prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
3298     result->f.lg_page_size = TARGET_PAGE_BITS;
3299     result->cacheattrs.shareability = shareability;
3300     result->cacheattrs.attrs = memattr;
3301     return false;
3302 }
3303 
3304 static bool get_phys_addr_twostage(CPUARMState *env, S1Translate *ptw,
3305                                    vaddr address,
3306                                    MMUAccessType access_type, MemOp memop,
3307                                    GetPhysAddrResult *result,
3308                                    ARMMMUFaultInfo *fi)
3309 {
3310     hwaddr ipa;
3311     int s1_prot, s1_lgpgsz;
3312     ARMSecuritySpace in_space = ptw->in_space;
3313     bool ret, ipa_secure, s1_guarded;
3314     ARMCacheAttrs cacheattrs1;
3315     ARMSecuritySpace ipa_space;
3316     uint64_t hcr;
3317 
3318     ret = get_phys_addr_nogpc(env, ptw, address, access_type,
3319                               memop, result, fi);
3320 
3321     /* If S1 fails, return early.  */
3322     if (ret) {
3323         return ret;
3324     }
3325 
3326     ipa = result->f.phys_addr;
3327     ipa_secure = result->f.attrs.secure;
3328     ipa_space = result->f.attrs.space;
3329 
3330     ptw->in_s1_is_el0 = ptw->in_mmu_idx == ARMMMUIdx_Stage1_E0;
3331     ptw->in_mmu_idx = ipa_secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
3332     ptw->in_space = ipa_space;
3333     ptw->in_ptw_idx = ptw_idx_for_stage_2(env, ptw->in_mmu_idx);
3334 
3335     /*
3336      * S1 is done, now do S2 translation.
3337      * Save the stage1 results so that we may merge prot and cacheattrs later.
3338      */
3339     s1_prot = result->f.prot;
3340     s1_lgpgsz = result->f.lg_page_size;
3341     s1_guarded = result->f.extra.arm.guarded;
3342     cacheattrs1 = result->cacheattrs;
3343     memset(result, 0, sizeof(*result));
3344 
3345     ret = get_phys_addr_nogpc(env, ptw, ipa, access_type,
3346                               memop, result, fi);
3347     fi->s2addr = ipa;
3348 
3349     /* Combine the S1 and S2 perms.  */
3350     result->f.prot &= s1_prot;
3351 
3352     /* If S2 fails, return early.  */
3353     if (ret) {
3354         return ret;
3355     }
3356 
3357     /*
3358      * If either S1 or S2 returned a result smaller than TARGET_PAGE_SIZE,
3359      * this means "don't put this in the TLB"; in this case, return a
3360      * result with lg_page_size == 0 to achieve that. Otherwise,
3361      * use the maximum of the S1 & S2 page size, so that invalidation
3362      * of pages > TARGET_PAGE_SIZE works correctly. (This works even though
3363      * we know the combined result permissions etc only cover the minimum
3364      * of the S1 and S2 page size, because we know that the common TLB code
3365      * never actually creates TLB entries bigger than TARGET_PAGE_SIZE,
3366      * and passing a larger page size value only affects invalidations.)
3367      */
3368     if (result->f.lg_page_size < TARGET_PAGE_BITS ||
3369         s1_lgpgsz < TARGET_PAGE_BITS) {
3370         result->f.lg_page_size = 0;
3371     } else if (result->f.lg_page_size < s1_lgpgsz) {
3372         result->f.lg_page_size = s1_lgpgsz;
3373     }
3374 
3375     /* Combine the S1 and S2 cache attributes. */
3376     hcr = arm_hcr_el2_eff_secstate(env, in_space);
3377     if (hcr & HCR_DC) {
3378         /*
3379          * HCR.DC forces the first stage attributes to
3380          *  Normal Non-Shareable,
3381          *  Inner Write-Back Read-Allocate Write-Allocate,
3382          *  Outer Write-Back Read-Allocate Write-Allocate.
3383          * Do not overwrite Tagged within attrs.
3384          */
3385         if (cacheattrs1.attrs != 0xf0) {
3386             cacheattrs1.attrs = 0xff;
3387         }
3388         cacheattrs1.shareability = 0;
3389     }
3390     result->cacheattrs = combine_cacheattrs(hcr, cacheattrs1,
3391                                             result->cacheattrs);
3392 
3393     /* No BTI GP information in stage 2, we just use the S1 value */
3394     result->f.extra.arm.guarded = s1_guarded;
3395 
3396     /*
3397      * Check if IPA translates to secure or non-secure PA space.
3398      * Note that VSTCR overrides VTCR and {N}SW overrides {N}SA.
3399      */
3400     if (in_space == ARMSS_Secure) {
3401         result->f.attrs.secure =
3402             !(env->cp15.vstcr_el2 & (VSTCR_SA | VSTCR_SW))
3403             && (ipa_secure
3404                 || !(env->cp15.vtcr_el2 & (VTCR_NSA | VTCR_NSW)));
3405         result->f.attrs.space = arm_secure_to_space(result->f.attrs.secure);
3406     }
3407 
3408     return false;
3409 }
3410 
3411 static bool get_phys_addr_nogpc(CPUARMState *env, S1Translate *ptw,
3412                                       vaddr address,
3413                                       MMUAccessType access_type, MemOp memop,
3414                                       GetPhysAddrResult *result,
3415                                       ARMMMUFaultInfo *fi)
3416 {
3417     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
3418     ARMMMUIdx s1_mmu_idx;
3419 
3420     /*
3421      * The page table entries may downgrade Secure to NonSecure, but
3422      * cannot upgrade a NonSecure translation regime's attributes
3423      * to Secure or Realm.
3424      */
3425     result->f.attrs.space = ptw->in_space;
3426     result->f.attrs.secure = arm_space_is_secure(ptw->in_space);
3427 
3428     switch (mmu_idx) {
3429     case ARMMMUIdx_Phys_S:
3430     case ARMMMUIdx_Phys_NS:
3431     case ARMMMUIdx_Phys_Root:
3432     case ARMMMUIdx_Phys_Realm:
3433         /* Checking Phys early avoids special casing later vs regime_el. */
3434         return get_phys_addr_disabled(env, ptw, address, access_type,
3435                                       result, fi);
3436 
3437     case ARMMMUIdx_Stage1_E0:
3438     case ARMMMUIdx_Stage1_E1:
3439     case ARMMMUIdx_Stage1_E1_PAN:
3440         /*
3441          * First stage lookup uses second stage for ptw; only
3442          * Secure has both S and NS IPA and starts with Stage2_S.
3443          */
3444         ptw->in_ptw_idx = (ptw->in_space == ARMSS_Secure) ?
3445             ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
3446         break;
3447 
3448     case ARMMMUIdx_Stage2:
3449     case ARMMMUIdx_Stage2_S:
3450         /*
3451          * Second stage lookup uses physical for ptw; whether this is S or
3452          * NS may depend on the SW/NSW bits if this is a stage 2 lookup for
3453          * the Secure EL2&0 regime.
3454          */
3455         ptw->in_ptw_idx = ptw_idx_for_stage_2(env, mmu_idx);
3456         break;
3457 
3458     case ARMMMUIdx_E10_0:
3459         s1_mmu_idx = ARMMMUIdx_Stage1_E0;
3460         goto do_twostage;
3461     case ARMMMUIdx_E10_1:
3462         s1_mmu_idx = ARMMMUIdx_Stage1_E1;
3463         goto do_twostage;
3464     case ARMMMUIdx_E10_1_PAN:
3465         s1_mmu_idx = ARMMMUIdx_Stage1_E1_PAN;
3466     do_twostage:
3467         /*
3468          * Call ourselves recursively to do the stage 1 and then stage 2
3469          * translations if mmu_idx is a two-stage regime, and EL2 present.
3470          * Otherwise, a stage1+stage2 translation is just stage 1.
3471          */
3472         ptw->in_mmu_idx = mmu_idx = s1_mmu_idx;
3473         if (arm_feature(env, ARM_FEATURE_EL2) &&
3474             !regime_translation_disabled(env, ARMMMUIdx_Stage2, ptw->in_space)) {
3475             return get_phys_addr_twostage(env, ptw, address, access_type,
3476                                           memop, result, fi);
3477         }
3478         /* fall through */
3479 
3480     default:
3481         /* Single stage uses physical for ptw. */
3482         ptw->in_ptw_idx = arm_space_to_phys(ptw->in_space);
3483         break;
3484     }
3485 
3486     result->f.attrs.user = regime_is_user(env, mmu_idx);
3487 
3488     /*
3489      * Fast Context Switch Extension. This doesn't exist at all in v8.
3490      * In v7 and earlier it affects all stage 1 translations.
3491      */
3492     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
3493         && !arm_feature(env, ARM_FEATURE_V8)) {
3494         if (regime_el(env, mmu_idx) == 3) {
3495             address += env->cp15.fcseidr_s;
3496         } else {
3497             address += env->cp15.fcseidr_ns;
3498         }
3499     }
3500 
3501     if (arm_feature(env, ARM_FEATURE_PMSA)) {
3502         bool ret;
3503         result->f.lg_page_size = TARGET_PAGE_BITS;
3504 
3505         if (arm_feature(env, ARM_FEATURE_V8)) {
3506             /* PMSAv8 */
3507             ret = get_phys_addr_pmsav8(env, ptw, address, access_type,
3508                                        result, fi);
3509         } else if (arm_feature(env, ARM_FEATURE_V7)) {
3510             /* PMSAv7 */
3511             ret = get_phys_addr_pmsav7(env, ptw, address, access_type,
3512                                        result, fi);
3513         } else {
3514             /* Pre-v7 MPU */
3515             ret = get_phys_addr_pmsav5(env, ptw, address, access_type,
3516                                        result, fi);
3517         }
3518         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
3519                       " mmu_idx %u -> %s (prot %c%c%c)\n",
3520                       access_type == MMU_DATA_LOAD ? "reading" :
3521                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
3522                       (uint32_t)address, mmu_idx,
3523                       ret ? "Miss" : "Hit",
3524                       result->f.prot & PAGE_READ ? 'r' : '-',
3525                       result->f.prot & PAGE_WRITE ? 'w' : '-',
3526                       result->f.prot & PAGE_EXEC ? 'x' : '-');
3527 
3528         return ret;
3529     }
3530 
3531     /* Definitely a real MMU, not an MPU */
3532 
3533     if (regime_translation_disabled(env, mmu_idx, ptw->in_space)) {
3534         return get_phys_addr_disabled(env, ptw, address, access_type,
3535                                       result, fi);
3536     }
3537 
3538     if (regime_using_lpae_format(env, mmu_idx)) {
3539         return get_phys_addr_lpae(env, ptw, address, access_type,
3540                                   memop, result, fi);
3541     } else if (arm_feature(env, ARM_FEATURE_V7) ||
3542                regime_sctlr(env, mmu_idx) & SCTLR_XP) {
3543         return get_phys_addr_v6(env, ptw, address, access_type, result, fi);
3544     } else {
3545         return get_phys_addr_v5(env, ptw, address, access_type, result, fi);
3546     }
3547 }
3548 
3549 static bool get_phys_addr_gpc(CPUARMState *env, S1Translate *ptw,
3550                               vaddr address,
3551                               MMUAccessType access_type, MemOp memop,
3552                               GetPhysAddrResult *result,
3553                               ARMMMUFaultInfo *fi)
3554 {
3555     if (get_phys_addr_nogpc(env, ptw, address, access_type,
3556                             memop, result, fi)) {
3557         return true;
3558     }
3559     if (!granule_protection_check(env, result->f.phys_addr,
3560                                   result->f.attrs.space, fi)) {
3561         fi->type = ARMFault_GPCFOnOutput;
3562         return true;
3563     }
3564     return false;
3565 }
3566 
3567 bool get_phys_addr_with_space_nogpc(CPUARMState *env, vaddr address,
3568                                     MMUAccessType access_type, MemOp memop,
3569                                     ARMMMUIdx mmu_idx, ARMSecuritySpace space,
3570                                     GetPhysAddrResult *result,
3571                                     ARMMMUFaultInfo *fi)
3572 {
3573     S1Translate ptw = {
3574         .in_mmu_idx = mmu_idx,
3575         .in_space = space,
3576     };
3577     return get_phys_addr_nogpc(env, &ptw, address, access_type,
3578                                memop, result, fi);
3579 }
3580 
3581 bool get_phys_addr(CPUARMState *env, vaddr address,
3582                    MMUAccessType access_type, MemOp memop, ARMMMUIdx mmu_idx,
3583                    GetPhysAddrResult *result, ARMMMUFaultInfo *fi)
3584 {
3585     S1Translate ptw = {
3586         .in_mmu_idx = mmu_idx,
3587     };
3588     ARMSecuritySpace ss;
3589 
3590     switch (mmu_idx) {
3591     case ARMMMUIdx_E10_0:
3592     case ARMMMUIdx_E10_1:
3593     case ARMMMUIdx_E10_1_PAN:
3594     case ARMMMUIdx_E20_0:
3595     case ARMMMUIdx_E20_2:
3596     case ARMMMUIdx_E20_2_PAN:
3597     case ARMMMUIdx_Stage1_E0:
3598     case ARMMMUIdx_Stage1_E1:
3599     case ARMMMUIdx_Stage1_E1_PAN:
3600     case ARMMMUIdx_E2:
3601         if (arm_aa32_secure_pl1_0(env)) {
3602             ss = ARMSS_Secure;
3603         } else {
3604             ss = arm_security_space_below_el3(env);
3605         }
3606         break;
3607     case ARMMMUIdx_Stage2:
3608         /*
3609          * For Secure EL2, we need this index to be NonSecure;
3610          * otherwise this will already be NonSecure or Realm.
3611          */
3612         ss = arm_security_space_below_el3(env);
3613         if (ss == ARMSS_Secure) {
3614             ss = ARMSS_NonSecure;
3615         }
3616         break;
3617     case ARMMMUIdx_Phys_NS:
3618     case ARMMMUIdx_MPrivNegPri:
3619     case ARMMMUIdx_MUserNegPri:
3620     case ARMMMUIdx_MPriv:
3621     case ARMMMUIdx_MUser:
3622         ss = ARMSS_NonSecure;
3623         break;
3624     case ARMMMUIdx_Stage2_S:
3625     case ARMMMUIdx_Phys_S:
3626     case ARMMMUIdx_MSPrivNegPri:
3627     case ARMMMUIdx_MSUserNegPri:
3628     case ARMMMUIdx_MSPriv:
3629     case ARMMMUIdx_MSUser:
3630         ss = ARMSS_Secure;
3631         break;
3632     case ARMMMUIdx_E3:
3633         if (arm_feature(env, ARM_FEATURE_AARCH64) &&
3634             cpu_isar_feature(aa64_rme, env_archcpu(env))) {
3635             ss = ARMSS_Root;
3636         } else {
3637             ss = ARMSS_Secure;
3638         }
3639         break;
3640     case ARMMMUIdx_Phys_Root:
3641         ss = ARMSS_Root;
3642         break;
3643     case ARMMMUIdx_Phys_Realm:
3644         ss = ARMSS_Realm;
3645         break;
3646     default:
3647         g_assert_not_reached();
3648     }
3649 
3650     ptw.in_space = ss;
3651     return get_phys_addr_gpc(env, &ptw, address, access_type,
3652                              memop, result, fi);
3653 }
3654 
3655 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
3656                                          MemTxAttrs *attrs)
3657 {
3658     ARMCPU *cpu = ARM_CPU(cs);
3659     CPUARMState *env = &cpu->env;
3660     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
3661     ARMSecuritySpace ss = arm_security_space(env);
3662     S1Translate ptw = {
3663         .in_mmu_idx = mmu_idx,
3664         .in_space = ss,
3665         .in_debug = true,
3666     };
3667     GetPhysAddrResult res = {};
3668     ARMMMUFaultInfo fi = {};
3669     bool ret;
3670 
3671     ret = get_phys_addr_gpc(env, &ptw, addr, MMU_DATA_LOAD, 0, &res, &fi);
3672     *attrs = res.f.attrs;
3673 
3674     if (ret) {
3675         return -1;
3676     }
3677     return res.f.phys_addr;
3678 }
3679