xref: /haiku/src/system/kernel/arch/arm64/VMSAv8TranslationMap.cpp (revision 5c1f231967bbf06af56728b86ad70f266c99f64d)
1a25542e7Smilek7 /*
2a25542e7Smilek7  * Copyright 2022 Haiku, Inc. All Rights Reserved.
3a25542e7Smilek7  * Distributed under the terms of the MIT License.
4a25542e7Smilek7  */
5a25542e7Smilek7 #include "VMSAv8TranslationMap.h"
6a25542e7Smilek7 
7baf574c9SOwen Anderson #include <algorithm>
83b098011SOwen Anderson #include <slab/Slab.h>
9a25542e7Smilek7 #include <util/AutoLock.h>
10a25542e7Smilek7 #include <util/ThreadAutoLock.h>
113b098011SOwen Anderson #include <vm/VMAddressSpace.h>
123b098011SOwen Anderson #include <vm/VMCache.h>
13a25542e7Smilek7 #include <vm/vm_page.h>
14a25542e7Smilek7 #include <vm/vm_priv.h>
15a25542e7Smilek7 
1632c542bdSOwen Anderson 
1732c542bdSOwen Anderson //#define DO_TRACE
1832c542bdSOwen Anderson #ifdef DO_TRACE
1932c542bdSOwen Anderson #	define TRACE(x...) dprintf(x)
2032c542bdSOwen Anderson #else
2132c542bdSOwen Anderson #	define TRACE(x...) ;
2232c542bdSOwen Anderson #endif
2332c542bdSOwen Anderson 
2432c542bdSOwen Anderson 
25a25542e7Smilek7 uint32_t VMSAv8TranslationMap::fHwFeature;
26a25542e7Smilek7 uint64_t VMSAv8TranslationMap::fMair;
27a25542e7Smilek7 
289fad0a5cSOwen Anderson // ASID Management
299fad0a5cSOwen Anderson static constexpr size_t kAsidBits = 8;
309fad0a5cSOwen Anderson static constexpr size_t kNumAsids = (1 << kAsidBits);
317908993dSOwen Anderson static spinlock sAsidLock = B_SPINLOCK_INITIALIZER;
329fad0a5cSOwen Anderson // A bitmap to track which ASIDs are in use.
339fad0a5cSOwen Anderson static uint64 sAsidBitMap[kNumAsids / 64] = {};
349fad0a5cSOwen Anderson // A mapping from ASID to translation map.
359fad0a5cSOwen Anderson static VMSAv8TranslationMap* sAsidMapping[kNumAsids] = {};
369fad0a5cSOwen Anderson 
379fad0a5cSOwen Anderson 
389fad0a5cSOwen Anderson static void
399fad0a5cSOwen Anderson free_asid(size_t asid)
409fad0a5cSOwen Anderson {
419fad0a5cSOwen Anderson 	for (size_t i = 0; i < B_COUNT_OF(sAsidBitMap); ++i) {
429fad0a5cSOwen Anderson 		if (asid < 64) {
439fad0a5cSOwen Anderson 			sAsidBitMap[i] &= ~(uint64_t{1} << asid);
449fad0a5cSOwen Anderson 			return;
459fad0a5cSOwen Anderson 		}
469fad0a5cSOwen Anderson 		asid -= 64;
479fad0a5cSOwen Anderson 	}
489fad0a5cSOwen Anderson 
499fad0a5cSOwen Anderson 	panic("Could not free ASID!");
509fad0a5cSOwen Anderson }
519fad0a5cSOwen Anderson 
529fad0a5cSOwen Anderson 
539406d2a4SOwen Anderson static void
549406d2a4SOwen Anderson flush_tlb_whole_asid(uint64_t asid)
559406d2a4SOwen Anderson {
569406d2a4SOwen Anderson 	asm("dsb ishst");
579406d2a4SOwen Anderson 	asm("tlbi aside1is, %0" ::"r"(asid << 48));
589406d2a4SOwen Anderson 	asm("dsb ish");
599406d2a4SOwen Anderson 	asm("isb");
609406d2a4SOwen Anderson }
619406d2a4SOwen Anderson 
629406d2a4SOwen Anderson 
639fad0a5cSOwen Anderson static size_t
649fad0a5cSOwen Anderson alloc_first_free_asid(void)
659fad0a5cSOwen Anderson {
669fad0a5cSOwen Anderson 	int asid = 0;
679fad0a5cSOwen Anderson 	for (size_t i = 0; i < B_COUNT_OF(sAsidBitMap); ++i) {
689fad0a5cSOwen Anderson 		int avail = __builtin_ffsll(~sAsidBitMap[i]);
699fad0a5cSOwen Anderson 		if (avail != 0) {
709fad0a5cSOwen Anderson 			sAsidBitMap[i] |= (uint64_t{1} << (avail-1));
719fad0a5cSOwen Anderson 			asid += (avail - 1);
729fad0a5cSOwen Anderson 			return asid;
739fad0a5cSOwen Anderson 		}
749fad0a5cSOwen Anderson 		asid += 64;
759fad0a5cSOwen Anderson 	}
769fad0a5cSOwen Anderson 
779fad0a5cSOwen Anderson 	return kNumAsids;
789fad0a5cSOwen Anderson }
797908993dSOwen Anderson 
80a25542e7Smilek7 
816a2e4f41SOwen Anderson static bool
826a2e4f41SOwen Anderson is_pte_dirty(uint64_t pte)
836a2e4f41SOwen Anderson {
84bb43aaacSOwen Anderson 	if ((pte & kAttrSWDIRTY) != 0)
85bb43aaacSOwen Anderson 		return true;
86bb43aaacSOwen Anderson 
876a2e4f41SOwen Anderson 	return (pte & kAttrAPReadOnly) == 0;
886a2e4f41SOwen Anderson }
896a2e4f41SOwen Anderson 
906a2e4f41SOwen Anderson 
916a2e4f41SOwen Anderson static uint64_t
926a2e4f41SOwen Anderson set_pte_dirty(uint64_t pte)
936a2e4f41SOwen Anderson {
946a2e4f41SOwen Anderson 	if ((pte & kAttrSWDBM) != 0)
956a2e4f41SOwen Anderson 		return pte & ~kAttrAPReadOnly;
966a2e4f41SOwen Anderson 
97bb43aaacSOwen Anderson 	return pte | kAttrSWDIRTY;
986a2e4f41SOwen Anderson }
996a2e4f41SOwen Anderson 
1006a2e4f41SOwen Anderson 
1016a2e4f41SOwen Anderson static uint64_t
1026a2e4f41SOwen Anderson set_pte_clean(uint64_t pte)
1036a2e4f41SOwen Anderson {
104bb43aaacSOwen Anderson 	pte &= ~kAttrSWDIRTY;
1056a2e4f41SOwen Anderson 	return pte | kAttrAPReadOnly;
1066a2e4f41SOwen Anderson }
1076a2e4f41SOwen Anderson 
1086a2e4f41SOwen Anderson 
109129bc12bSOwen Anderson static bool
110129bc12bSOwen Anderson is_pte_accessed(uint64_t pte)
111129bc12bSOwen Anderson {
112129bc12bSOwen Anderson 	return (pte & kPteValidMask) != 0 && (pte & kAttrAF) != 0;
113129bc12bSOwen Anderson }
114129bc12bSOwen Anderson 
115129bc12bSOwen Anderson 
116a25542e7Smilek7 VMSAv8TranslationMap::VMSAv8TranslationMap(
117a25542e7Smilek7 	bool kernel, phys_addr_t pageTable, int pageBits, int vaBits, int minBlockLevel)
118a25542e7Smilek7 	:
119a25542e7Smilek7 	fIsKernel(kernel),
120a25542e7Smilek7 	fPageTable(pageTable),
121a25542e7Smilek7 	fPageBits(pageBits),
122a25542e7Smilek7 	fVaBits(vaBits),
1237908993dSOwen Anderson 	fMinBlockLevel(minBlockLevel),
1244e4d3167SOwen Anderson 	fASID(kernel ? 0 : -1),
1259fad0a5cSOwen Anderson 	fRefcount(0)
126a25542e7Smilek7 {
12732c542bdSOwen Anderson 	TRACE("+VMSAv8TranslationMap(%p, %d, 0x%" B_PRIxADDR ", %d, %d, %d)\n", this,
12832c542bdSOwen Anderson 		kernel, pageTable, pageBits, vaBits, minBlockLevel);
129a25542e7Smilek7 
130a25542e7Smilek7 	fInitialLevel = CalcStartLevel(fVaBits, fPageBits);
131a25542e7Smilek7 }
132a25542e7Smilek7 
133a25542e7Smilek7 
134a25542e7Smilek7 VMSAv8TranslationMap::~VMSAv8TranslationMap()
135a25542e7Smilek7 {
13632c542bdSOwen Anderson 	TRACE("-VMSAv8TranslationMap(%p)\n", this);
13732c542bdSOwen Anderson 	TRACE("  fIsKernel: %d, fPageTable: 0x%" B_PRIxADDR ", fASID: %d, fRefcount: %d\n",
13832c542bdSOwen Anderson 		fIsKernel, fPageTable, fASID, fRefcount);
13932c542bdSOwen Anderson 
1407908993dSOwen Anderson 	ASSERT(!fIsKernel);
1419fad0a5cSOwen Anderson 	ASSERT(fRefcount == 0);
1427908993dSOwen Anderson 	{
1437908993dSOwen Anderson 		ThreadCPUPinner pinner(thread_get_current_thread());
1447908993dSOwen Anderson 		FreeTable(fPageTable, 0, fInitialLevel, [](int level, uint64_t oldPte) {});
1457908993dSOwen Anderson 	}
146a25542e7Smilek7 
1477908993dSOwen Anderson 	{
1487908993dSOwen Anderson 		InterruptsSpinLocker locker(sAsidLock);
1497908993dSOwen Anderson 
1509fad0a5cSOwen Anderson 		if (fASID != -1) {
1517908993dSOwen Anderson 			sAsidMapping[fASID] = NULL;
1529fad0a5cSOwen Anderson 			free_asid(fASID);
1537908993dSOwen Anderson 		}
154a25542e7Smilek7 	}
1559fad0a5cSOwen Anderson }
1569fad0a5cSOwen Anderson 
1579fad0a5cSOwen Anderson 
1589fad0a5cSOwen Anderson // Switch user map into TTBR0.
1599fad0a5cSOwen Anderson // Passing kernel map here configures empty page table.
1609fad0a5cSOwen Anderson void
1619fad0a5cSOwen Anderson VMSAv8TranslationMap::SwitchUserMap(VMSAv8TranslationMap *from, VMSAv8TranslationMap *to)
1629fad0a5cSOwen Anderson {
1634b9a9eabSOwen Anderson 	InterruptsSpinLocker locker(sAsidLock);
1649fad0a5cSOwen Anderson 
1659fad0a5cSOwen Anderson 	if (!from->fIsKernel) {
1669fad0a5cSOwen Anderson 		from->fRefcount--;
1679fad0a5cSOwen Anderson 	}
1689fad0a5cSOwen Anderson 
1699fad0a5cSOwen Anderson 	if (!to->fIsKernel) {
1709fad0a5cSOwen Anderson 		to->fRefcount++;
1719fad0a5cSOwen Anderson 	} else {
1729fad0a5cSOwen Anderson 		arch_vm_install_empty_table_ttbr0();
1739fad0a5cSOwen Anderson 		return;
1749fad0a5cSOwen Anderson 	}
1759fad0a5cSOwen Anderson 
1769fad0a5cSOwen Anderson 	ASSERT(to->fPageTable != 0);
1779fad0a5cSOwen Anderson 	uint64_t ttbr = to->fPageTable | ((fHwFeature & HW_COMMON_NOT_PRIVATE) != 0 ? 1 : 0);
1789fad0a5cSOwen Anderson 
1799fad0a5cSOwen Anderson 	if (to->fASID != -1) {
1809fad0a5cSOwen Anderson 		WRITE_SPECIALREG(TTBR0_EL1, ((uint64_t)to->fASID << 48) | ttbr);
1819fad0a5cSOwen Anderson 		asm("isb");
1829fad0a5cSOwen Anderson 		return;
1839fad0a5cSOwen Anderson 	}
1849fad0a5cSOwen Anderson 
1859fad0a5cSOwen Anderson 	size_t allocatedAsid = alloc_first_free_asid();
1869fad0a5cSOwen Anderson 	if (allocatedAsid != kNumAsids) {
1879fad0a5cSOwen Anderson 		to->fASID = allocatedAsid;
1889fad0a5cSOwen Anderson 		sAsidMapping[allocatedAsid] = to;
1899fad0a5cSOwen Anderson 
1909fad0a5cSOwen Anderson 		WRITE_SPECIALREG(TTBR0_EL1, (allocatedAsid << 48) | ttbr);
1919406d2a4SOwen Anderson 		flush_tlb_whole_asid(allocatedAsid);
1929fad0a5cSOwen Anderson 		return;
1939fad0a5cSOwen Anderson 	}
1949fad0a5cSOwen Anderson 
1954e4d3167SOwen Anderson 	// ASID 0 is reserved for the kernel.
1964e4d3167SOwen Anderson 	for (size_t i = 1; i < kNumAsids; ++i) {
1979fad0a5cSOwen Anderson 		if (sAsidMapping[i]->fRefcount == 0) {
1989fad0a5cSOwen Anderson 			sAsidMapping[i]->fASID = -1;
1999fad0a5cSOwen Anderson 			to->fASID = i;
2009fad0a5cSOwen Anderson 			sAsidMapping[i] = to;
2019fad0a5cSOwen Anderson 
2029fad0a5cSOwen Anderson 			WRITE_SPECIALREG(TTBR0_EL1, (i << 48) | ttbr);
2039406d2a4SOwen Anderson 			flush_tlb_whole_asid(i);
2049fad0a5cSOwen Anderson 			return;
2059fad0a5cSOwen Anderson 		}
2069fad0a5cSOwen Anderson 	}
2079fad0a5cSOwen Anderson 
2089fad0a5cSOwen Anderson 	panic("cannot assign ASID");
2099fad0a5cSOwen Anderson }
210a25542e7Smilek7 
211a25542e7Smilek7 
212a25542e7Smilek7 int
213a25542e7Smilek7 VMSAv8TranslationMap::CalcStartLevel(int vaBits, int pageBits)
214a25542e7Smilek7 {
215a25542e7Smilek7 	int level = 4;
216a25542e7Smilek7 
217a25542e7Smilek7 	int bitsLeft = vaBits - pageBits;
218a25542e7Smilek7 	while (bitsLeft > 0) {
219a25542e7Smilek7 		int tableBits = pageBits - 3;
220a25542e7Smilek7 		bitsLeft -= tableBits;
221a25542e7Smilek7 		level--;
222a25542e7Smilek7 	}
223a25542e7Smilek7 
224a25542e7Smilek7 	ASSERT(level >= 0);
225a25542e7Smilek7 
226a25542e7Smilek7 	return level;
227a25542e7Smilek7 }
228a25542e7Smilek7 
229a25542e7Smilek7 
230a25542e7Smilek7 bool
231a25542e7Smilek7 VMSAv8TranslationMap::Lock()
232a25542e7Smilek7 {
23332c542bdSOwen Anderson 	TRACE("VMSAv8TranslationMap::Lock()\n");
234a25542e7Smilek7 	recursive_lock_lock(&fLock);
235a25542e7Smilek7 	return true;
236a25542e7Smilek7 }
237a25542e7Smilek7 
238a25542e7Smilek7 
239a25542e7Smilek7 void
240a25542e7Smilek7 VMSAv8TranslationMap::Unlock()
241a25542e7Smilek7 {
24232c542bdSOwen Anderson 	TRACE("VMSAv8TranslationMap::Unlock()\n");
243a25542e7Smilek7 	recursive_lock_unlock(&fLock);
244a25542e7Smilek7 }
245a25542e7Smilek7 
246a25542e7Smilek7 
247a25542e7Smilek7 addr_t
248a25542e7Smilek7 VMSAv8TranslationMap::MappedSize() const
249a25542e7Smilek7 {
250a25542e7Smilek7 	panic("VMSAv8TranslationMap::MappedSize not implemented");
251a25542e7Smilek7 	return 0;
252a25542e7Smilek7 }
253a25542e7Smilek7 
254a25542e7Smilek7 
255a25542e7Smilek7 size_t
256a25542e7Smilek7 VMSAv8TranslationMap::MaxPagesNeededToMap(addr_t start, addr_t end) const
257a25542e7Smilek7 {
258a25542e7Smilek7 	size_t result = 0;
259a25542e7Smilek7 	size_t size = end - start + 1;
260a25542e7Smilek7 
261a25542e7Smilek7 	for (int i = fInitialLevel; i < 3; i++) {
262a25542e7Smilek7 		int tableBits = fPageBits - 3;
263a25542e7Smilek7 		int shift = tableBits * (3 - i) + fPageBits;
264a25542e7Smilek7 		uint64_t entrySize = 1UL << shift;
265a25542e7Smilek7 
266a25542e7Smilek7 		result += size / entrySize + 2;
267a25542e7Smilek7 	}
268a25542e7Smilek7 
269a25542e7Smilek7 	return result;
270a25542e7Smilek7 }
271a25542e7Smilek7 
272a25542e7Smilek7 
273a25542e7Smilek7 uint64_t*
274a25542e7Smilek7 VMSAv8TranslationMap::TableFromPa(phys_addr_t pa)
275a25542e7Smilek7 {
276a25542e7Smilek7 	return reinterpret_cast<uint64_t*>(KERNEL_PMAP_BASE + pa);
277a25542e7Smilek7 }
278a25542e7Smilek7 
279a25542e7Smilek7 
2807908993dSOwen Anderson template<typename EntryRemoved>
281a25542e7Smilek7 void
2827908993dSOwen Anderson VMSAv8TranslationMap::FreeTable(phys_addr_t ptPa, uint64_t va, int level,
2837908993dSOwen Anderson 	EntryRemoved &&entryRemoved)
284a25542e7Smilek7 {
2857908993dSOwen Anderson 	ASSERT(level < 4);
286a25542e7Smilek7 
287a25542e7Smilek7 	int tableBits = fPageBits - 3;
288a25542e7Smilek7 	uint64_t tableSize = 1UL << tableBits;
2897908993dSOwen Anderson 	uint64_t vaMask = (1UL << fVaBits) - 1;
290a25542e7Smilek7 
2917908993dSOwen Anderson 	int shift = tableBits * (3 - level) + fPageBits;
2927908993dSOwen Anderson 	uint64_t entrySize = 1UL << shift;
2937908993dSOwen Anderson 
2947908993dSOwen Anderson 	uint64_t nextVa = va;
295a25542e7Smilek7 	uint64_t* pt = TableFromPa(ptPa);
296a25542e7Smilek7 	for (uint64_t i = 0; i < tableSize; i++) {
2977908993dSOwen Anderson 		uint64_t oldPte = (uint64_t) atomic_get_and_set64((int64*) &pt[i], 0);
2987908993dSOwen Anderson 
29918a27fe0SOwen Anderson 		if (level < 3 && (oldPte & kPteTypeMask) == kPteTypeL012Table) {
3007908993dSOwen Anderson 			FreeTable(oldPte & kPteAddrMask, nextVa, level + 1, entryRemoved);
30118a27fe0SOwen Anderson 		} else if ((oldPte & kPteTypeMask) != 0) {
3027908993dSOwen Anderson 			uint64_t fullVa = (fIsKernel ? ~vaMask : 0) | nextVa;
3037908993dSOwen Anderson 			asm("dsb ishst");
3047908993dSOwen Anderson 			asm("tlbi vaae1is, %0" :: "r" ((fullVa >> 12) & kTLBIMask));
3057908993dSOwen Anderson 			// Does it correctly flush block entries at level < 3? We don't use them anyway though.
3067908993dSOwen Anderson 			// TODO: Flush only currently used ASID (using vae1is)
3077908993dSOwen Anderson 			entryRemoved(level, oldPte);
308a25542e7Smilek7 		}
309a25542e7Smilek7 
3107908993dSOwen Anderson 		nextVa += entrySize;
3117908993dSOwen Anderson 	}
3127908993dSOwen Anderson 
3137908993dSOwen Anderson 	asm("dsb ish");
3147908993dSOwen Anderson 
315a25542e7Smilek7 	vm_page* page = vm_lookup_page(ptPa >> fPageBits);
3167908993dSOwen Anderson 	DEBUG_PAGE_ACCESS_START(page);
317a25542e7Smilek7 	vm_page_set_state(page, PAGE_STATE_FREE);
318a25542e7Smilek7 }
319a25542e7Smilek7 
320a25542e7Smilek7 
32118a27fe0SOwen Anderson // Make a new page sub-table.
32218a27fe0SOwen Anderson // The parent table is `ptPa`, and the new sub-table's PTE will be at `index`
32318a27fe0SOwen Anderson // in it.
32418a27fe0SOwen Anderson // Returns the physical address of the new table, or the address of the existing
32518a27fe0SOwen Anderson // one if the PTE is already filled.
326a25542e7Smilek7 phys_addr_t
327baf574c9SOwen Anderson VMSAv8TranslationMap::GetOrMakeTable(phys_addr_t ptPa, int level, int index,
328baf574c9SOwen Anderson 	vm_page_reservation* reservation)
329a25542e7Smilek7 {
33018a27fe0SOwen Anderson 	ASSERT(level < 3);
331a25542e7Smilek7 
33218a27fe0SOwen Anderson 	uint64_t* ptePtr = TableFromPa(ptPa) + index;
33318a27fe0SOwen Anderson 	uint64_t oldPte = atomic_get64((int64*) ptePtr);
334a25542e7Smilek7 
33518a27fe0SOwen Anderson 	int type = oldPte & kPteTypeMask;
33618a27fe0SOwen Anderson 	if (type == kPteTypeL012Table) {
33718a27fe0SOwen Anderson 		// This is table entry already, just return it
338a25542e7Smilek7 		return oldPte & kPteAddrMask;
33918a27fe0SOwen Anderson 	} else if (reservation != nullptr) {
34018a27fe0SOwen Anderson 		// Create new table there
34118a27fe0SOwen Anderson 		vm_page* page = vm_page_allocate_page(reservation, PAGE_STATE_WIRED | VM_PAGE_ALLOC_CLEAR);
342a25542e7Smilek7 		phys_addr_t newTablePa = page->physical_page_number << fPageBits;
34318a27fe0SOwen Anderson 		DEBUG_PAGE_ACCESS_END(page);
344a25542e7Smilek7 
34518a27fe0SOwen Anderson 		// We only create mappings at the final level so we don't need to handle
34618a27fe0SOwen Anderson 		// splitting block mappings
347baf574c9SOwen Anderson 		ASSERT(type != kPteTypeL12Block);
348a25542e7Smilek7 
34918a27fe0SOwen Anderson 		// Ensure that writes to page being attached have completed
35018a27fe0SOwen Anderson 		asm("dsb ishst");
351a25542e7Smilek7 
35218a27fe0SOwen Anderson 		uint64_t oldPteRefetch = (uint64_t)atomic_test_and_set64((int64*) ptePtr,
35318a27fe0SOwen Anderson 			newTablePa | kPteTypeL012Table, oldPte);
35418a27fe0SOwen Anderson 		if (oldPteRefetch != oldPte) {
35518a27fe0SOwen Anderson 			// If the old PTE has mutated, it must be because another thread has allocated the
35618a27fe0SOwen Anderson 			// sub-table at the same time as us. If that has happened, deallocate the page we
35718a27fe0SOwen Anderson 			// setup and use the one they installed instead.
35818a27fe0SOwen Anderson 			ASSERT((oldPteRefetch & kPteTypeMask) == kPteTypeL012Table);
35918a27fe0SOwen Anderson 			DEBUG_PAGE_ACCESS_START(page);
36018a27fe0SOwen Anderson 			vm_page_set_state(page, PAGE_STATE_FREE);
36118a27fe0SOwen Anderson 			return oldPteRefetch & kPteAddrMask;
362a25542e7Smilek7 		}
363a25542e7Smilek7 
364a25542e7Smilek7 		return newTablePa;
365a25542e7Smilek7 	}
366a25542e7Smilek7 
36718a27fe0SOwen Anderson 	// There's no existing table and we have no reservation
368a25542e7Smilek7 	return 0;
369a25542e7Smilek7 }
370a25542e7Smilek7 
371a25542e7Smilek7 
372129bc12bSOwen Anderson bool
373129bc12bSOwen Anderson VMSAv8TranslationMap::FlushVAIfAccessed(uint64_t pte, addr_t va)
374baf574c9SOwen Anderson {
375129bc12bSOwen Anderson 	if (!is_pte_accessed(pte))
376129bc12bSOwen Anderson 		return false;
377129bc12bSOwen Anderson 
3784b9a9eabSOwen Anderson 	InterruptsSpinLocker locker(sAsidLock);
379af5e461fSOwen Anderson 	if (fIsKernel) {
380af5e461fSOwen Anderson 		// We can't flush by ASID for kernel space.
381af5e461fSOwen Anderson 		asm("dsb ishst"); // Ensure PTE write completed
382af5e461fSOwen Anderson 		asm("tlbi vaae1is, %0" ::"r"(((va >> 12) & kTLBIMask)));
383af5e461fSOwen Anderson 		asm("dsb ish");
384af5e461fSOwen Anderson 		asm("isb");
385af5e461fSOwen Anderson 	} else if (fASID != -1) {
386129bc12bSOwen Anderson 		asm("dsb ishst"); // Ensure PTE write completed
387baf574c9SOwen Anderson         asm("tlbi vae1is, %0" ::"r"(((va >> 12) & kTLBIMask) | (uint64_t(fASID) << 48)));
388baf574c9SOwen Anderson 		asm("dsb ish"); // Wait for TLB flush to complete
389129bc12bSOwen Anderson 		asm("isb");
390129bc12bSOwen Anderson 		return true;
391baf574c9SOwen Anderson 	}
392129bc12bSOwen Anderson 
393129bc12bSOwen Anderson 	return false;
394baf574c9SOwen Anderson }
395baf574c9SOwen Anderson 
396baf574c9SOwen Anderson 
397129bc12bSOwen Anderson bool
3984bb796cfSOwen Anderson VMSAv8TranslationMap::AttemptPteBreakBeforeMake(uint64_t* ptePtr, uint64_t oldPte, addr_t va)
399baf574c9SOwen Anderson {
4004bb796cfSOwen Anderson 	uint64_t loadedPte = atomic_test_and_set64((int64_t*)ptePtr, 0, oldPte);
4014bb796cfSOwen Anderson 	if (loadedPte != oldPte)
402129bc12bSOwen Anderson 		return false;
4034bb796cfSOwen Anderson 
404129bc12bSOwen Anderson 	FlushVAIfAccessed(oldPte, va);
405129bc12bSOwen Anderson 
406129bc12bSOwen Anderson 	return true;
407baf574c9SOwen Anderson }
408baf574c9SOwen Anderson 
409baf574c9SOwen Anderson 
410baf574c9SOwen Anderson template<typename UpdatePte>
411baf574c9SOwen Anderson void
412baf574c9SOwen Anderson VMSAv8TranslationMap::ProcessRange(phys_addr_t ptPa, int level, addr_t va, size_t size,
413baf574c9SOwen Anderson     vm_page_reservation* reservation, UpdatePte&& updatePte)
414baf574c9SOwen Anderson {
415baf574c9SOwen Anderson 	ASSERT(level < 4);
416baf574c9SOwen Anderson 	ASSERT(ptPa != 0);
417baf574c9SOwen Anderson 
418af5e461fSOwen Anderson 	uint64_t pageMask = (1UL << fPageBits) - 1;
419af5e461fSOwen Anderson 	uint64_t vaMask = (1UL << fVaBits) - 1;
420af5e461fSOwen Anderson 
421af5e461fSOwen Anderson 	ASSERT((va & pageMask) == 0);
422af5e461fSOwen Anderson 
423baf574c9SOwen Anderson 	int tableBits = fPageBits - 3;
424baf574c9SOwen Anderson 	uint64_t tableMask = (1UL << tableBits) - 1;
425baf574c9SOwen Anderson 
426baf574c9SOwen Anderson 	int shift = tableBits * (3 - level) + fPageBits;
427baf574c9SOwen Anderson 	uint64_t entrySize = 1UL << shift;
428baf574c9SOwen Anderson 	uint64_t entryMask = entrySize - 1;
429baf574c9SOwen Anderson 
430baf574c9SOwen Anderson 	uint64_t alignedDownVa = va & ~entryMask;
431baf574c9SOwen Anderson 	uint64_t alignedUpEnd = (va + size + (entrySize - 1)) & ~entryMask;
432baf574c9SOwen Anderson 	if (level == 3)
433baf574c9SOwen Anderson 		ASSERT(alignedDownVa == va);
434baf574c9SOwen Anderson 
435baf574c9SOwen Anderson     for (uint64_t effectiveVa = alignedDownVa; effectiveVa < alignedUpEnd;
436baf574c9SOwen Anderson         effectiveVa += entrySize) {
437af5e461fSOwen Anderson 		int index = ((effectiveVa & vaMask) >> shift) & tableMask;
438baf574c9SOwen Anderson 		uint64_t* ptePtr = TableFromPa(ptPa) + index;
439baf574c9SOwen Anderson 
440baf574c9SOwen Anderson 		if (level == 3) {
441baf574c9SOwen Anderson 			updatePte(ptePtr, effectiveVa);
442baf574c9SOwen Anderson 		} else {
443baf574c9SOwen Anderson 			phys_addr_t subTable = GetOrMakeTable(ptPa, level, index, reservation);
444baf574c9SOwen Anderson 
445baf574c9SOwen Anderson 			// When reservation is null, we can't create a new subtable. This can be intentional,
446baf574c9SOwen Anderson 			// for example when called from Unmap().
447baf574c9SOwen Anderson 			if (subTable == 0)
448baf574c9SOwen Anderson 				continue;
449baf574c9SOwen Anderson 
450baf574c9SOwen Anderson 			uint64_t subVa = std::max(effectiveVa, va);
451baf574c9SOwen Anderson 			size_t subSize = std::min(size_t(entrySize - (subVa & entryMask)), size);
452baf574c9SOwen Anderson             ProcessRange(subTable, level + 1, subVa, subSize, reservation, updatePte);
453baf574c9SOwen Anderson 
454baf574c9SOwen Anderson 			size -= subSize;
455baf574c9SOwen Anderson 		}
456baf574c9SOwen Anderson 	}
457baf574c9SOwen Anderson }
458baf574c9SOwen Anderson 
459baf574c9SOwen Anderson 
460a25542e7Smilek7 uint8_t
461a25542e7Smilek7 VMSAv8TranslationMap::MairIndex(uint8_t type)
462a25542e7Smilek7 {
463a25542e7Smilek7 	for (int i = 0; i < 8; i++)
464a25542e7Smilek7 		if (((fMair >> (i * 8)) & 0xff) == type)
465a25542e7Smilek7 			return i;
466a25542e7Smilek7 
467a25542e7Smilek7 	panic("MAIR entry not found");
468a25542e7Smilek7 	return 0;
469a25542e7Smilek7 }
470a25542e7Smilek7 
471a25542e7Smilek7 
472a25542e7Smilek7 uint64_t
473a25542e7Smilek7 VMSAv8TranslationMap::GetMemoryAttr(uint32 attributes, uint32 memoryType, bool isKernel)
474a25542e7Smilek7 {
475a25542e7Smilek7 	uint64_t attr = 0;
476a25542e7Smilek7 
477a25542e7Smilek7 	if (!isKernel)
478a25542e7Smilek7 		attr |= kAttrNG;
479a25542e7Smilek7 
480a25542e7Smilek7 	if ((attributes & B_EXECUTE_AREA) == 0)
481a25542e7Smilek7 		attr |= kAttrUXN;
482a25542e7Smilek7 	if ((attributes & B_KERNEL_EXECUTE_AREA) == 0)
483a25542e7Smilek7 		attr |= kAttrPXN;
484a25542e7Smilek7 
485108f6fdcSOwen Anderson 	// SWDBM is software reserved bit that we use to mark that
486108f6fdcSOwen Anderson 	// writes are allowed, and fault handler should clear kAttrAPReadOnly.
487108f6fdcSOwen Anderson 	// In that case kAttrAPReadOnly doubles as not-dirty bit.
488108f6fdcSOwen Anderson 	// Additionally dirty state can be stored in SWDIRTY, in order not to lose
489108f6fdcSOwen Anderson 	// dirty state when changing protection from RW to RO.
490a25542e7Smilek7 
491108f6fdcSOwen Anderson 	// All page permissions begin life in RO state.
492108f6fdcSOwen Anderson 	attr |= kAttrAPReadOnly;
493108f6fdcSOwen Anderson 
494108f6fdcSOwen Anderson 	// User-Execute implies User-Read, because it would break PAN otherwise
495108f6fdcSOwen Anderson 	if ((attributes & B_READ_AREA) != 0 || (attributes & B_EXECUTE_AREA) != 0)
496108f6fdcSOwen Anderson 		attr |= kAttrAPUserAccess; // Allow user reads
497108f6fdcSOwen Anderson 
498108f6fdcSOwen Anderson 	if ((attributes & B_WRITE_AREA) != 0 || (attributes & B_KERNEL_WRITE_AREA) != 0)
499108f6fdcSOwen Anderson 		attr |= kAttrSWDBM; // Mark as writeable
500108f6fdcSOwen Anderson 
501108f6fdcSOwen Anderson 	// When supported by hardware copy our SWDBM bit into DBM,
502108f6fdcSOwen Anderson 	// so that kAttrAPReadOnly is cleared on write attempt automatically
503108f6fdcSOwen Anderson 	// without going through fault handler.
504108f6fdcSOwen Anderson 	if ((fHwFeature & HW_DIRTY) != 0 && (attr & kAttrSWDBM) != 0)
505a25542e7Smilek7 		attr |= kAttrDBM;
506a25542e7Smilek7 
507108f6fdcSOwen Anderson 	attr |= kAttrSHInnerShareable; // Inner Shareable
508a25542e7Smilek7 
509108f6fdcSOwen Anderson 	uint8_t type = MAIR_NORMAL_WB;
510108f6fdcSOwen Anderson 
511*5c1f2319SAugustin Cavalier 	switch (memoryType & B_MEMORY_TYPE_MASK) {
512*5c1f2319SAugustin Cavalier 		case B_UNCACHED_MEMORY:
5138cb8c3d7SOwen Anderson 			// TODO: This probably should be nGnRE for PCI
5148cb8c3d7SOwen Anderson 			type = MAIR_DEVICE_nGnRnE;
5158cb8c3d7SOwen Anderson 			break;
516*5c1f2319SAugustin Cavalier 		case B_WRITE_COMBINING_MEMORY:
517edb17c54SOwen Anderson 			type = MAIR_NORMAL_NC;
5188cb8c3d7SOwen Anderson 			break;
519*5c1f2319SAugustin Cavalier 		case B_WRITE_THROUGH_MEMORY:
520108f6fdcSOwen Anderson 			type = MAIR_NORMAL_WT;
5218cb8c3d7SOwen Anderson 			break;
522*5c1f2319SAugustin Cavalier 		case B_WRITE_PROTECTED_MEMORY:
523108f6fdcSOwen Anderson 			type = MAIR_NORMAL_WT;
5248cb8c3d7SOwen Anderson 			break;
5258cb8c3d7SOwen Anderson 		default:
526*5c1f2319SAugustin Cavalier 		case B_WRITE_BACK_MEMORY:
527108f6fdcSOwen Anderson 			type = MAIR_NORMAL_WB;
5288cb8c3d7SOwen Anderson 			break;
5298cb8c3d7SOwen Anderson 	}
530108f6fdcSOwen Anderson 
531108f6fdcSOwen Anderson 	attr |= MairIndex(type) << 2;
532a25542e7Smilek7 
533a25542e7Smilek7 	return attr;
534a25542e7Smilek7 }
535a25542e7Smilek7 
536a25542e7Smilek7 
537a25542e7Smilek7 status_t
538a25542e7Smilek7 VMSAv8TranslationMap::Map(addr_t va, phys_addr_t pa, uint32 attributes, uint32 memoryType,
539a25542e7Smilek7 	vm_page_reservation* reservation)
540a25542e7Smilek7 {
54132c542bdSOwen Anderson 	TRACE("VMSAv8TranslationMap::Map(0x%" B_PRIxADDR ", 0x%" B_PRIxADDR
54232c542bdSOwen Anderson 		", 0x%x, 0x%x)\n", va, pa, attributes, memoryType);
54332c542bdSOwen Anderson 
544a25542e7Smilek7 	ThreadCPUPinner pinner(thread_get_current_thread());
545a25542e7Smilek7 
546a25542e7Smilek7 	ASSERT(ValidateVa(va));
547a25542e7Smilek7 	uint64_t attr = GetMemoryAttr(attributes, memoryType, fIsKernel);
548a25542e7Smilek7 
549baf574c9SOwen Anderson 	// During first mapping we need to allocate root table
550baf574c9SOwen Anderson 	if (fPageTable == 0) {
551a25542e7Smilek7 		vm_page* page = vm_page_allocate_page(reservation, PAGE_STATE_WIRED | VM_PAGE_ALLOC_CLEAR);
552baf574c9SOwen Anderson 		DEBUG_PAGE_ACCESS_END(page);
553a25542e7Smilek7 		fPageTable = page->physical_page_number << fPageBits;
554a25542e7Smilek7 	}
555a25542e7Smilek7 
556af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, va, B_PAGE_SIZE, reservation,
557baf574c9SOwen Anderson 		[=](uint64_t* ptePtr, uint64_t effectiveVa) {
5584bb796cfSOwen Anderson 			while (true) {
559af5e461fSOwen Anderson 				phys_addr_t effectivePa = effectiveVa - va + pa;
560baf574c9SOwen Anderson 				uint64_t oldPte = atomic_get64((int64*)ptePtr);
561baf574c9SOwen Anderson 				uint64_t newPte = effectivePa | attr | kPteTypeL3Page;
562baf574c9SOwen Anderson 
563baf574c9SOwen Anderson 				if (newPte == oldPte)
564baf574c9SOwen Anderson 					return;
565baf574c9SOwen Anderson 
566af5e461fSOwen Anderson 				if ((oldPte & kPteValidMask) != 0) {
567baf574c9SOwen Anderson 					// ARM64 requires "break-before-make". We must set the PTE to an invalid
568baf574c9SOwen Anderson 					// entry and flush the TLB as appropriate before we can write the new PTE.
569129bc12bSOwen Anderson 					if (!AttemptPteBreakBeforeMake(ptePtr, oldPte, effectiveVa))
5704bb796cfSOwen Anderson 						continue;
571baf574c9SOwen Anderson 				}
572baf574c9SOwen Anderson 
573baf574c9SOwen Anderson 				// Install the new PTE
574baf574c9SOwen Anderson 				atomic_set64((int64*)ptePtr, newPte);
575baf574c9SOwen Anderson 				asm("dsb ishst"); // Ensure PTE write completed
576129bc12bSOwen Anderson 				asm("isb");
5774bb796cfSOwen Anderson 				break;
5784bb796cfSOwen Anderson 			}
579baf574c9SOwen Anderson 		});
580a25542e7Smilek7 
581a25542e7Smilek7 	return B_OK;
582a25542e7Smilek7 }
583a25542e7Smilek7 
584a25542e7Smilek7 
585a25542e7Smilek7 status_t
586a25542e7Smilek7 VMSAv8TranslationMap::Unmap(addr_t start, addr_t end)
587a25542e7Smilek7 {
58832c542bdSOwen Anderson 	TRACE("VMSAv8TranslationMap::Unmap(0x%" B_PRIxADDR ", 0x%" B_PRIxADDR
58932c542bdSOwen Anderson 		")\n", start, end);
590a25542e7Smilek7 	ThreadCPUPinner pinner(thread_get_current_thread());
591a25542e7Smilek7 
592a25542e7Smilek7 	size_t size = end - start + 1;
593a25542e7Smilek7 	ASSERT(ValidateVa(start));
594a25542e7Smilek7 
595baf574c9SOwen Anderson 	if (fPageTable == 0)
596baf574c9SOwen Anderson 		return B_OK;
597baf574c9SOwen Anderson 
598af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, start, size, nullptr,
599baf574c9SOwen Anderson 		[=](uint64_t* ptePtr, uint64_t effectiveVa) {
600129bc12bSOwen Anderson 			uint64_t oldPte = atomic_get_and_set64((int64_t*)ptePtr, 0);
601129bc12bSOwen Anderson 			FlushVAIfAccessed(oldPte, effectiveVa);
602baf574c9SOwen Anderson 		});
603a25542e7Smilek7 
604a25542e7Smilek7 	return B_OK;
605a25542e7Smilek7 }
606a25542e7Smilek7 
607a25542e7Smilek7 
608a25542e7Smilek7 status_t
609a25542e7Smilek7 VMSAv8TranslationMap::UnmapPage(VMArea* area, addr_t address, bool updatePageQueue)
610a25542e7Smilek7 {
61132c542bdSOwen Anderson 	TRACE("VMSAv8TranslationMap::UnmapPage(0x%" B_PRIxADDR "(%s), 0x%"
61232c542bdSOwen Anderson 		B_PRIxADDR ", %d)\n", (addr_t)area, area->name, address,
61332c542bdSOwen Anderson 		updatePageQueue);
61432c542bdSOwen Anderson 
61573c51743SOwen Anderson 	ASSERT(ValidateVa(address));
616a25542e7Smilek7 	ThreadCPUPinner pinner(thread_get_current_thread());
617a25542e7Smilek7 	RecursiveLocker locker(fLock);
618a25542e7Smilek7 
61973c51743SOwen Anderson 	uint64_t oldPte = 0;
620af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, address, B_PAGE_SIZE, nullptr,
62173c51743SOwen Anderson 		[=, &oldPte](uint64_t* ptePtr, uint64_t effectiveVa) {
62273c51743SOwen Anderson 			oldPte = atomic_get_and_set64((int64_t*)ptePtr, 0);
623129bc12bSOwen Anderson 			FlushVAIfAccessed(oldPte, effectiveVa);
62473c51743SOwen Anderson 		});
625a25542e7Smilek7 
6264b9a9eabSOwen Anderson 	if ((oldPte & kPteValidMask) == 0)
6274b9a9eabSOwen Anderson 		return B_ENTRY_NOT_FOUND;
6284b9a9eabSOwen Anderson 
629a25542e7Smilek7 	pinner.Unlock();
630a25542e7Smilek7 	locker.Detach();
63173c51743SOwen Anderson 	PageUnmapped(area, (oldPte & kPteAddrMask) >> fPageBits, (oldPte & kAttrAF) != 0,
6326a2e4f41SOwen Anderson 		is_pte_dirty(oldPte), updatePageQueue);
633a25542e7Smilek7 
634a25542e7Smilek7 	return B_OK;
635a25542e7Smilek7 }
636a25542e7Smilek7 
637a25542e7Smilek7 
6383b098011SOwen Anderson void
6393b098011SOwen Anderson VMSAv8TranslationMap::UnmapPages(VMArea* area, addr_t address, size_t size, bool updatePageQueue)
6403b098011SOwen Anderson {
6413b098011SOwen Anderson 	TRACE("VMSAv8TranslationMap::UnmapPages(0x%" B_PRIxADDR "(%s), 0x%"
6423b098011SOwen Anderson 		B_PRIxADDR ", 0x%" B_PRIxSIZE ", %d)\n", (addr_t)area,
6433b098011SOwen Anderson 		area->name, address, size, updatePageQueue);
6443b098011SOwen Anderson 
6453b098011SOwen Anderson 	ASSERT(ValidateVa(address));
6463b098011SOwen Anderson 	VMAreaMappings queue;
6473b098011SOwen Anderson 	ThreadCPUPinner pinner(thread_get_current_thread());
6483b098011SOwen Anderson 	RecursiveLocker locker(fLock);
6493b098011SOwen Anderson 
650af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, address, size, nullptr,
6513b098011SOwen Anderson 		[=, &queue](uint64_t* ptePtr, uint64_t effectiveVa) {
6523b098011SOwen Anderson 			uint64_t oldPte = atomic_get_and_set64((int64_t*)ptePtr, 0);
653af5e461fSOwen Anderson 			FlushVAIfAccessed(oldPte, effectiveVa);
6543b098011SOwen Anderson 			if ((oldPte & kPteValidMask) == 0)
6553b098011SOwen Anderson 				return;
6563b098011SOwen Anderson 
6573b098011SOwen Anderson 			if (area->cache_type == CACHE_TYPE_DEVICE)
6583b098011SOwen Anderson 				return;
6593b098011SOwen Anderson 
6603b098011SOwen Anderson 			// get the page
6613b098011SOwen Anderson 			vm_page* page = vm_lookup_page((oldPte & kPteAddrMask) >> fPageBits);
6623b098011SOwen Anderson 			ASSERT(page != NULL);
6633b098011SOwen Anderson 
6643b098011SOwen Anderson 			DEBUG_PAGE_ACCESS_START(page);
6653b098011SOwen Anderson 
6663b098011SOwen Anderson 			// transfer the accessed/dirty flags to the page
6673b098011SOwen Anderson 			page->accessed = (oldPte & kAttrAF) != 0;
6683b098011SOwen Anderson 			page->modified = is_pte_dirty(oldPte);
6693b098011SOwen Anderson 
6703b098011SOwen Anderson 			// remove the mapping object/decrement the wired_count of the
6713b098011SOwen Anderson 			// page
6723b098011SOwen Anderson 			if (area->wiring == B_NO_LOCK) {
6733b098011SOwen Anderson 				vm_page_mapping* mapping = NULL;
6743b098011SOwen Anderson 				vm_page_mappings::Iterator iterator
6753b098011SOwen Anderson 					= page->mappings.GetIterator();
6763b098011SOwen Anderson 				while ((mapping = iterator.Next()) != NULL) {
6773b098011SOwen Anderson 					if (mapping->area == area)
6783b098011SOwen Anderson 						break;
6793b098011SOwen Anderson 				}
6803b098011SOwen Anderson 
6813b098011SOwen Anderson 				ASSERT(mapping != NULL);
6823b098011SOwen Anderson 
6833b098011SOwen Anderson 				area->mappings.Remove(mapping);
6843b098011SOwen Anderson 				page->mappings.Remove(mapping);
6853b098011SOwen Anderson 				queue.Add(mapping);
6863b098011SOwen Anderson 			} else
6873b098011SOwen Anderson 				page->DecrementWiredCount();
6883b098011SOwen Anderson 
6893b098011SOwen Anderson 			if (!page->IsMapped()) {
6903b098011SOwen Anderson 				atomic_add(&gMappedPagesCount, -1);
6913b098011SOwen Anderson 
6923b098011SOwen Anderson 				if (updatePageQueue) {
6933b098011SOwen Anderson 					if (page->Cache()->temporary)
6943b098011SOwen Anderson 						vm_page_set_state(page, PAGE_STATE_INACTIVE);
6953b098011SOwen Anderson 					else if (page->modified)
6963b098011SOwen Anderson 						vm_page_set_state(page, PAGE_STATE_MODIFIED);
6973b098011SOwen Anderson 					else
6983b098011SOwen Anderson 						vm_page_set_state(page, PAGE_STATE_CACHED);
6993b098011SOwen Anderson 				}
7003b098011SOwen Anderson 			}
7013b098011SOwen Anderson 
7023b098011SOwen Anderson 			DEBUG_PAGE_ACCESS_END(page);
7033b098011SOwen Anderson 		});
7043b098011SOwen Anderson 
7053b098011SOwen Anderson 	// TODO: As in UnmapPage() we can lose page dirty flags here. ATM it's not
7063b098011SOwen Anderson 	// really critical here, as in all cases this method is used, the unmapped
7073b098011SOwen Anderson 	// area range is unmapped for good (resized/cut) and the pages will likely
7083b098011SOwen Anderson 	// be freed.
7093b098011SOwen Anderson 
7103b098011SOwen Anderson 	locker.Unlock();
7113b098011SOwen Anderson 
7123b098011SOwen Anderson 	// free removed mappings
7133b098011SOwen Anderson 	bool isKernelSpace = area->address_space == VMAddressSpace::Kernel();
7143b098011SOwen Anderson 	uint32 freeFlags = CACHE_DONT_WAIT_FOR_MEMORY
7153b098011SOwen Anderson 		| (isKernelSpace ? CACHE_DONT_LOCK_KERNEL_SPACE : 0);
7163b098011SOwen Anderson 
7173b098011SOwen Anderson 	while (vm_page_mapping* mapping = queue.RemoveHead())
7183b098011SOwen Anderson 		vm_free_page_mapping(mapping->page->physical_page_number, mapping, freeFlags);
7193b098011SOwen Anderson }
7203b098011SOwen Anderson 
7213b098011SOwen Anderson 
7220a367809SOwen Anderson void
7230a367809SOwen Anderson VMSAv8TranslationMap::UnmapArea(VMArea* area, bool deletingAddressSpace,
7240a367809SOwen Anderson 	bool ignoreTopCachePageFlags)
7250a367809SOwen Anderson {
7260a367809SOwen Anderson 	TRACE("VMSAv8TranslationMap::UnmapArea(0x%" B_PRIxADDR "(%s), 0x%"
7270a367809SOwen Anderson 		B_PRIxADDR ", 0x%" B_PRIxSIZE ", %d, %d)\n", (addr_t)area,
7280a367809SOwen Anderson 		area->name, area->Base(), area->Size(), deletingAddressSpace,
7290a367809SOwen Anderson 		ignoreTopCachePageFlags);
7300a367809SOwen Anderson 
7310a367809SOwen Anderson 	if (area->cache_type == CACHE_TYPE_DEVICE || area->wiring != B_NO_LOCK) {
7320a367809SOwen Anderson 		UnmapPages(area, area->Base(), area->Size(), true);
7330a367809SOwen Anderson 		return;
7340a367809SOwen Anderson 	}
7350a367809SOwen Anderson 
7360a367809SOwen Anderson 	bool unmapPages = !deletingAddressSpace || !ignoreTopCachePageFlags;
7370a367809SOwen Anderson 
7380a367809SOwen Anderson 	RecursiveLocker locker(fLock);
7390a367809SOwen Anderson 	ThreadCPUPinner pinner(thread_get_current_thread());
7400a367809SOwen Anderson 
7410a367809SOwen Anderson 	VMAreaMappings mappings;
7420a367809SOwen Anderson 	mappings.MoveFrom(&area->mappings);
7430a367809SOwen Anderson 
7440a367809SOwen Anderson 	for (VMAreaMappings::Iterator it = mappings.GetIterator();
7450a367809SOwen Anderson 			vm_page_mapping* mapping = it.Next();) {
7460a367809SOwen Anderson 
7470a367809SOwen Anderson 		vm_page* page = mapping->page;
7480a367809SOwen Anderson 		page->mappings.Remove(mapping);
7490a367809SOwen Anderson 
7500a367809SOwen Anderson 		VMCache* cache = page->Cache();
7510a367809SOwen Anderson 
7520a367809SOwen Anderson 		bool pageFullyUnmapped = false;
7530a367809SOwen Anderson 		if (!page->IsMapped()) {
7540a367809SOwen Anderson 			atomic_add(&gMappedPagesCount, -1);
7550a367809SOwen Anderson 			pageFullyUnmapped = true;
7560a367809SOwen Anderson 		}
7570a367809SOwen Anderson 
7580a367809SOwen Anderson 		if (unmapPages || cache != area->cache) {
7590a367809SOwen Anderson 			addr_t address = area->Base()
7600a367809SOwen Anderson 				+ ((page->cache_offset * B_PAGE_SIZE)
7610a367809SOwen Anderson 				- area->cache_offset);
7620a367809SOwen Anderson 
7630a367809SOwen Anderson 			uint64_t oldPte = 0;
764af5e461fSOwen Anderson 			ProcessRange(fPageTable, fInitialLevel, address, B_PAGE_SIZE, nullptr,
7650a367809SOwen Anderson 				[=, &oldPte](uint64_t* ptePtr, uint64_t effectiveVa) {
7660a367809SOwen Anderson 					oldPte = atomic_get_and_set64((int64_t*)ptePtr, 0);
767129bc12bSOwen Anderson 					if (!deletingAddressSpace)
768129bc12bSOwen Anderson 						FlushVAIfAccessed(oldPte, effectiveVa);
7690a367809SOwen Anderson 				});
7700a367809SOwen Anderson 
7710a367809SOwen Anderson 			if ((oldPte & kPteValidMask) == 0) {
7720a367809SOwen Anderson 				panic("page %p has mapping for area %p "
7730a367809SOwen Anderson 					"(%#" B_PRIxADDR "), but has no "
7740a367809SOwen Anderson 					"page table", page, area, address);
7750a367809SOwen Anderson 				continue;
7760a367809SOwen Anderson 			}
7770a367809SOwen Anderson 
7780a367809SOwen Anderson 			// transfer the accessed/dirty flags to the page and
7790a367809SOwen Anderson 			// invalidate the mapping, if necessary
7800a367809SOwen Anderson 			if (is_pte_dirty(oldPte))
7810a367809SOwen Anderson 				page->modified = true;
7820a367809SOwen Anderson 			if (oldPte & kAttrAF)
7830a367809SOwen Anderson 				page->accessed = true;
7840a367809SOwen Anderson 
7850a367809SOwen Anderson 			if (pageFullyUnmapped) {
7860a367809SOwen Anderson 				DEBUG_PAGE_ACCESS_START(page);
7870a367809SOwen Anderson 
7880a367809SOwen Anderson 				if (cache->temporary) {
7890a367809SOwen Anderson 					vm_page_set_state(page,
7900a367809SOwen Anderson 						PAGE_STATE_INACTIVE);
7910a367809SOwen Anderson 				} else if (page->modified) {
7920a367809SOwen Anderson 					vm_page_set_state(page,
7930a367809SOwen Anderson 						PAGE_STATE_MODIFIED);
7940a367809SOwen Anderson 				} else {
7950a367809SOwen Anderson 					vm_page_set_state(page,
7960a367809SOwen Anderson 						PAGE_STATE_CACHED);
7970a367809SOwen Anderson 				}
7980a367809SOwen Anderson 
7990a367809SOwen Anderson 				DEBUG_PAGE_ACCESS_END(page);
8000a367809SOwen Anderson 			}
8010a367809SOwen Anderson 		}
8020a367809SOwen Anderson 	}
8030a367809SOwen Anderson 
8040a367809SOwen Anderson 	locker.Unlock();
8050a367809SOwen Anderson 
8060a367809SOwen Anderson 	bool isKernelSpace = area->address_space == VMAddressSpace::Kernel();
8070a367809SOwen Anderson 	uint32 freeFlags = CACHE_DONT_WAIT_FOR_MEMORY
8080a367809SOwen Anderson 		| (isKernelSpace ? CACHE_DONT_LOCK_KERNEL_SPACE : 0);
8090a367809SOwen Anderson 
8100a367809SOwen Anderson 	while (vm_page_mapping* mapping = mappings.RemoveHead())
8110a367809SOwen Anderson 		vm_free_page_mapping(mapping->page->physical_page_number, mapping, freeFlags);
8120a367809SOwen Anderson }
8130a367809SOwen Anderson 
8140a367809SOwen Anderson 
815a25542e7Smilek7 bool
816a25542e7Smilek7 VMSAv8TranslationMap::ValidateVa(addr_t va)
817a25542e7Smilek7 {
818a25542e7Smilek7 	uint64_t vaMask = (1UL << fVaBits) - 1;
819a25542e7Smilek7 	bool kernelAddr = (va & (1UL << 63)) != 0;
820a25542e7Smilek7 	if (kernelAddr != fIsKernel)
821a25542e7Smilek7 		return false;
822a25542e7Smilek7 	if ((va & ~vaMask) != (fIsKernel ? ~vaMask : 0))
823a25542e7Smilek7 		return false;
824a25542e7Smilek7 	return true;
825a25542e7Smilek7 }
826a25542e7Smilek7 
827a25542e7Smilek7 
828a25542e7Smilek7 status_t
829a25542e7Smilek7 VMSAv8TranslationMap::Query(addr_t va, phys_addr_t* pa, uint32* flags)
830a25542e7Smilek7 {
83173c51743SOwen Anderson 	*flags = 0;
83273c51743SOwen Anderson 	*pa = 0;
83373c51743SOwen Anderson 
83473c51743SOwen Anderson 	uint64_t pageMask = (1UL << fPageBits) - 1;
835088b72e7SOwen Anderson 	va &= ~pageMask;
836af5e461fSOwen Anderson 
837af5e461fSOwen Anderson 	ThreadCPUPinner pinner(thread_get_current_thread());
838a25542e7Smilek7 	ASSERT(ValidateVa(va));
839a25542e7Smilek7 
840af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, va, B_PAGE_SIZE, nullptr,
84173c51743SOwen Anderson 		[=](uint64_t* ptePtr, uint64_t effectiveVa) {
84273c51743SOwen Anderson 			uint64_t pte = atomic_get64((int64_t*)ptePtr);
84373c51743SOwen Anderson 			*pa = pte & kPteAddrMask;
84473c51743SOwen Anderson 			*flags |= PAGE_PRESENT | B_KERNEL_READ_AREA;
845a25542e7Smilek7 			if ((pte & kAttrAF) != 0)
84673c51743SOwen Anderson 				*flags |= PAGE_ACCESSED;
8476a2e4f41SOwen Anderson 			if (is_pte_dirty(pte))
84873c51743SOwen Anderson 				*flags |= PAGE_MODIFIED;
849a25542e7Smilek7 
850a25542e7Smilek7 			if ((pte & kAttrUXN) == 0)
85173c51743SOwen Anderson 				*flags |= B_EXECUTE_AREA;
852a25542e7Smilek7 			if ((pte & kAttrPXN) == 0)
85373c51743SOwen Anderson 				*flags |= B_KERNEL_EXECUTE_AREA;
854a25542e7Smilek7 
855108f6fdcSOwen Anderson 			if ((pte & kAttrAPUserAccess) != 0)
85673c51743SOwen Anderson 				*flags |= B_READ_AREA;
857a25542e7Smilek7 
8586a2e4f41SOwen Anderson 			if ((pte & kAttrSWDBM) != 0) {
85973c51743SOwen Anderson 				*flags |= B_KERNEL_WRITE_AREA;
860108f6fdcSOwen Anderson 				if ((pte & kAttrAPUserAccess) != 0)
86173c51743SOwen Anderson 					*flags |= B_WRITE_AREA;
862a25542e7Smilek7 			}
86373c51743SOwen Anderson 		});
864a25542e7Smilek7 
865a25542e7Smilek7 	return B_OK;
866a25542e7Smilek7 }
867a25542e7Smilek7 
868a25542e7Smilek7 
869a25542e7Smilek7 status_t
870a25542e7Smilek7 VMSAv8TranslationMap::QueryInterrupt(
871a25542e7Smilek7 	addr_t virtualAddress, phys_addr_t* _physicalAddress, uint32* _flags)
872a25542e7Smilek7 {
873a25542e7Smilek7 	return Query(virtualAddress, _physicalAddress, _flags);
874a25542e7Smilek7 }
875a25542e7Smilek7 
876a25542e7Smilek7 
877a25542e7Smilek7 status_t
878a25542e7Smilek7 VMSAv8TranslationMap::Protect(addr_t start, addr_t end, uint32 attributes, uint32 memoryType)
879a25542e7Smilek7 {
88032c542bdSOwen Anderson 	TRACE("VMSAv8TranslationMap::Protect(0x%" B_PRIxADDR ", 0x%"
88132c542bdSOwen Anderson 		B_PRIxADDR ", 0x%x, 0x%x)\n", start, end, attributes, memoryType);
88232c542bdSOwen Anderson 
883f73ff202SOwen Anderson 	uint64_t attr = GetMemoryAttr(attributes, memoryType, fIsKernel);
884a25542e7Smilek7 	size_t size = end - start + 1;
885a25542e7Smilek7 	ASSERT(ValidateVa(start));
886a25542e7Smilek7 
887af5e461fSOwen Anderson 	ThreadCPUPinner pinner(thread_get_current_thread());
888af5e461fSOwen Anderson 
889af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, start, size, nullptr,
890f73ff202SOwen Anderson 		[=](uint64_t* ptePtr, uint64_t effectiveVa) {
891f73ff202SOwen Anderson 			// We need to use an atomic compare-swap loop because we must
892f73ff202SOwen Anderson 			// need to clear somes bits while setting others.
893f73ff202SOwen Anderson 			while (true) {
894f73ff202SOwen Anderson 				uint64_t oldPte = atomic_get64((int64_t*)ptePtr);
895f73ff202SOwen Anderson 				uint64_t newPte = oldPte & ~kPteAttrMask;
896f73ff202SOwen Anderson 				newPte |= attr;
897f73ff202SOwen Anderson 
8984bb796cfSOwen Anderson 				// Preserve access bit.
8994bb796cfSOwen Anderson 				newPte |= oldPte & kAttrAF;
9004bb796cfSOwen Anderson 
9016a2e4f41SOwen Anderson 				// Preserve the dirty bit.
9026a2e4f41SOwen Anderson 				if (is_pte_dirty(oldPte))
9036a2e4f41SOwen Anderson 					newPte = set_pte_dirty(newPte);
9044bb796cfSOwen Anderson 
9054bb796cfSOwen Anderson 				uint64_t oldMemoryType = oldPte & (kAttrShareability | kAttrMemoryAttrIdx);
9064bb796cfSOwen Anderson 				uint64_t newMemoryType = newPte & (kAttrShareability | kAttrMemoryAttrIdx);
9074bb796cfSOwen Anderson 				if (oldMemoryType != newMemoryType) {
9084bb796cfSOwen Anderson 					// ARM64 requires "break-before-make". We must set the PTE to an invalid
9094bb796cfSOwen Anderson 					// entry and flush the TLB as appropriate before we can write the new PTE.
9104bb796cfSOwen Anderson 					// In this case specifically, it applies any time we change cacheability or
9114bb796cfSOwen Anderson 					// shareability.
912129bc12bSOwen Anderson 					if (!AttemptPteBreakBeforeMake(ptePtr, oldPte, effectiveVa))
9134bb796cfSOwen Anderson 						continue;
9144bb796cfSOwen Anderson 
9154bb796cfSOwen Anderson 					atomic_set64((int64_t*)ptePtr, newPte);
9164bb796cfSOwen Anderson 					asm("dsb ishst"); // Ensure PTE write completed
917129bc12bSOwen Anderson 					asm("isb");
9184bb796cfSOwen Anderson 
9194bb796cfSOwen Anderson 					// No compare-exchange loop required in this case.
9204bb796cfSOwen Anderson 					break;
9214bb796cfSOwen Anderson 				} else {
922f73ff202SOwen Anderson 					if ((uint64_t)atomic_test_and_set64((int64_t*)ptePtr, newPte, oldPte) == oldPte) {
923129bc12bSOwen Anderson 						FlushVAIfAccessed(oldPte, effectiveVa);
924f73ff202SOwen Anderson 						break;
925f73ff202SOwen Anderson 					}
926f73ff202SOwen Anderson 				}
9274bb796cfSOwen Anderson 			}
928f73ff202SOwen Anderson 		});
929a25542e7Smilek7 
930a25542e7Smilek7 	return B_OK;
931a25542e7Smilek7 }
932a25542e7Smilek7 
933a25542e7Smilek7 
934a25542e7Smilek7 status_t
935a25542e7Smilek7 VMSAv8TranslationMap::ClearFlags(addr_t va, uint32 flags)
936a25542e7Smilek7 {
937a25542e7Smilek7 	ASSERT(ValidateVa(va));
938a25542e7Smilek7 
9394bb796cfSOwen Anderson 	bool clearAF = flags & PAGE_ACCESSED;
9404bb796cfSOwen Anderson 	bool setRO = flags & PAGE_MODIFIED;
941a25542e7Smilek7 
942744bdd73SOwen Anderson 	if (!clearAF && !setRO)
943744bdd73SOwen Anderson 		return B_OK;
944744bdd73SOwen Anderson 
945af5e461fSOwen Anderson 	ThreadCPUPinner pinner(thread_get_current_thread());
946af5e461fSOwen Anderson 
947129bc12bSOwen Anderson 	uint64_t oldPte = 0;
948af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, va, B_PAGE_SIZE, nullptr,
949129bc12bSOwen Anderson 		[=, &oldPte](uint64_t* ptePtr, uint64_t effectiveVa) {
950744bdd73SOwen Anderson 			if (clearAF && setRO) {
951744bdd73SOwen Anderson 				// We need to use an atomic compare-swap loop because we must
952744bdd73SOwen Anderson 				// need to clear one bit while setting the other.
953744bdd73SOwen Anderson 				while (true) {
954129bc12bSOwen Anderson 					oldPte = atomic_get64((int64_t*)ptePtr);
955744bdd73SOwen Anderson 					uint64_t newPte = oldPte & ~kAttrAF;
9566a2e4f41SOwen Anderson 					newPte = set_pte_clean(newPte);
957744bdd73SOwen Anderson 
958744bdd73SOwen Anderson                     if ((uint64_t)atomic_test_and_set64((int64_t*)ptePtr, newPte, oldPte) == oldPte)
959744bdd73SOwen Anderson 						break;
960744bdd73SOwen Anderson 				}
961744bdd73SOwen Anderson 			} else if (clearAF) {
962129bc12bSOwen Anderson 				oldPte = atomic_and64((int64_t*)ptePtr, ~kAttrAF);
963744bdd73SOwen Anderson 			} else {
9646a2e4f41SOwen Anderson 				while (true) {
965129bc12bSOwen Anderson 					oldPte = atomic_get64((int64_t*)ptePtr);
966129bc12bSOwen Anderson 					if (!is_pte_dirty(oldPte)) {
967129bc12bSOwen Anderson 						// Avoid a TLB flush
968129bc12bSOwen Anderson 						oldPte = 0;
9696a2e4f41SOwen Anderson 						return;
970129bc12bSOwen Anderson 					}
9716a2e4f41SOwen Anderson 					uint64_t newPte = set_pte_clean(oldPte);
9726a2e4f41SOwen Anderson                     if ((uint64_t)atomic_test_and_set64((int64_t*)ptePtr, newPte, oldPte) == oldPte)
9736a2e4f41SOwen Anderson 						break;
9746a2e4f41SOwen Anderson 				}
975744bdd73SOwen Anderson 			}
976744bdd73SOwen Anderson 		});
977744bdd73SOwen Anderson 
978129bc12bSOwen Anderson 	FlushVAIfAccessed(oldPte, va);
979129bc12bSOwen Anderson 
980a25542e7Smilek7 	return B_OK;
981a25542e7Smilek7 }
982a25542e7Smilek7 
983a25542e7Smilek7 
984a25542e7Smilek7 bool
985a25542e7Smilek7 VMSAv8TranslationMap::ClearAccessedAndModified(
986a25542e7Smilek7 	VMArea* area, addr_t address, bool unmapIfUnaccessed, bool& _modified)
987a25542e7Smilek7 {
98832c542bdSOwen Anderson 	TRACE("VMSAv8TranslationMap::ClearAccessedAndModified(0x%"
98932c542bdSOwen Anderson 		B_PRIxADDR "(%s), 0x%" B_PRIxADDR ", %d)\n", (addr_t)area,
99032c542bdSOwen Anderson 		area->name, address, unmapIfUnaccessed);
991af5e461fSOwen Anderson 	ASSERT(ValidateVa(address));
99232c542bdSOwen Anderson 
993bb67bf75SOwen Anderson 	RecursiveLocker locker(fLock);
994bb67bf75SOwen Anderson 	ThreadCPUPinner pinner(thread_get_current_thread());
995bb67bf75SOwen Anderson 
996bb67bf75SOwen Anderson 	uint64_t oldPte = 0;
997af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, address, B_PAGE_SIZE, nullptr,
9984bb796cfSOwen Anderson 		[=, &oldPte](uint64_t* ptePtr, uint64_t effectiveVa) {
999bb67bf75SOwen Anderson 			// We need to use an atomic compare-swap loop because we must
1000bb67bf75SOwen Anderson 			// first read the old PTE and make decisions based on the AF
1001bb67bf75SOwen Anderson 			// bit to proceed.
1002bb67bf75SOwen Anderson 			while (true) {
1003bb67bf75SOwen Anderson 				oldPte = atomic_get64((int64_t*)ptePtr);
1004bb67bf75SOwen Anderson 				uint64_t newPte = oldPte & ~kAttrAF;
10056a2e4f41SOwen Anderson 				newPte = set_pte_clean(newPte);
1006bb67bf75SOwen Anderson 
1007bb67bf75SOwen Anderson 				// If the page has been not be accessed, then unmap it.
1008bb67bf75SOwen Anderson 				if (unmapIfUnaccessed && (oldPte & kAttrAF) == 0)
1009bb67bf75SOwen Anderson 					newPte = 0;
1010bb67bf75SOwen Anderson 
1011bb67bf75SOwen Anderson 				if ((uint64_t)atomic_test_and_set64((int64_t*)ptePtr, newPte, oldPte) == oldPte)
1012bb67bf75SOwen Anderson 					break;
1013bb67bf75SOwen Anderson 			}
1014bb67bf75SOwen Anderson 			asm("dsb ishst"); // Ensure PTE write completed
1015bb67bf75SOwen Anderson 		});
1016bb67bf75SOwen Anderson 
1017bb67bf75SOwen Anderson 	pinner.Unlock();
10186a2e4f41SOwen Anderson 	_modified = is_pte_dirty(oldPte);
1019129bc12bSOwen Anderson 
1020129bc12bSOwen Anderson 	if (FlushVAIfAccessed(oldPte, address))
1021bb67bf75SOwen Anderson 		return true;
1022bb67bf75SOwen Anderson 
1023bb67bf75SOwen Anderson 	if (!unmapIfUnaccessed)
1024bb67bf75SOwen Anderson 		return false;
1025bb67bf75SOwen Anderson 
1026bb67bf75SOwen Anderson 	locker.Detach(); // UnaccessedPageUnmapped takes ownership
1027bb67bf75SOwen Anderson 	phys_addr_t oldPa = oldPte & kPteAddrMask;
1028bb67bf75SOwen Anderson 	UnaccessedPageUnmapped(area, oldPa >> fPageBits);
1029bb67bf75SOwen Anderson 	return false;
1030a25542e7Smilek7 }
1031a25542e7Smilek7 
1032a25542e7Smilek7 
1033a25542e7Smilek7 void
1034a25542e7Smilek7 VMSAv8TranslationMap::Flush()
1035a25542e7Smilek7 {
103683316034SOwen Anderson 	// Necessary invalidation is performed during mapping,
103783316034SOwen Anderson 	// no need to do anything more here.
1038a25542e7Smilek7 }
1039