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