xref: /openbmc/qemu/target/arm/ptw.c (revision e53c136f)
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                                 target_ulong address,
78                                 MMUAccessType access_type,
79                                 GetPhysAddrResult *result,
80                                 ARMMMUFaultInfo *fi);
81 
82 static bool get_phys_addr_gpc(CPUARMState *env, S1Translate *ptw,
83                               target_ulong address,
84                               MMUAccessType access_type,
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, &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  * @result: set on translation success,
1688  * @fi: set to fault info if the translation fails
1689  */
1690 static bool get_phys_addr_lpae(CPUARMState *env, S1Translate *ptw,
1691                                uint64_t address,
1692                                MMUAccessType access_type,
1693                                GetPhysAddrResult *result, ARMMMUFaultInfo *fi)
1694 {
1695     ARMCPU *cpu = env_archcpu(env);
1696     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
1697     int32_t level;
1698     ARMVAParameters param;
1699     uint64_t ttbr;
1700     hwaddr descaddr, indexmask, indexmask_grainsize;
1701     uint32_t tableattrs;
1702     target_ulong page_size;
1703     uint64_t attrs;
1704     int32_t stride;
1705     int addrsize, inputsize, outputsize;
1706     uint64_t tcr = regime_tcr(env, mmu_idx);
1707     int ap, xn, pxn;
1708     uint32_t el = regime_el(env, mmu_idx);
1709     uint64_t descaddrmask;
1710     bool aarch64 = arm_el_is_aa64(env, el);
1711     uint64_t descriptor, new_descriptor;
1712     ARMSecuritySpace out_space;
1713     bool device;
1714 
1715     /* TODO: This code does not support shareability levels. */
1716     if (aarch64) {
1717         int ps;
1718 
1719         param = aa64_va_parameters(env, address, mmu_idx,
1720                                    access_type != MMU_INST_FETCH,
1721                                    !arm_el_is_aa64(env, 1));
1722         level = 0;
1723 
1724         /*
1725          * If TxSZ is programmed to a value larger than the maximum,
1726          * or smaller than the effective minimum, it is IMPLEMENTATION
1727          * DEFINED whether we behave as if the field were programmed
1728          * within bounds, or if a level 0 Translation fault is generated.
1729          *
1730          * With FEAT_LVA, fault on less than minimum becomes required,
1731          * so our choice is to always raise the fault.
1732          */
1733         if (param.tsz_oob) {
1734             goto do_translation_fault;
1735         }
1736 
1737         addrsize = 64 - 8 * param.tbi;
1738         inputsize = 64 - param.tsz;
1739 
1740         /*
1741          * Bound PS by PARANGE to find the effective output address size.
1742          * ID_AA64MMFR0 is a read-only register so values outside of the
1743          * supported mappings can be considered an implementation error.
1744          */
1745         ps = FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
1746         ps = MIN(ps, param.ps);
1747         assert(ps < ARRAY_SIZE(pamax_map));
1748         outputsize = pamax_map[ps];
1749 
1750         /*
1751          * With LPA2, the effective output address (OA) size is at most 48 bits
1752          * unless TCR.DS == 1
1753          */
1754         if (!param.ds && param.gran != Gran64K) {
1755             outputsize = MIN(outputsize, 48);
1756         }
1757     } else {
1758         param = aa32_va_parameters(env, address, mmu_idx);
1759         level = 1;
1760         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
1761         inputsize = addrsize - param.tsz;
1762         outputsize = 40;
1763     }
1764 
1765     /*
1766      * We determined the region when collecting the parameters, but we
1767      * have not yet validated that the address is valid for the region.
1768      * Extract the top bits and verify that they all match select.
1769      *
1770      * For aa32, if inputsize == addrsize, then we have selected the
1771      * region by exclusion in aa32_va_parameters and there is no more
1772      * validation to do here.
1773      */
1774     if (inputsize < addrsize) {
1775         target_ulong top_bits = sextract64(address, inputsize,
1776                                            addrsize - inputsize);
1777         if (-top_bits != param.select) {
1778             /* The gap between the two regions is a Translation fault */
1779             goto do_translation_fault;
1780         }
1781     }
1782 
1783     stride = arm_granule_bits(param.gran) - 3;
1784 
1785     /*
1786      * Note that QEMU ignores shareability and cacheability attributes,
1787      * so we don't need to do anything with the SH, ORGN, IRGN fields
1788      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
1789      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
1790      * implement any ASID-like capability so we can ignore it (instead
1791      * we will always flush the TLB any time the ASID is changed).
1792      */
1793     ttbr = regime_ttbr(env, mmu_idx, param.select);
1794 
1795     /*
1796      * Here we should have set up all the parameters for the translation:
1797      * inputsize, ttbr, epd, stride, tbi
1798      */
1799 
1800     if (param.epd) {
1801         /*
1802          * Translation table walk disabled => Translation fault on TLB miss
1803          * Note: This is always 0 on 64-bit EL2 and EL3.
1804          */
1805         goto do_translation_fault;
1806     }
1807 
1808     if (!regime_is_stage2(mmu_idx)) {
1809         /*
1810          * The starting level depends on the virtual address size (which can
1811          * be up to 48 bits) and the translation granule size. It indicates
1812          * the number of strides (stride bits at a time) needed to
1813          * consume the bits of the input address. In the pseudocode this is:
1814          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
1815          * where their 'inputsize' is our 'inputsize', 'grainsize' is
1816          * our 'stride + 3' and 'stride' is our 'stride'.
1817          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
1818          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
1819          * = 4 - (inputsize - 4) / stride;
1820          */
1821         level = 4 - (inputsize - 4) / stride;
1822     } else {
1823         int startlevel = check_s2_mmu_setup(cpu, aarch64, tcr, param.ds,
1824                                             inputsize, stride);
1825         if (startlevel == INT_MIN) {
1826             level = 0;
1827             goto do_translation_fault;
1828         }
1829         level = startlevel;
1830     }
1831 
1832     indexmask_grainsize = MAKE_64BIT_MASK(0, stride + 3);
1833     indexmask = MAKE_64BIT_MASK(0, inputsize - (stride * (4 - level)));
1834 
1835     /* Now we can extract the actual base address from the TTBR */
1836     descaddr = extract64(ttbr, 0, 48);
1837 
1838     /*
1839      * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [5:2] of TTBR.
1840      *
1841      * Otherwise, if the base address is out of range, raise AddressSizeFault.
1842      * In the pseudocode, this is !IsZero(baseregister<47:outputsize>),
1843      * but we've just cleared the bits above 47, so simplify the test.
1844      */
1845     if (outputsize > 48) {
1846         descaddr |= extract64(ttbr, 2, 4) << 48;
1847     } else if (descaddr >> outputsize) {
1848         level = 0;
1849         fi->type = ARMFault_AddressSize;
1850         goto do_fault;
1851     }
1852 
1853     /*
1854      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
1855      * and also to mask out CnP (bit 0) which could validly be non-zero.
1856      */
1857     descaddr &= ~indexmask;
1858 
1859     /*
1860      * For AArch32, the address field in the descriptor goes up to bit 39
1861      * for both v7 and v8.  However, for v8 the SBZ bits [47:40] must be 0
1862      * or an AddressSize fault is raised.  So for v8 we extract those SBZ
1863      * bits as part of the address, which will be checked via outputsize.
1864      * For AArch64, the address field goes up to bit 47, or 49 with FEAT_LPA2;
1865      * the highest bits of a 52-bit output are placed elsewhere.
1866      */
1867     if (param.ds) {
1868         descaddrmask = MAKE_64BIT_MASK(0, 50);
1869     } else if (arm_feature(env, ARM_FEATURE_V8)) {
1870         descaddrmask = MAKE_64BIT_MASK(0, 48);
1871     } else {
1872         descaddrmask = MAKE_64BIT_MASK(0, 40);
1873     }
1874     descaddrmask &= ~indexmask_grainsize;
1875     tableattrs = 0;
1876 
1877  next_level:
1878     descaddr |= (address >> (stride * (4 - level))) & indexmask;
1879     descaddr &= ~7ULL;
1880 
1881     /*
1882      * Process the NSTable bit from the previous level.  This changes
1883      * the table address space and the output space from Secure to
1884      * NonSecure.  With RME, the EL3 translation regime does not change
1885      * from Root to NonSecure.
1886      */
1887     if (ptw->in_space == ARMSS_Secure
1888         && !regime_is_stage2(mmu_idx)
1889         && extract32(tableattrs, 4, 1)) {
1890         /*
1891          * Stage2_S -> Stage2 or Phys_S -> Phys_NS
1892          * Assert the relative order of the secure/non-secure indexes.
1893          */
1894         QEMU_BUILD_BUG_ON(ARMMMUIdx_Phys_S + 1 != ARMMMUIdx_Phys_NS);
1895         QEMU_BUILD_BUG_ON(ARMMMUIdx_Stage2_S + 1 != ARMMMUIdx_Stage2);
1896         ptw->in_ptw_idx += 1;
1897         ptw->in_space = ARMSS_NonSecure;
1898     }
1899 
1900     if (!S1_ptw_translate(env, ptw, descaddr, fi)) {
1901         goto do_fault;
1902     }
1903     descriptor = arm_ldq_ptw(env, ptw, fi);
1904     if (fi->type != ARMFault_None) {
1905         goto do_fault;
1906     }
1907     new_descriptor = descriptor;
1908 
1909  restart_atomic_update:
1910     if (!(descriptor & 1) ||
1911         (!(descriptor & 2) &&
1912          !lpae_block_desc_valid(cpu, param.ds, param.gran, level))) {
1913         /* Invalid, or a block descriptor at an invalid level */
1914         goto do_translation_fault;
1915     }
1916 
1917     descaddr = descriptor & descaddrmask;
1918 
1919     /*
1920      * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [15:12]
1921      * of descriptor.  For FEAT_LPA2 and effective DS, bits [51:50] of
1922      * descaddr are in [9:8].  Otherwise, if descaddr is out of range,
1923      * raise AddressSizeFault.
1924      */
1925     if (outputsize > 48) {
1926         if (param.ds) {
1927             descaddr |= extract64(descriptor, 8, 2) << 50;
1928         } else {
1929             descaddr |= extract64(descriptor, 12, 4) << 48;
1930         }
1931     } else if (descaddr >> outputsize) {
1932         fi->type = ARMFault_AddressSize;
1933         goto do_fault;
1934     }
1935 
1936     if ((descriptor & 2) && (level < 3)) {
1937         /*
1938          * Table entry. The top five bits are attributes which may
1939          * propagate down through lower levels of the table (and
1940          * which are all arranged so that 0 means "no effect", so
1941          * we can gather them up by ORing in the bits at each level).
1942          */
1943         tableattrs |= extract64(descriptor, 59, 5);
1944         level++;
1945         indexmask = indexmask_grainsize;
1946         goto next_level;
1947     }
1948 
1949     /*
1950      * Block entry at level 1 or 2, or page entry at level 3.
1951      * These are basically the same thing, although the number
1952      * of bits we pull in from the vaddr varies. Note that although
1953      * descaddrmask masks enough of the low bits of the descriptor
1954      * to give a correct page or table address, the address field
1955      * in a block descriptor is smaller; so we need to explicitly
1956      * clear the lower bits here before ORing in the low vaddr bits.
1957      *
1958      * Afterward, descaddr is the final physical address.
1959      */
1960     page_size = (1ULL << ((stride * (4 - level)) + 3));
1961     descaddr &= ~(hwaddr)(page_size - 1);
1962     descaddr |= (address & (page_size - 1));
1963 
1964     if (likely(!ptw->in_debug)) {
1965         /*
1966          * Access flag.
1967          * If HA is enabled, prepare to update the descriptor below.
1968          * Otherwise, pass the access fault on to software.
1969          */
1970         if (!(descriptor & (1 << 10))) {
1971             if (param.ha) {
1972                 new_descriptor |= 1 << 10; /* AF */
1973             } else {
1974                 fi->type = ARMFault_AccessFlag;
1975                 goto do_fault;
1976             }
1977         }
1978 
1979         /*
1980          * Dirty Bit.
1981          * If HD is enabled, pre-emptively set/clear the appropriate AP/S2AP
1982          * bit for writeback. The actual write protection test may still be
1983          * overridden by tableattrs, to be merged below.
1984          */
1985         if (param.hd
1986             && extract64(descriptor, 51, 1)  /* DBM */
1987             && access_type == MMU_DATA_STORE) {
1988             if (regime_is_stage2(mmu_idx)) {
1989                 new_descriptor |= 1ull << 7;    /* set S2AP[1] */
1990             } else {
1991                 new_descriptor &= ~(1ull << 7); /* clear AP[2] */
1992             }
1993         }
1994     }
1995 
1996     /*
1997      * Extract attributes from the (modified) descriptor, and apply
1998      * table descriptors. Stage 2 table descriptors do not include
1999      * any attribute fields. HPD disables all the table attributes
2000      * except NSTable (which we have already handled).
2001      */
2002     attrs = new_descriptor & (MAKE_64BIT_MASK(2, 10) | MAKE_64BIT_MASK(50, 14));
2003     if (!regime_is_stage2(mmu_idx)) {
2004         if (!param.hpd) {
2005             attrs |= extract64(tableattrs, 0, 2) << 53;     /* XN, PXN */
2006             /*
2007              * The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
2008              * means "force PL1 access only", which means forcing AP[1] to 0.
2009              */
2010             attrs &= ~(extract64(tableattrs, 2, 1) << 6); /* !APT[0] => AP[1] */
2011             attrs |= extract32(tableattrs, 3, 1) << 7;    /* APT[1] => AP[2] */
2012         }
2013     }
2014 
2015     ap = extract32(attrs, 6, 2);
2016     out_space = ptw->in_space;
2017     if (regime_is_stage2(mmu_idx)) {
2018         /*
2019          * R_GYNXY: For stage2 in Realm security state, bit 55 is NS.
2020          * The bit remains ignored for other security states.
2021          * R_YMCSL: Executing an insn fetched from non-Realm causes
2022          * a stage2 permission fault.
2023          */
2024         if (out_space == ARMSS_Realm && extract64(attrs, 55, 1)) {
2025             out_space = ARMSS_NonSecure;
2026             result->f.prot = get_S2prot_noexecute(ap);
2027         } else {
2028             xn = extract64(attrs, 53, 2);
2029             result->f.prot = get_S2prot(env, ap, xn, ptw->in_s1_is_el0);
2030         }
2031     } else {
2032         int nse, ns = extract32(attrs, 5, 1);
2033         switch (out_space) {
2034         case ARMSS_Root:
2035             /*
2036              * R_GVZML: Bit 11 becomes the NSE field in the EL3 regime.
2037              * R_XTYPW: NSE and NS together select the output pa space.
2038              */
2039             nse = extract32(attrs, 11, 1);
2040             out_space = (nse << 1) | ns;
2041             if (out_space == ARMSS_Secure &&
2042                 !cpu_isar_feature(aa64_sel2, cpu)) {
2043                 out_space = ARMSS_NonSecure;
2044             }
2045             break;
2046         case ARMSS_Secure:
2047             if (ns) {
2048                 out_space = ARMSS_NonSecure;
2049             }
2050             break;
2051         case ARMSS_Realm:
2052             switch (mmu_idx) {
2053             case ARMMMUIdx_Stage1_E0:
2054             case ARMMMUIdx_Stage1_E1:
2055             case ARMMMUIdx_Stage1_E1_PAN:
2056                 /* I_CZPRF: For Realm EL1&0 stage1, NS bit is RES0. */
2057                 break;
2058             case ARMMMUIdx_E2:
2059             case ARMMMUIdx_E20_0:
2060             case ARMMMUIdx_E20_2:
2061             case ARMMMUIdx_E20_2_PAN:
2062                 /*
2063                  * R_LYKFZ, R_WGRZN: For Realm EL2 and EL2&1,
2064                  * NS changes the output to non-secure space.
2065                  */
2066                 if (ns) {
2067                     out_space = ARMSS_NonSecure;
2068                 }
2069                 break;
2070             default:
2071                 g_assert_not_reached();
2072             }
2073             break;
2074         case ARMSS_NonSecure:
2075             /* R_QRMFF: For NonSecure state, the NS bit is RES0. */
2076             break;
2077         default:
2078             g_assert_not_reached();
2079         }
2080         xn = extract64(attrs, 54, 1);
2081         pxn = extract64(attrs, 53, 1);
2082 
2083         if (el == 1 && nv_nv1_enabled(env, ptw)) {
2084             /*
2085              * With FEAT_NV, when HCR_EL2.{NV,NV1} == {1,1}, the block/page
2086              * descriptor bit 54 holds PXN, 53 is RES0, and the effective value
2087              * of UXN is 0. Similarly for bits 59 and 60 in table descriptors
2088              * (which we have already folded into bits 53 and 54 of attrs).
2089              * AP[1] (descriptor bit 6, our ap bit 0) is treated as 0.
2090              * Similarly, APTable[0] from the table descriptor is treated as 0;
2091              * we already folded this into AP[1] and squashing that to 0 does
2092              * the right thing.
2093              */
2094             pxn = xn;
2095             xn = 0;
2096             ap &= ~1;
2097         }
2098         /*
2099          * Note that we modified ptw->in_space earlier for NSTable, but
2100          * result->f.attrs retains a copy of the original security space.
2101          */
2102         result->f.prot = get_S1prot(env, mmu_idx, aarch64, ap, xn, pxn,
2103                                     result->f.attrs.space, out_space);
2104     }
2105 
2106     if (!(result->f.prot & (1 << access_type))) {
2107         fi->type = ARMFault_Permission;
2108         goto do_fault;
2109     }
2110 
2111     /* If FEAT_HAFDBS has made changes, update the PTE. */
2112     if (new_descriptor != descriptor) {
2113         new_descriptor = arm_casq_ptw(env, descriptor, new_descriptor, ptw, fi);
2114         if (fi->type != ARMFault_None) {
2115             goto do_fault;
2116         }
2117         /*
2118          * I_YZSVV says that if the in-memory descriptor has changed,
2119          * then we must use the information in that new value
2120          * (which might include a different output address, different
2121          * attributes, or generate a fault).
2122          * Restart the handling of the descriptor value from scratch.
2123          */
2124         if (new_descriptor != descriptor) {
2125             descriptor = new_descriptor;
2126             goto restart_atomic_update;
2127         }
2128     }
2129 
2130     result->f.attrs.space = out_space;
2131     result->f.attrs.secure = arm_space_is_secure(out_space);
2132 
2133     if (regime_is_stage2(mmu_idx)) {
2134         result->cacheattrs.is_s2_format = true;
2135         result->cacheattrs.attrs = extract32(attrs, 2, 4);
2136         /*
2137          * Security state does not really affect HCR_EL2.FWB;
2138          * we only need to filter FWB for aa32 or other FEAT.
2139          */
2140         device = S2_attrs_are_device(arm_hcr_el2_eff(env),
2141                                      result->cacheattrs.attrs);
2142     } else {
2143         /* Index into MAIR registers for cache attributes */
2144         uint8_t attrindx = extract32(attrs, 2, 3);
2145         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
2146         assert(attrindx <= 7);
2147         result->cacheattrs.is_s2_format = false;
2148         result->cacheattrs.attrs = extract64(mair, attrindx * 8, 8);
2149 
2150         /* When in aarch64 mode, and BTI is enabled, remember GP in the TLB. */
2151         if (aarch64 && cpu_isar_feature(aa64_bti, cpu)) {
2152             result->f.extra.arm.guarded = extract64(attrs, 50, 1); /* GP */
2153         }
2154         device = S1_attrs_are_device(result->cacheattrs.attrs);
2155     }
2156 
2157     /*
2158      * Enable alignment checks on Device memory.
2159      *
2160      * Per R_XCHFJ, this check is mis-ordered. The correct ordering
2161      * for alignment, permission, and stage 2 faults should be:
2162      *    - Alignment fault caused by the memory type
2163      *    - Permission fault
2164      *    - A stage 2 fault on the memory access
2165      * but due to the way the TCG softmmu TLB operates, we will have
2166      * implicitly done the permission check and the stage2 lookup in
2167      * finding the TLB entry, so the alignment check cannot be done sooner.
2168      *
2169      * In v7, for a CPU without the Virtualization Extensions this
2170      * access is UNPREDICTABLE; we choose to make it take the alignment
2171      * fault as is required for a v7VE CPU. (QEMU doesn't emulate any
2172      * CPUs with ARM_FEATURE_LPAE but not ARM_FEATURE_V7VE anyway.)
2173      */
2174     if (device) {
2175         result->f.tlb_fill_flags |= TLB_CHECK_ALIGNED;
2176     }
2177 
2178     /*
2179      * For FEAT_LPA2 and effective DS, the SH field in the attributes
2180      * was re-purposed for output address bits.  The SH attribute in
2181      * that case comes from TCR_ELx, which we extracted earlier.
2182      */
2183     if (param.ds) {
2184         result->cacheattrs.shareability = param.sh;
2185     } else {
2186         result->cacheattrs.shareability = extract32(attrs, 8, 2);
2187     }
2188 
2189     result->f.phys_addr = descaddr;
2190     result->f.lg_page_size = ctz64(page_size);
2191     return false;
2192 
2193  do_translation_fault:
2194     fi->type = ARMFault_Translation;
2195  do_fault:
2196     if (fi->s1ptw) {
2197         /* Retain the existing stage 2 fi->level */
2198         assert(fi->stage2);
2199     } else {
2200         fi->level = level;
2201         fi->stage2 = regime_is_stage2(mmu_idx);
2202     }
2203     fi->s1ns = fault_s1ns(ptw->in_space, mmu_idx);
2204     return true;
2205 }
2206 
2207 static bool get_phys_addr_pmsav5(CPUARMState *env,
2208                                  S1Translate *ptw,
2209                                  uint32_t address,
2210                                  MMUAccessType access_type,
2211                                  GetPhysAddrResult *result,
2212                                  ARMMMUFaultInfo *fi)
2213 {
2214     int n;
2215     uint32_t mask;
2216     uint32_t base;
2217     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
2218     bool is_user = regime_is_user(env, mmu_idx);
2219 
2220     if (regime_translation_disabled(env, mmu_idx, ptw->in_space)) {
2221         /* MPU disabled.  */
2222         result->f.phys_addr = address;
2223         result->f.prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
2224         return false;
2225     }
2226 
2227     result->f.phys_addr = address;
2228     for (n = 7; n >= 0; n--) {
2229         base = env->cp15.c6_region[n];
2230         if ((base & 1) == 0) {
2231             continue;
2232         }
2233         mask = 1 << ((base >> 1) & 0x1f);
2234         /* Keep this shift separate from the above to avoid an
2235            (undefined) << 32.  */
2236         mask = (mask << 1) - 1;
2237         if (((base ^ address) & ~mask) == 0) {
2238             break;
2239         }
2240     }
2241     if (n < 0) {
2242         fi->type = ARMFault_Background;
2243         return true;
2244     }
2245 
2246     if (access_type == MMU_INST_FETCH) {
2247         mask = env->cp15.pmsav5_insn_ap;
2248     } else {
2249         mask = env->cp15.pmsav5_data_ap;
2250     }
2251     mask = (mask >> (n * 4)) & 0xf;
2252     switch (mask) {
2253     case 0:
2254         fi->type = ARMFault_Permission;
2255         fi->level = 1;
2256         return true;
2257     case 1:
2258         if (is_user) {
2259             fi->type = ARMFault_Permission;
2260             fi->level = 1;
2261             return true;
2262         }
2263         result->f.prot = PAGE_READ | PAGE_WRITE;
2264         break;
2265     case 2:
2266         result->f.prot = PAGE_READ;
2267         if (!is_user) {
2268             result->f.prot |= PAGE_WRITE;
2269         }
2270         break;
2271     case 3:
2272         result->f.prot = PAGE_READ | PAGE_WRITE;
2273         break;
2274     case 5:
2275         if (is_user) {
2276             fi->type = ARMFault_Permission;
2277             fi->level = 1;
2278             return true;
2279         }
2280         result->f.prot = PAGE_READ;
2281         break;
2282     case 6:
2283         result->f.prot = PAGE_READ;
2284         break;
2285     default:
2286         /* Bad permission.  */
2287         fi->type = ARMFault_Permission;
2288         fi->level = 1;
2289         return true;
2290     }
2291     result->f.prot |= PAGE_EXEC;
2292     return false;
2293 }
2294 
2295 static void get_phys_addr_pmsav7_default(CPUARMState *env, ARMMMUIdx mmu_idx,
2296                                          int32_t address, uint8_t *prot)
2297 {
2298     if (!arm_feature(env, ARM_FEATURE_M)) {
2299         *prot = PAGE_READ | PAGE_WRITE;
2300         switch (address) {
2301         case 0xF0000000 ... 0xFFFFFFFF:
2302             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
2303                 /* hivecs execing is ok */
2304                 *prot |= PAGE_EXEC;
2305             }
2306             break;
2307         case 0x00000000 ... 0x7FFFFFFF:
2308             *prot |= PAGE_EXEC;
2309             break;
2310         }
2311     } else {
2312         /* Default system address map for M profile cores.
2313          * The architecture specifies which regions are execute-never;
2314          * at the MPU level no other checks are defined.
2315          */
2316         switch (address) {
2317         case 0x00000000 ... 0x1fffffff: /* ROM */
2318         case 0x20000000 ... 0x3fffffff: /* SRAM */
2319         case 0x60000000 ... 0x7fffffff: /* RAM */
2320         case 0x80000000 ... 0x9fffffff: /* RAM */
2321             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
2322             break;
2323         case 0x40000000 ... 0x5fffffff: /* Peripheral */
2324         case 0xa0000000 ... 0xbfffffff: /* Device */
2325         case 0xc0000000 ... 0xdfffffff: /* Device */
2326         case 0xe0000000 ... 0xffffffff: /* System */
2327             *prot = PAGE_READ | PAGE_WRITE;
2328             break;
2329         default:
2330             g_assert_not_reached();
2331         }
2332     }
2333 }
2334 
2335 static bool m_is_ppb_region(CPUARMState *env, uint32_t address)
2336 {
2337     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
2338     return arm_feature(env, ARM_FEATURE_M) &&
2339         extract32(address, 20, 12) == 0xe00;
2340 }
2341 
2342 static bool m_is_system_region(CPUARMState *env, uint32_t address)
2343 {
2344     /*
2345      * True if address is in the M profile system region
2346      * 0xe0000000 - 0xffffffff
2347      */
2348     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
2349 }
2350 
2351 static bool pmsav7_use_background_region(ARMCPU *cpu, ARMMMUIdx mmu_idx,
2352                                          bool is_secure, bool is_user)
2353 {
2354     /*
2355      * Return true if we should use the default memory map as a
2356      * "background" region if there are no hits against any MPU regions.
2357      */
2358     CPUARMState *env = &cpu->env;
2359 
2360     if (is_user) {
2361         return false;
2362     }
2363 
2364     if (arm_feature(env, ARM_FEATURE_M)) {
2365         return env->v7m.mpu_ctrl[is_secure] & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
2366     }
2367 
2368     if (mmu_idx == ARMMMUIdx_Stage2) {
2369         return false;
2370     }
2371 
2372     return regime_sctlr(env, mmu_idx) & SCTLR_BR;
2373 }
2374 
2375 static bool get_phys_addr_pmsav7(CPUARMState *env,
2376                                  S1Translate *ptw,
2377                                  uint32_t address,
2378                                  MMUAccessType access_type,
2379                                  GetPhysAddrResult *result,
2380                                  ARMMMUFaultInfo *fi)
2381 {
2382     ARMCPU *cpu = env_archcpu(env);
2383     int n;
2384     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
2385     bool is_user = regime_is_user(env, mmu_idx);
2386     bool secure = arm_space_is_secure(ptw->in_space);
2387 
2388     result->f.phys_addr = address;
2389     result->f.lg_page_size = TARGET_PAGE_BITS;
2390     result->f.prot = 0;
2391 
2392     if (regime_translation_disabled(env, mmu_idx, ptw->in_space) ||
2393         m_is_ppb_region(env, address)) {
2394         /*
2395          * MPU disabled or M profile PPB access: use default memory map.
2396          * The other case which uses the default memory map in the
2397          * v7M ARM ARM pseudocode is exception vector reads from the vector
2398          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
2399          * which always does a direct read using address_space_ldl(), rather
2400          * than going via this function, so we don't need to check that here.
2401          */
2402         get_phys_addr_pmsav7_default(env, mmu_idx, address, &result->f.prot);
2403     } else { /* MPU enabled */
2404         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
2405             /* region search */
2406             uint32_t base = env->pmsav7.drbar[n];
2407             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
2408             uint32_t rmask;
2409             bool srdis = false;
2410 
2411             if (!(env->pmsav7.drsr[n] & 0x1)) {
2412                 continue;
2413             }
2414 
2415             if (!rsize) {
2416                 qemu_log_mask(LOG_GUEST_ERROR,
2417                               "DRSR[%d]: Rsize field cannot be 0\n", n);
2418                 continue;
2419             }
2420             rsize++;
2421             rmask = (1ull << rsize) - 1;
2422 
2423             if (base & rmask) {
2424                 qemu_log_mask(LOG_GUEST_ERROR,
2425                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
2426                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
2427                               n, base, rmask);
2428                 continue;
2429             }
2430 
2431             if (address < base || address > base + rmask) {
2432                 /*
2433                  * Address not in this region. We must check whether the
2434                  * region covers addresses in the same page as our address.
2435                  * In that case we must not report a size that covers the
2436                  * whole page for a subsequent hit against a different MPU
2437                  * region or the background region, because it would result in
2438                  * incorrect TLB hits for subsequent accesses to addresses that
2439                  * are in this MPU region.
2440                  */
2441                 if (ranges_overlap(base, rmask,
2442                                    address & TARGET_PAGE_MASK,
2443                                    TARGET_PAGE_SIZE)) {
2444                     result->f.lg_page_size = 0;
2445                 }
2446                 continue;
2447             }
2448 
2449             /* Region matched */
2450 
2451             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
2452                 int i, snd;
2453                 uint32_t srdis_mask;
2454 
2455                 rsize -= 3; /* sub region size (power of 2) */
2456                 snd = ((address - base) >> rsize) & 0x7;
2457                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
2458 
2459                 srdis_mask = srdis ? 0x3 : 0x0;
2460                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
2461                     /*
2462                      * This will check in groups of 2, 4 and then 8, whether
2463                      * the subregion bits are consistent. rsize is incremented
2464                      * back up to give the region size, considering consistent
2465                      * adjacent subregions as one region. Stop testing if rsize
2466                      * is already big enough for an entire QEMU page.
2467                      */
2468                     int snd_rounded = snd & ~(i - 1);
2469                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
2470                                                      snd_rounded + 8, i);
2471                     if (srdis_mask ^ srdis_multi) {
2472                         break;
2473                     }
2474                     srdis_mask = (srdis_mask << i) | srdis_mask;
2475                     rsize++;
2476                 }
2477             }
2478             if (srdis) {
2479                 continue;
2480             }
2481             if (rsize < TARGET_PAGE_BITS) {
2482                 result->f.lg_page_size = rsize;
2483             }
2484             break;
2485         }
2486 
2487         if (n == -1) { /* no hits */
2488             if (!pmsav7_use_background_region(cpu, mmu_idx, secure, is_user)) {
2489                 /* background fault */
2490                 fi->type = ARMFault_Background;
2491                 return true;
2492             }
2493             get_phys_addr_pmsav7_default(env, mmu_idx, address,
2494                                          &result->f.prot);
2495         } else { /* a MPU hit! */
2496             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
2497             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
2498 
2499             if (m_is_system_region(env, address)) {
2500                 /* System space is always execute never */
2501                 xn = 1;
2502             }
2503 
2504             if (is_user) { /* User mode AP bit decoding */
2505                 switch (ap) {
2506                 case 0:
2507                 case 1:
2508                 case 5:
2509                     break; /* no access */
2510                 case 3:
2511                     result->f.prot |= PAGE_WRITE;
2512                     /* fall through */
2513                 case 2:
2514                 case 6:
2515                     result->f.prot |= PAGE_READ | PAGE_EXEC;
2516                     break;
2517                 case 7:
2518                     /* for v7M, same as 6; for R profile a reserved value */
2519                     if (arm_feature(env, ARM_FEATURE_M)) {
2520                         result->f.prot |= PAGE_READ | PAGE_EXEC;
2521                         break;
2522                     }
2523                     /* fall through */
2524                 default:
2525                     qemu_log_mask(LOG_GUEST_ERROR,
2526                                   "DRACR[%d]: Bad value for AP bits: 0x%"
2527                                   PRIx32 "\n", n, ap);
2528                 }
2529             } else { /* Priv. mode AP bits decoding */
2530                 switch (ap) {
2531                 case 0:
2532                     break; /* no access */
2533                 case 1:
2534                 case 2:
2535                 case 3:
2536                     result->f.prot |= PAGE_WRITE;
2537                     /* fall through */
2538                 case 5:
2539                 case 6:
2540                     result->f.prot |= PAGE_READ | PAGE_EXEC;
2541                     break;
2542                 case 7:
2543                     /* for v7M, same as 6; for R profile a reserved value */
2544                     if (arm_feature(env, ARM_FEATURE_M)) {
2545                         result->f.prot |= PAGE_READ | PAGE_EXEC;
2546                         break;
2547                     }
2548                     /* fall through */
2549                 default:
2550                     qemu_log_mask(LOG_GUEST_ERROR,
2551                                   "DRACR[%d]: Bad value for AP bits: 0x%"
2552                                   PRIx32 "\n", n, ap);
2553                 }
2554             }
2555 
2556             /* execute never */
2557             if (xn) {
2558                 result->f.prot &= ~PAGE_EXEC;
2559             }
2560         }
2561     }
2562 
2563     fi->type = ARMFault_Permission;
2564     fi->level = 1;
2565     return !(result->f.prot & (1 << access_type));
2566 }
2567 
2568 static uint32_t *regime_rbar(CPUARMState *env, ARMMMUIdx mmu_idx,
2569                              uint32_t secure)
2570 {
2571     if (regime_el(env, mmu_idx) == 2) {
2572         return env->pmsav8.hprbar;
2573     } else {
2574         return env->pmsav8.rbar[secure];
2575     }
2576 }
2577 
2578 static uint32_t *regime_rlar(CPUARMState *env, ARMMMUIdx mmu_idx,
2579                              uint32_t secure)
2580 {
2581     if (regime_el(env, mmu_idx) == 2) {
2582         return env->pmsav8.hprlar;
2583     } else {
2584         return env->pmsav8.rlar[secure];
2585     }
2586 }
2587 
2588 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
2589                        MMUAccessType access_type, ARMMMUIdx mmu_idx,
2590                        bool secure, GetPhysAddrResult *result,
2591                        ARMMMUFaultInfo *fi, uint32_t *mregion)
2592 {
2593     /*
2594      * Perform a PMSAv8 MPU lookup (without also doing the SAU check
2595      * that a full phys-to-virt translation does).
2596      * mregion is (if not NULL) set to the region number which matched,
2597      * or -1 if no region number is returned (MPU off, address did not
2598      * hit a region, address hit in multiple regions).
2599      * If the region hit doesn't cover the entire TARGET_PAGE the address
2600      * is within, then we set the result page_size to 1 to force the
2601      * memory system to use a subpage.
2602      */
2603     ARMCPU *cpu = env_archcpu(env);
2604     bool is_user = regime_is_user(env, mmu_idx);
2605     int n;
2606     int matchregion = -1;
2607     bool hit = false;
2608     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
2609     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
2610     int region_counter;
2611 
2612     if (regime_el(env, mmu_idx) == 2) {
2613         region_counter = cpu->pmsav8r_hdregion;
2614     } else {
2615         region_counter = cpu->pmsav7_dregion;
2616     }
2617 
2618     result->f.lg_page_size = TARGET_PAGE_BITS;
2619     result->f.phys_addr = address;
2620     result->f.prot = 0;
2621     if (mregion) {
2622         *mregion = -1;
2623     }
2624 
2625     if (mmu_idx == ARMMMUIdx_Stage2) {
2626         fi->stage2 = true;
2627     }
2628 
2629     /*
2630      * Unlike the ARM ARM pseudocode, we don't need to check whether this
2631      * was an exception vector read from the vector table (which is always
2632      * done using the default system address map), because those accesses
2633      * are done in arm_v7m_load_vector(), which always does a direct
2634      * read using address_space_ldl(), rather than going via this function.
2635      */
2636     if (regime_translation_disabled(env, mmu_idx, arm_secure_to_space(secure))) {
2637         /* MPU disabled */
2638         hit = true;
2639     } else if (m_is_ppb_region(env, address)) {
2640         hit = true;
2641     } else {
2642         if (pmsav7_use_background_region(cpu, mmu_idx, secure, is_user)) {
2643             hit = true;
2644         }
2645 
2646         uint32_t bitmask;
2647         if (arm_feature(env, ARM_FEATURE_M)) {
2648             bitmask = 0x1f;
2649         } else {
2650             bitmask = 0x3f;
2651             fi->level = 0;
2652         }
2653 
2654         for (n = region_counter - 1; n >= 0; n--) {
2655             /* region search */
2656             /*
2657              * Note that the base address is bits [31:x] from the register
2658              * with bits [x-1:0] all zeroes, but the limit address is bits
2659              * [31:x] from the register with bits [x:0] all ones. Where x is
2660              * 5 for Cortex-M and 6 for Cortex-R
2661              */
2662             uint32_t base = regime_rbar(env, mmu_idx, secure)[n] & ~bitmask;
2663             uint32_t limit = regime_rlar(env, mmu_idx, secure)[n] | bitmask;
2664 
2665             if (!(regime_rlar(env, mmu_idx, secure)[n] & 0x1)) {
2666                 /* Region disabled */
2667                 continue;
2668             }
2669 
2670             if (address < base || address > limit) {
2671                 /*
2672                  * Address not in this region. We must check whether the
2673                  * region covers addresses in the same page as our address.
2674                  * In that case we must not report a size that covers the
2675                  * whole page for a subsequent hit against a different MPU
2676                  * region or the background region, because it would result in
2677                  * incorrect TLB hits for subsequent accesses to addresses that
2678                  * are in this MPU region.
2679                  */
2680                 if (limit >= base &&
2681                     ranges_overlap(base, limit - base + 1,
2682                                    addr_page_base,
2683                                    TARGET_PAGE_SIZE)) {
2684                     result->f.lg_page_size = 0;
2685                 }
2686                 continue;
2687             }
2688 
2689             if (base > addr_page_base || limit < addr_page_limit) {
2690                 result->f.lg_page_size = 0;
2691             }
2692 
2693             if (matchregion != -1) {
2694                 /*
2695                  * Multiple regions match -- always a failure (unlike
2696                  * PMSAv7 where highest-numbered-region wins)
2697                  */
2698                 fi->type = ARMFault_Permission;
2699                 if (arm_feature(env, ARM_FEATURE_M)) {
2700                     fi->level = 1;
2701                 }
2702                 return true;
2703             }
2704 
2705             matchregion = n;
2706             hit = true;
2707         }
2708     }
2709 
2710     if (!hit) {
2711         if (arm_feature(env, ARM_FEATURE_M)) {
2712             fi->type = ARMFault_Background;
2713         } else {
2714             fi->type = ARMFault_Permission;
2715         }
2716         return true;
2717     }
2718 
2719     if (matchregion == -1) {
2720         /* hit using the background region */
2721         get_phys_addr_pmsav7_default(env, mmu_idx, address, &result->f.prot);
2722     } else {
2723         uint32_t matched_rbar = regime_rbar(env, mmu_idx, secure)[matchregion];
2724         uint32_t matched_rlar = regime_rlar(env, mmu_idx, secure)[matchregion];
2725         uint32_t ap = extract32(matched_rbar, 1, 2);
2726         uint32_t xn = extract32(matched_rbar, 0, 1);
2727         bool pxn = false;
2728 
2729         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
2730             pxn = extract32(matched_rlar, 4, 1);
2731         }
2732 
2733         if (m_is_system_region(env, address)) {
2734             /* System space is always execute never */
2735             xn = 1;
2736         }
2737 
2738         if (regime_el(env, mmu_idx) == 2) {
2739             result->f.prot = simple_ap_to_rw_prot_is_user(ap,
2740                                             mmu_idx != ARMMMUIdx_E2);
2741         } else {
2742             result->f.prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
2743         }
2744 
2745         if (!arm_feature(env, ARM_FEATURE_M)) {
2746             uint8_t attrindx = extract32(matched_rlar, 1, 3);
2747             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
2748             uint8_t sh = extract32(matched_rlar, 3, 2);
2749 
2750             if (regime_sctlr(env, mmu_idx) & SCTLR_WXN &&
2751                 result->f.prot & PAGE_WRITE && mmu_idx != ARMMMUIdx_Stage2) {
2752                 xn = 0x1;
2753             }
2754 
2755             if ((regime_el(env, mmu_idx) == 1) &&
2756                 regime_sctlr(env, mmu_idx) & SCTLR_UWXN && ap == 0x1) {
2757                 pxn = 0x1;
2758             }
2759 
2760             result->cacheattrs.is_s2_format = false;
2761             result->cacheattrs.attrs = extract64(mair, attrindx * 8, 8);
2762             result->cacheattrs.shareability = sh;
2763         }
2764 
2765         if (result->f.prot && !xn && !(pxn && !is_user)) {
2766             result->f.prot |= PAGE_EXEC;
2767         }
2768 
2769         if (mregion) {
2770             *mregion = matchregion;
2771         }
2772     }
2773 
2774     fi->type = ARMFault_Permission;
2775     if (arm_feature(env, ARM_FEATURE_M)) {
2776         fi->level = 1;
2777     }
2778     return !(result->f.prot & (1 << access_type));
2779 }
2780 
2781 static bool v8m_is_sau_exempt(CPUARMState *env,
2782                               uint32_t address, MMUAccessType access_type)
2783 {
2784     /*
2785      * The architecture specifies that certain address ranges are
2786      * exempt from v8M SAU/IDAU checks.
2787      */
2788     return
2789         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
2790         (address >= 0xe0000000 && address <= 0xe0002fff) ||
2791         (address >= 0xe000e000 && address <= 0xe000efff) ||
2792         (address >= 0xe002e000 && address <= 0xe002efff) ||
2793         (address >= 0xe0040000 && address <= 0xe0041fff) ||
2794         (address >= 0xe00ff000 && address <= 0xe00fffff);
2795 }
2796 
2797 void v8m_security_lookup(CPUARMState *env, uint32_t address,
2798                          MMUAccessType access_type, ARMMMUIdx mmu_idx,
2799                          bool is_secure, V8M_SAttributes *sattrs)
2800 {
2801     /*
2802      * Look up the security attributes for this address. Compare the
2803      * pseudocode SecurityCheck() function.
2804      * We assume the caller has zero-initialized *sattrs.
2805      */
2806     ARMCPU *cpu = env_archcpu(env);
2807     int r;
2808     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
2809     int idau_region = IREGION_NOTVALID;
2810     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
2811     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
2812 
2813     if (cpu->idau) {
2814         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
2815         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
2816 
2817         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
2818                    &idau_nsc);
2819     }
2820 
2821     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
2822         /* 0xf0000000..0xffffffff is always S for insn fetches */
2823         return;
2824     }
2825 
2826     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
2827         sattrs->ns = !is_secure;
2828         return;
2829     }
2830 
2831     if (idau_region != IREGION_NOTVALID) {
2832         sattrs->irvalid = true;
2833         sattrs->iregion = idau_region;
2834     }
2835 
2836     switch (env->sau.ctrl & 3) {
2837     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
2838         break;
2839     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
2840         sattrs->ns = true;
2841         break;
2842     default: /* SAU.ENABLE == 1 */
2843         for (r = 0; r < cpu->sau_sregion; r++) {
2844             if (env->sau.rlar[r] & 1) {
2845                 uint32_t base = env->sau.rbar[r] & ~0x1f;
2846                 uint32_t limit = env->sau.rlar[r] | 0x1f;
2847 
2848                 if (base <= address && limit >= address) {
2849                     if (base > addr_page_base || limit < addr_page_limit) {
2850                         sattrs->subpage = true;
2851                     }
2852                     if (sattrs->srvalid) {
2853                         /*
2854                          * If we hit in more than one region then we must report
2855                          * as Secure, not NS-Callable, with no valid region
2856                          * number info.
2857                          */
2858                         sattrs->ns = false;
2859                         sattrs->nsc = false;
2860                         sattrs->sregion = 0;
2861                         sattrs->srvalid = false;
2862                         break;
2863                     } else {
2864                         if (env->sau.rlar[r] & 2) {
2865                             sattrs->nsc = true;
2866                         } else {
2867                             sattrs->ns = true;
2868                         }
2869                         sattrs->srvalid = true;
2870                         sattrs->sregion = r;
2871                     }
2872                 } else {
2873                     /*
2874                      * Address not in this region. We must check whether the
2875                      * region covers addresses in the same page as our address.
2876                      * In that case we must not report a size that covers the
2877                      * whole page for a subsequent hit against a different MPU
2878                      * region or the background region, because it would result
2879                      * in incorrect TLB hits for subsequent accesses to
2880                      * addresses that are in this MPU region.
2881                      */
2882                     if (limit >= base &&
2883                         ranges_overlap(base, limit - base + 1,
2884                                        addr_page_base,
2885                                        TARGET_PAGE_SIZE)) {
2886                         sattrs->subpage = true;
2887                     }
2888                 }
2889             }
2890         }
2891         break;
2892     }
2893 
2894     /*
2895      * The IDAU will override the SAU lookup results if it specifies
2896      * higher security than the SAU does.
2897      */
2898     if (!idau_ns) {
2899         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
2900             sattrs->ns = false;
2901             sattrs->nsc = idau_nsc;
2902         }
2903     }
2904 }
2905 
2906 static bool get_phys_addr_pmsav8(CPUARMState *env,
2907                                  S1Translate *ptw,
2908                                  uint32_t address,
2909                                  MMUAccessType access_type,
2910                                  GetPhysAddrResult *result,
2911                                  ARMMMUFaultInfo *fi)
2912 {
2913     V8M_SAttributes sattrs = {};
2914     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
2915     bool secure = arm_space_is_secure(ptw->in_space);
2916     bool ret;
2917 
2918     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
2919         v8m_security_lookup(env, address, access_type, mmu_idx,
2920                             secure, &sattrs);
2921         if (access_type == MMU_INST_FETCH) {
2922             /*
2923              * Instruction fetches always use the MMU bank and the
2924              * transaction attribute determined by the fetch address,
2925              * regardless of CPU state. This is painful for QEMU
2926              * to handle, because it would mean we need to encode
2927              * into the mmu_idx not just the (user, negpri) information
2928              * for the current security state but also that for the
2929              * other security state, which would balloon the number
2930              * of mmu_idx values needed alarmingly.
2931              * Fortunately we can avoid this because it's not actually
2932              * possible to arbitrarily execute code from memory with
2933              * the wrong security attribute: it will always generate
2934              * an exception of some kind or another, apart from the
2935              * special case of an NS CPU executing an SG instruction
2936              * in S&NSC memory. So we always just fail the translation
2937              * here and sort things out in the exception handler
2938              * (including possibly emulating an SG instruction).
2939              */
2940             if (sattrs.ns != !secure) {
2941                 if (sattrs.nsc) {
2942                     fi->type = ARMFault_QEMU_NSCExec;
2943                 } else {
2944                     fi->type = ARMFault_QEMU_SFault;
2945                 }
2946                 result->f.lg_page_size = sattrs.subpage ? 0 : TARGET_PAGE_BITS;
2947                 result->f.phys_addr = address;
2948                 result->f.prot = 0;
2949                 return true;
2950             }
2951         } else {
2952             /*
2953              * For data accesses we always use the MMU bank indicated
2954              * by the current CPU state, but the security attributes
2955              * might downgrade a secure access to nonsecure.
2956              */
2957             if (sattrs.ns) {
2958                 result->f.attrs.secure = false;
2959                 result->f.attrs.space = ARMSS_NonSecure;
2960             } else if (!secure) {
2961                 /*
2962                  * NS access to S memory must fault.
2963                  * Architecturally we should first check whether the
2964                  * MPU information for this address indicates that we
2965                  * are doing an unaligned access to Device memory, which
2966                  * should generate a UsageFault instead. QEMU does not
2967                  * currently check for that kind of unaligned access though.
2968                  * If we added it we would need to do so as a special case
2969                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
2970                  */
2971                 fi->type = ARMFault_QEMU_SFault;
2972                 result->f.lg_page_size = sattrs.subpage ? 0 : TARGET_PAGE_BITS;
2973                 result->f.phys_addr = address;
2974                 result->f.prot = 0;
2975                 return true;
2976             }
2977         }
2978     }
2979 
2980     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, secure,
2981                             result, fi, NULL);
2982     if (sattrs.subpage) {
2983         result->f.lg_page_size = 0;
2984     }
2985     return ret;
2986 }
2987 
2988 /*
2989  * Translate from the 4-bit stage 2 representation of
2990  * memory attributes (without cache-allocation hints) to
2991  * the 8-bit representation of the stage 1 MAIR registers
2992  * (which includes allocation hints).
2993  *
2994  * ref: shared/translation/attrs/S2AttrDecode()
2995  *      .../S2ConvertAttrsHints()
2996  */
2997 static uint8_t convert_stage2_attrs(uint64_t hcr, uint8_t s2attrs)
2998 {
2999     uint8_t hiattr = extract32(s2attrs, 2, 2);
3000     uint8_t loattr = extract32(s2attrs, 0, 2);
3001     uint8_t hihint = 0, lohint = 0;
3002 
3003     if (hiattr != 0) { /* normal memory */
3004         if (hcr & HCR_CD) { /* cache disabled */
3005             hiattr = loattr = 1; /* non-cacheable */
3006         } else {
3007             if (hiattr != 1) { /* Write-through or write-back */
3008                 hihint = 3; /* RW allocate */
3009             }
3010             if (loattr != 1) { /* Write-through or write-back */
3011                 lohint = 3; /* RW allocate */
3012             }
3013         }
3014     }
3015 
3016     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
3017 }
3018 
3019 /*
3020  * Combine either inner or outer cacheability attributes for normal
3021  * memory, according to table D4-42 and pseudocode procedure
3022  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
3023  *
3024  * NB: only stage 1 includes allocation hints (RW bits), leading to
3025  * some asymmetry.
3026  */
3027 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
3028 {
3029     if (s1 == 4 || s2 == 4) {
3030         /* non-cacheable has precedence */
3031         return 4;
3032     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
3033         /* stage 1 write-through takes precedence */
3034         return s1;
3035     } else if (extract32(s2, 2, 2) == 2) {
3036         /* stage 2 write-through takes precedence, but the allocation hint
3037          * is still taken from stage 1
3038          */
3039         return (2 << 2) | extract32(s1, 0, 2);
3040     } else { /* write-back */
3041         return s1;
3042     }
3043 }
3044 
3045 /*
3046  * Combine the memory type and cacheability attributes of
3047  * s1 and s2 for the HCR_EL2.FWB == 0 case, returning the
3048  * combined attributes in MAIR_EL1 format.
3049  */
3050 static uint8_t combined_attrs_nofwb(uint64_t hcr,
3051                                     ARMCacheAttrs s1, ARMCacheAttrs s2)
3052 {
3053     uint8_t s1lo, s2lo, s1hi, s2hi, s2_mair_attrs, ret_attrs;
3054 
3055     if (s2.is_s2_format) {
3056         s2_mair_attrs = convert_stage2_attrs(hcr, s2.attrs);
3057     } else {
3058         s2_mair_attrs = s2.attrs;
3059     }
3060 
3061     s1lo = extract32(s1.attrs, 0, 4);
3062     s2lo = extract32(s2_mair_attrs, 0, 4);
3063     s1hi = extract32(s1.attrs, 4, 4);
3064     s2hi = extract32(s2_mair_attrs, 4, 4);
3065 
3066     /* Combine memory type and cacheability attributes */
3067     if (s1hi == 0 || s2hi == 0) {
3068         /* Device has precedence over normal */
3069         if (s1lo == 0 || s2lo == 0) {
3070             /* nGnRnE has precedence over anything */
3071             ret_attrs = 0;
3072         } else if (s1lo == 4 || s2lo == 4) {
3073             /* non-Reordering has precedence over Reordering */
3074             ret_attrs = 4;  /* nGnRE */
3075         } else if (s1lo == 8 || s2lo == 8) {
3076             /* non-Gathering has precedence over Gathering */
3077             ret_attrs = 8;  /* nGRE */
3078         } else {
3079             ret_attrs = 0xc; /* GRE */
3080         }
3081     } else { /* Normal memory */
3082         /* Outer/inner cacheability combine independently */
3083         ret_attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
3084                   | combine_cacheattr_nibble(s1lo, s2lo);
3085     }
3086     return ret_attrs;
3087 }
3088 
3089 static uint8_t force_cacheattr_nibble_wb(uint8_t attr)
3090 {
3091     /*
3092      * Given the 4 bits specifying the outer or inner cacheability
3093      * in MAIR format, return a value specifying Normal Write-Back,
3094      * with the allocation and transient hints taken from the input
3095      * if the input specified some kind of cacheable attribute.
3096      */
3097     if (attr == 0 || attr == 4) {
3098         /*
3099          * 0 == an UNPREDICTABLE encoding
3100          * 4 == Non-cacheable
3101          * Either way, force Write-Back RW allocate non-transient
3102          */
3103         return 0xf;
3104     }
3105     /* Change WriteThrough to WriteBack, keep allocation and transient hints */
3106     return attr | 4;
3107 }
3108 
3109 /*
3110  * Combine the memory type and cacheability attributes of
3111  * s1 and s2 for the HCR_EL2.FWB == 1 case, returning the
3112  * combined attributes in MAIR_EL1 format.
3113  */
3114 static uint8_t combined_attrs_fwb(ARMCacheAttrs s1, ARMCacheAttrs s2)
3115 {
3116     assert(s2.is_s2_format && !s1.is_s2_format);
3117 
3118     switch (s2.attrs) {
3119     case 7:
3120         /* Use stage 1 attributes */
3121         return s1.attrs;
3122     case 6:
3123         /*
3124          * Force Normal Write-Back. Note that if S1 is Normal cacheable
3125          * then we take the allocation hints from it; otherwise it is
3126          * RW allocate, non-transient.
3127          */
3128         if ((s1.attrs & 0xf0) == 0) {
3129             /* S1 is Device */
3130             return 0xff;
3131         }
3132         /* Need to check the Inner and Outer nibbles separately */
3133         return force_cacheattr_nibble_wb(s1.attrs & 0xf) |
3134             force_cacheattr_nibble_wb(s1.attrs >> 4) << 4;
3135     case 5:
3136         /* If S1 attrs are Device, use them; otherwise Normal Non-cacheable */
3137         if ((s1.attrs & 0xf0) == 0) {
3138             return s1.attrs;
3139         }
3140         return 0x44;
3141     case 0 ... 3:
3142         /* Force Device, of subtype specified by S2 */
3143         return s2.attrs << 2;
3144     default:
3145         /*
3146          * RESERVED values (including RES0 descriptor bit [5] being nonzero);
3147          * arbitrarily force Device.
3148          */
3149         return 0;
3150     }
3151 }
3152 
3153 /*
3154  * Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
3155  * and CombineS1S2Desc()
3156  *
3157  * @env:     CPUARMState
3158  * @s1:      Attributes from stage 1 walk
3159  * @s2:      Attributes from stage 2 walk
3160  */
3161 static ARMCacheAttrs combine_cacheattrs(uint64_t hcr,
3162                                         ARMCacheAttrs s1, ARMCacheAttrs s2)
3163 {
3164     ARMCacheAttrs ret;
3165     bool tagged = false;
3166 
3167     assert(!s1.is_s2_format);
3168     ret.is_s2_format = false;
3169 
3170     if (s1.attrs == 0xf0) {
3171         tagged = true;
3172         s1.attrs = 0xff;
3173     }
3174 
3175     /* Combine shareability attributes (table D4-43) */
3176     if (s1.shareability == 2 || s2.shareability == 2) {
3177         /* if either are outer-shareable, the result is outer-shareable */
3178         ret.shareability = 2;
3179     } else if (s1.shareability == 3 || s2.shareability == 3) {
3180         /* if either are inner-shareable, the result is inner-shareable */
3181         ret.shareability = 3;
3182     } else {
3183         /* both non-shareable */
3184         ret.shareability = 0;
3185     }
3186 
3187     /* Combine memory type and cacheability attributes */
3188     if (hcr & HCR_FWB) {
3189         ret.attrs = combined_attrs_fwb(s1, s2);
3190     } else {
3191         ret.attrs = combined_attrs_nofwb(hcr, s1, s2);
3192     }
3193 
3194     /*
3195      * Any location for which the resultant memory type is any
3196      * type of Device memory is always treated as Outer Shareable.
3197      * Any location for which the resultant memory type is Normal
3198      * Inner Non-cacheable, Outer Non-cacheable is always treated
3199      * as Outer Shareable.
3200      * TODO: FEAT_XS adds another value (0x40) also meaning iNCoNC
3201      */
3202     if ((ret.attrs & 0xf0) == 0 || ret.attrs == 0x44) {
3203         ret.shareability = 2;
3204     }
3205 
3206     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
3207     if (tagged && ret.attrs == 0xff) {
3208         ret.attrs = 0xf0;
3209     }
3210 
3211     return ret;
3212 }
3213 
3214 /*
3215  * MMU disabled.  S1 addresses within aa64 translation regimes are
3216  * still checked for bounds -- see AArch64.S1DisabledOutput().
3217  */
3218 static bool get_phys_addr_disabled(CPUARMState *env,
3219                                    S1Translate *ptw,
3220                                    target_ulong address,
3221                                    MMUAccessType access_type,
3222                                    GetPhysAddrResult *result,
3223                                    ARMMMUFaultInfo *fi)
3224 {
3225     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
3226     uint8_t memattr = 0x00;    /* Device nGnRnE */
3227     uint8_t shareability = 0;  /* non-shareable */
3228     int r_el;
3229 
3230     switch (mmu_idx) {
3231     case ARMMMUIdx_Stage2:
3232     case ARMMMUIdx_Stage2_S:
3233     case ARMMMUIdx_Phys_S:
3234     case ARMMMUIdx_Phys_NS:
3235     case ARMMMUIdx_Phys_Root:
3236     case ARMMMUIdx_Phys_Realm:
3237         break;
3238 
3239     default:
3240         r_el = regime_el(env, mmu_idx);
3241         if (arm_el_is_aa64(env, r_el)) {
3242             int pamax = arm_pamax(env_archcpu(env));
3243             uint64_t tcr = env->cp15.tcr_el[r_el];
3244             int addrtop, tbi;
3245 
3246             tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
3247             if (access_type == MMU_INST_FETCH) {
3248                 tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
3249             }
3250             tbi = (tbi >> extract64(address, 55, 1)) & 1;
3251             addrtop = (tbi ? 55 : 63);
3252 
3253             if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
3254                 fi->type = ARMFault_AddressSize;
3255                 fi->level = 0;
3256                 fi->stage2 = false;
3257                 return 1;
3258             }
3259 
3260             /*
3261              * When TBI is disabled, we've just validated that all of the
3262              * bits above PAMax are zero, so logically we only need to
3263              * clear the top byte for TBI.  But it's clearer to follow
3264              * the pseudocode set of addrdesc.paddress.
3265              */
3266             address = extract64(address, 0, 52);
3267         }
3268 
3269         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
3270         if (r_el == 1) {
3271             uint64_t hcr = arm_hcr_el2_eff_secstate(env, ptw->in_space);
3272             if (hcr & HCR_DC) {
3273                 if (hcr & HCR_DCT) {
3274                     memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
3275                 } else {
3276                     memattr = 0xff;  /* Normal, WB, RWA */
3277                 }
3278             }
3279         }
3280         if (memattr == 0) {
3281             if (access_type == MMU_INST_FETCH) {
3282                 if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
3283                     memattr = 0xee;  /* Normal, WT, RA, NT */
3284                 } else {
3285                     memattr = 0x44;  /* Normal, NC, No */
3286                 }
3287             }
3288             shareability = 2; /* outer shareable */
3289         }
3290         result->cacheattrs.is_s2_format = false;
3291         break;
3292     }
3293 
3294     result->f.phys_addr = address;
3295     result->f.prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
3296     result->f.lg_page_size = TARGET_PAGE_BITS;
3297     result->cacheattrs.shareability = shareability;
3298     result->cacheattrs.attrs = memattr;
3299     return false;
3300 }
3301 
3302 static bool get_phys_addr_twostage(CPUARMState *env, S1Translate *ptw,
3303                                    target_ulong address,
3304                                    MMUAccessType access_type,
3305                                    GetPhysAddrResult *result,
3306                                    ARMMMUFaultInfo *fi)
3307 {
3308     hwaddr ipa;
3309     int s1_prot, s1_lgpgsz;
3310     ARMSecuritySpace in_space = ptw->in_space;
3311     bool ret, ipa_secure, s1_guarded;
3312     ARMCacheAttrs cacheattrs1;
3313     ARMSecuritySpace ipa_space;
3314     uint64_t hcr;
3315 
3316     ret = get_phys_addr_nogpc(env, ptw, address, access_type, result, fi);
3317 
3318     /* If S1 fails, return early.  */
3319     if (ret) {
3320         return ret;
3321     }
3322 
3323     ipa = result->f.phys_addr;
3324     ipa_secure = result->f.attrs.secure;
3325     ipa_space = result->f.attrs.space;
3326 
3327     ptw->in_s1_is_el0 = ptw->in_mmu_idx == ARMMMUIdx_Stage1_E0;
3328     ptw->in_mmu_idx = ipa_secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
3329     ptw->in_space = ipa_space;
3330     ptw->in_ptw_idx = ptw_idx_for_stage_2(env, ptw->in_mmu_idx);
3331 
3332     /*
3333      * S1 is done, now do S2 translation.
3334      * Save the stage1 results so that we may merge prot and cacheattrs later.
3335      */
3336     s1_prot = result->f.prot;
3337     s1_lgpgsz = result->f.lg_page_size;
3338     s1_guarded = result->f.extra.arm.guarded;
3339     cacheattrs1 = result->cacheattrs;
3340     memset(result, 0, sizeof(*result));
3341 
3342     ret = get_phys_addr_nogpc(env, ptw, ipa, access_type, result, fi);
3343     fi->s2addr = ipa;
3344 
3345     /* Combine the S1 and S2 perms.  */
3346     result->f.prot &= s1_prot;
3347 
3348     /* If S2 fails, return early.  */
3349     if (ret) {
3350         return ret;
3351     }
3352 
3353     /*
3354      * If either S1 or S2 returned a result smaller than TARGET_PAGE_SIZE,
3355      * this means "don't put this in the TLB"; in this case, return a
3356      * result with lg_page_size == 0 to achieve that. Otherwise,
3357      * use the maximum of the S1 & S2 page size, so that invalidation
3358      * of pages > TARGET_PAGE_SIZE works correctly. (This works even though
3359      * we know the combined result permissions etc only cover the minimum
3360      * of the S1 and S2 page size, because we know that the common TLB code
3361      * never actually creates TLB entries bigger than TARGET_PAGE_SIZE,
3362      * and passing a larger page size value only affects invalidations.)
3363      */
3364     if (result->f.lg_page_size < TARGET_PAGE_BITS ||
3365         s1_lgpgsz < TARGET_PAGE_BITS) {
3366         result->f.lg_page_size = 0;
3367     } else if (result->f.lg_page_size < s1_lgpgsz) {
3368         result->f.lg_page_size = s1_lgpgsz;
3369     }
3370 
3371     /* Combine the S1 and S2 cache attributes. */
3372     hcr = arm_hcr_el2_eff_secstate(env, in_space);
3373     if (hcr & HCR_DC) {
3374         /*
3375          * HCR.DC forces the first stage attributes to
3376          *  Normal Non-Shareable,
3377          *  Inner Write-Back Read-Allocate Write-Allocate,
3378          *  Outer Write-Back Read-Allocate Write-Allocate.
3379          * Do not overwrite Tagged within attrs.
3380          */
3381         if (cacheattrs1.attrs != 0xf0) {
3382             cacheattrs1.attrs = 0xff;
3383         }
3384         cacheattrs1.shareability = 0;
3385     }
3386     result->cacheattrs = combine_cacheattrs(hcr, cacheattrs1,
3387                                             result->cacheattrs);
3388 
3389     /* No BTI GP information in stage 2, we just use the S1 value */
3390     result->f.extra.arm.guarded = s1_guarded;
3391 
3392     /*
3393      * Check if IPA translates to secure or non-secure PA space.
3394      * Note that VSTCR overrides VTCR and {N}SW overrides {N}SA.
3395      */
3396     if (in_space == ARMSS_Secure) {
3397         result->f.attrs.secure =
3398             !(env->cp15.vstcr_el2 & (VSTCR_SA | VSTCR_SW))
3399             && (ipa_secure
3400                 || !(env->cp15.vtcr_el2 & (VTCR_NSA | VTCR_NSW)));
3401         result->f.attrs.space = arm_secure_to_space(result->f.attrs.secure);
3402     }
3403 
3404     return false;
3405 }
3406 
3407 static bool get_phys_addr_nogpc(CPUARMState *env, S1Translate *ptw,
3408                                       target_ulong address,
3409                                       MMUAccessType access_type,
3410                                       GetPhysAddrResult *result,
3411                                       ARMMMUFaultInfo *fi)
3412 {
3413     ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
3414     ARMMMUIdx s1_mmu_idx;
3415 
3416     /*
3417      * The page table entries may downgrade Secure to NonSecure, but
3418      * cannot upgrade a NonSecure translation regime's attributes
3419      * to Secure or Realm.
3420      */
3421     result->f.attrs.space = ptw->in_space;
3422     result->f.attrs.secure = arm_space_is_secure(ptw->in_space);
3423 
3424     switch (mmu_idx) {
3425     case ARMMMUIdx_Phys_S:
3426     case ARMMMUIdx_Phys_NS:
3427     case ARMMMUIdx_Phys_Root:
3428     case ARMMMUIdx_Phys_Realm:
3429         /* Checking Phys early avoids special casing later vs regime_el. */
3430         return get_phys_addr_disabled(env, ptw, address, access_type,
3431                                       result, fi);
3432 
3433     case ARMMMUIdx_Stage1_E0:
3434     case ARMMMUIdx_Stage1_E1:
3435     case ARMMMUIdx_Stage1_E1_PAN:
3436         /*
3437          * First stage lookup uses second stage for ptw; only
3438          * Secure has both S and NS IPA and starts with Stage2_S.
3439          */
3440         ptw->in_ptw_idx = (ptw->in_space == ARMSS_Secure) ?
3441             ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
3442         break;
3443 
3444     case ARMMMUIdx_Stage2:
3445     case ARMMMUIdx_Stage2_S:
3446         /*
3447          * Second stage lookup uses physical for ptw; whether this is S or
3448          * NS may depend on the SW/NSW bits if this is a stage 2 lookup for
3449          * the Secure EL2&0 regime.
3450          */
3451         ptw->in_ptw_idx = ptw_idx_for_stage_2(env, mmu_idx);
3452         break;
3453 
3454     case ARMMMUIdx_E10_0:
3455         s1_mmu_idx = ARMMMUIdx_Stage1_E0;
3456         goto do_twostage;
3457     case ARMMMUIdx_E10_1:
3458         s1_mmu_idx = ARMMMUIdx_Stage1_E1;
3459         goto do_twostage;
3460     case ARMMMUIdx_E10_1_PAN:
3461         s1_mmu_idx = ARMMMUIdx_Stage1_E1_PAN;
3462     do_twostage:
3463         /*
3464          * Call ourselves recursively to do the stage 1 and then stage 2
3465          * translations if mmu_idx is a two-stage regime, and EL2 present.
3466          * Otherwise, a stage1+stage2 translation is just stage 1.
3467          */
3468         ptw->in_mmu_idx = mmu_idx = s1_mmu_idx;
3469         if (arm_feature(env, ARM_FEATURE_EL2) &&
3470             !regime_translation_disabled(env, ARMMMUIdx_Stage2, ptw->in_space)) {
3471             return get_phys_addr_twostage(env, ptw, address, access_type,
3472                                           result, fi);
3473         }
3474         /* fall through */
3475 
3476     default:
3477         /* Single stage uses physical for ptw. */
3478         ptw->in_ptw_idx = arm_space_to_phys(ptw->in_space);
3479         break;
3480     }
3481 
3482     result->f.attrs.user = regime_is_user(env, mmu_idx);
3483 
3484     /*
3485      * Fast Context Switch Extension. This doesn't exist at all in v8.
3486      * In v7 and earlier it affects all stage 1 translations.
3487      */
3488     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
3489         && !arm_feature(env, ARM_FEATURE_V8)) {
3490         if (regime_el(env, mmu_idx) == 3) {
3491             address += env->cp15.fcseidr_s;
3492         } else {
3493             address += env->cp15.fcseidr_ns;
3494         }
3495     }
3496 
3497     if (arm_feature(env, ARM_FEATURE_PMSA)) {
3498         bool ret;
3499         result->f.lg_page_size = TARGET_PAGE_BITS;
3500 
3501         if (arm_feature(env, ARM_FEATURE_V8)) {
3502             /* PMSAv8 */
3503             ret = get_phys_addr_pmsav8(env, ptw, address, access_type,
3504                                        result, fi);
3505         } else if (arm_feature(env, ARM_FEATURE_V7)) {
3506             /* PMSAv7 */
3507             ret = get_phys_addr_pmsav7(env, ptw, address, access_type,
3508                                        result, fi);
3509         } else {
3510             /* Pre-v7 MPU */
3511             ret = get_phys_addr_pmsav5(env, ptw, address, access_type,
3512                                        result, fi);
3513         }
3514         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
3515                       " mmu_idx %u -> %s (prot %c%c%c)\n",
3516                       access_type == MMU_DATA_LOAD ? "reading" :
3517                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
3518                       (uint32_t)address, mmu_idx,
3519                       ret ? "Miss" : "Hit",
3520                       result->f.prot & PAGE_READ ? 'r' : '-',
3521                       result->f.prot & PAGE_WRITE ? 'w' : '-',
3522                       result->f.prot & PAGE_EXEC ? 'x' : '-');
3523 
3524         return ret;
3525     }
3526 
3527     /* Definitely a real MMU, not an MPU */
3528 
3529     if (regime_translation_disabled(env, mmu_idx, ptw->in_space)) {
3530         return get_phys_addr_disabled(env, ptw, address, access_type,
3531                                       result, fi);
3532     }
3533 
3534     if (regime_using_lpae_format(env, mmu_idx)) {
3535         return get_phys_addr_lpae(env, ptw, address, access_type, result, fi);
3536     } else if (arm_feature(env, ARM_FEATURE_V7) ||
3537                regime_sctlr(env, mmu_idx) & SCTLR_XP) {
3538         return get_phys_addr_v6(env, ptw, address, access_type, result, fi);
3539     } else {
3540         return get_phys_addr_v5(env, ptw, address, access_type, result, fi);
3541     }
3542 }
3543 
3544 static bool get_phys_addr_gpc(CPUARMState *env, S1Translate *ptw,
3545                               target_ulong address,
3546                               MMUAccessType access_type,
3547                               GetPhysAddrResult *result,
3548                               ARMMMUFaultInfo *fi)
3549 {
3550     if (get_phys_addr_nogpc(env, ptw, address, access_type, result, fi)) {
3551         return true;
3552     }
3553     if (!granule_protection_check(env, result->f.phys_addr,
3554                                   result->f.attrs.space, fi)) {
3555         fi->type = ARMFault_GPCFOnOutput;
3556         return true;
3557     }
3558     return false;
3559 }
3560 
3561 bool get_phys_addr_with_space_nogpc(CPUARMState *env, target_ulong address,
3562                                     MMUAccessType access_type,
3563                                     ARMMMUIdx mmu_idx, ARMSecuritySpace space,
3564                                     GetPhysAddrResult *result,
3565                                     ARMMMUFaultInfo *fi)
3566 {
3567     S1Translate ptw = {
3568         .in_mmu_idx = mmu_idx,
3569         .in_space = space,
3570     };
3571     return get_phys_addr_nogpc(env, &ptw, address, access_type, result, fi);
3572 }
3573 
3574 bool get_phys_addr(CPUARMState *env, target_ulong address,
3575                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
3576                    GetPhysAddrResult *result, ARMMMUFaultInfo *fi)
3577 {
3578     S1Translate ptw = {
3579         .in_mmu_idx = mmu_idx,
3580     };
3581     ARMSecuritySpace ss;
3582 
3583     switch (mmu_idx) {
3584     case ARMMMUIdx_E10_0:
3585     case ARMMMUIdx_E10_1:
3586     case ARMMMUIdx_E10_1_PAN:
3587     case ARMMMUIdx_E20_0:
3588     case ARMMMUIdx_E20_2:
3589     case ARMMMUIdx_E20_2_PAN:
3590     case ARMMMUIdx_Stage1_E0:
3591     case ARMMMUIdx_Stage1_E1:
3592     case ARMMMUIdx_Stage1_E1_PAN:
3593     case ARMMMUIdx_E2:
3594         if (arm_aa32_secure_pl1_0(env)) {
3595             ss = ARMSS_Secure;
3596         } else {
3597             ss = arm_security_space_below_el3(env);
3598         }
3599         break;
3600     case ARMMMUIdx_Stage2:
3601         /*
3602          * For Secure EL2, we need this index to be NonSecure;
3603          * otherwise this will already be NonSecure or Realm.
3604          */
3605         ss = arm_security_space_below_el3(env);
3606         if (ss == ARMSS_Secure) {
3607             ss = ARMSS_NonSecure;
3608         }
3609         break;
3610     case ARMMMUIdx_Phys_NS:
3611     case ARMMMUIdx_MPrivNegPri:
3612     case ARMMMUIdx_MUserNegPri:
3613     case ARMMMUIdx_MPriv:
3614     case ARMMMUIdx_MUser:
3615         ss = ARMSS_NonSecure;
3616         break;
3617     case ARMMMUIdx_Stage2_S:
3618     case ARMMMUIdx_Phys_S:
3619     case ARMMMUIdx_MSPrivNegPri:
3620     case ARMMMUIdx_MSUserNegPri:
3621     case ARMMMUIdx_MSPriv:
3622     case ARMMMUIdx_MSUser:
3623         ss = ARMSS_Secure;
3624         break;
3625     case ARMMMUIdx_E3:
3626         if (arm_feature(env, ARM_FEATURE_AARCH64) &&
3627             cpu_isar_feature(aa64_rme, env_archcpu(env))) {
3628             ss = ARMSS_Root;
3629         } else {
3630             ss = ARMSS_Secure;
3631         }
3632         break;
3633     case ARMMMUIdx_Phys_Root:
3634         ss = ARMSS_Root;
3635         break;
3636     case ARMMMUIdx_Phys_Realm:
3637         ss = ARMSS_Realm;
3638         break;
3639     default:
3640         g_assert_not_reached();
3641     }
3642 
3643     ptw.in_space = ss;
3644     return get_phys_addr_gpc(env, &ptw, address, access_type, result, fi);
3645 }
3646 
3647 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
3648                                          MemTxAttrs *attrs)
3649 {
3650     ARMCPU *cpu = ARM_CPU(cs);
3651     CPUARMState *env = &cpu->env;
3652     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
3653     ARMSecuritySpace ss = arm_security_space(env);
3654     S1Translate ptw = {
3655         .in_mmu_idx = mmu_idx,
3656         .in_space = ss,
3657         .in_debug = true,
3658     };
3659     GetPhysAddrResult res = {};
3660     ARMMMUFaultInfo fi = {};
3661     bool ret;
3662 
3663     ret = get_phys_addr_gpc(env, &ptw, addr, MMU_DATA_LOAD, &res, &fi);
3664     *attrs = res.f.attrs;
3665 
3666     if (ret) {
3667         return -1;
3668     }
3669     return res.f.phys_addr;
3670 }
3671