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