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