xref: /haiku/src/system/kernel/arch/arm64/VMSAv8TranslationMap.cpp (revision af5e461fb16570a5a407725357302463bc0f8fde)
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 	if (recursive_lock_get_recursion(&fLock) == 1) {
244a25542e7Smilek7 		// we're about to release it for the last time
245a25542e7Smilek7 		Flush();
246a25542e7Smilek7 	}
247a25542e7Smilek7 	recursive_lock_unlock(&fLock);
248a25542e7Smilek7 }
249a25542e7Smilek7 
250a25542e7Smilek7 
251a25542e7Smilek7 addr_t
252a25542e7Smilek7 VMSAv8TranslationMap::MappedSize() const
253a25542e7Smilek7 {
254a25542e7Smilek7 	panic("VMSAv8TranslationMap::MappedSize not implemented");
255a25542e7Smilek7 	return 0;
256a25542e7Smilek7 }
257a25542e7Smilek7 
258a25542e7Smilek7 
259a25542e7Smilek7 size_t
260a25542e7Smilek7 VMSAv8TranslationMap::MaxPagesNeededToMap(addr_t start, addr_t end) const
261a25542e7Smilek7 {
262a25542e7Smilek7 	size_t result = 0;
263a25542e7Smilek7 	size_t size = end - start + 1;
264a25542e7Smilek7 
265a25542e7Smilek7 	for (int i = fInitialLevel; i < 3; i++) {
266a25542e7Smilek7 		int tableBits = fPageBits - 3;
267a25542e7Smilek7 		int shift = tableBits * (3 - i) + fPageBits;
268a25542e7Smilek7 		uint64_t entrySize = 1UL << shift;
269a25542e7Smilek7 
270a25542e7Smilek7 		result += size / entrySize + 2;
271a25542e7Smilek7 	}
272a25542e7Smilek7 
273a25542e7Smilek7 	return result;
274a25542e7Smilek7 }
275a25542e7Smilek7 
276a25542e7Smilek7 
277a25542e7Smilek7 uint64_t*
278a25542e7Smilek7 VMSAv8TranslationMap::TableFromPa(phys_addr_t pa)
279a25542e7Smilek7 {
280a25542e7Smilek7 	return reinterpret_cast<uint64_t*>(KERNEL_PMAP_BASE + pa);
281a25542e7Smilek7 }
282a25542e7Smilek7 
283a25542e7Smilek7 
2847908993dSOwen Anderson template<typename EntryRemoved>
285a25542e7Smilek7 void
2867908993dSOwen Anderson VMSAv8TranslationMap::FreeTable(phys_addr_t ptPa, uint64_t va, int level,
2877908993dSOwen Anderson 	EntryRemoved &&entryRemoved)
288a25542e7Smilek7 {
2897908993dSOwen Anderson 	ASSERT(level < 4);
290a25542e7Smilek7 
291a25542e7Smilek7 	int tableBits = fPageBits - 3;
292a25542e7Smilek7 	uint64_t tableSize = 1UL << tableBits;
2937908993dSOwen Anderson 	uint64_t vaMask = (1UL << fVaBits) - 1;
294a25542e7Smilek7 
2957908993dSOwen Anderson 	int shift = tableBits * (3 - level) + fPageBits;
2967908993dSOwen Anderson 	uint64_t entrySize = 1UL << shift;
2977908993dSOwen Anderson 
2987908993dSOwen Anderson 	uint64_t nextVa = va;
299a25542e7Smilek7 	uint64_t* pt = TableFromPa(ptPa);
300a25542e7Smilek7 	for (uint64_t i = 0; i < tableSize; i++) {
3017908993dSOwen Anderson 		uint64_t oldPte = (uint64_t) atomic_get_and_set64((int64*) &pt[i], 0);
3027908993dSOwen Anderson 
30318a27fe0SOwen Anderson 		if (level < 3 && (oldPte & kPteTypeMask) == kPteTypeL012Table) {
3047908993dSOwen Anderson 			FreeTable(oldPte & kPteAddrMask, nextVa, level + 1, entryRemoved);
30518a27fe0SOwen Anderson 		} else if ((oldPte & kPteTypeMask) != 0) {
3067908993dSOwen Anderson 			uint64_t fullVa = (fIsKernel ? ~vaMask : 0) | nextVa;
3077908993dSOwen Anderson 			asm("dsb ishst");
3087908993dSOwen Anderson 			asm("tlbi vaae1is, %0" :: "r" ((fullVa >> 12) & kTLBIMask));
3097908993dSOwen Anderson 			// Does it correctly flush block entries at level < 3? We don't use them anyway though.
3107908993dSOwen Anderson 			// TODO: Flush only currently used ASID (using vae1is)
3117908993dSOwen Anderson 			entryRemoved(level, oldPte);
312a25542e7Smilek7 		}
313a25542e7Smilek7 
3147908993dSOwen Anderson 		nextVa += entrySize;
3157908993dSOwen Anderson 	}
3167908993dSOwen Anderson 
3177908993dSOwen Anderson 	asm("dsb ish");
3187908993dSOwen Anderson 
319a25542e7Smilek7 	vm_page* page = vm_lookup_page(ptPa >> fPageBits);
3207908993dSOwen Anderson 	DEBUG_PAGE_ACCESS_START(page);
321a25542e7Smilek7 	vm_page_set_state(page, PAGE_STATE_FREE);
322a25542e7Smilek7 }
323a25542e7Smilek7 
324a25542e7Smilek7 
32518a27fe0SOwen Anderson // Make a new page sub-table.
32618a27fe0SOwen Anderson // The parent table is `ptPa`, and the new sub-table's PTE will be at `index`
32718a27fe0SOwen Anderson // in it.
32818a27fe0SOwen Anderson // Returns the physical address of the new table, or the address of the existing
32918a27fe0SOwen Anderson // one if the PTE is already filled.
330a25542e7Smilek7 phys_addr_t
331baf574c9SOwen Anderson VMSAv8TranslationMap::GetOrMakeTable(phys_addr_t ptPa, int level, int index,
332baf574c9SOwen Anderson 	vm_page_reservation* reservation)
333a25542e7Smilek7 {
33418a27fe0SOwen Anderson 	ASSERT(level < 3);
335a25542e7Smilek7 
33618a27fe0SOwen Anderson 	uint64_t* ptePtr = TableFromPa(ptPa) + index;
33718a27fe0SOwen Anderson 	uint64_t oldPte = atomic_get64((int64*) ptePtr);
338a25542e7Smilek7 
33918a27fe0SOwen Anderson 	int type = oldPte & kPteTypeMask;
34018a27fe0SOwen Anderson 	if (type == kPteTypeL012Table) {
34118a27fe0SOwen Anderson 		// This is table entry already, just return it
342a25542e7Smilek7 		return oldPte & kPteAddrMask;
34318a27fe0SOwen Anderson 	} else if (reservation != nullptr) {
34418a27fe0SOwen Anderson 		// Create new table there
34518a27fe0SOwen Anderson 		vm_page* page = vm_page_allocate_page(reservation, PAGE_STATE_WIRED | VM_PAGE_ALLOC_CLEAR);
346a25542e7Smilek7 		phys_addr_t newTablePa = page->physical_page_number << fPageBits;
34718a27fe0SOwen Anderson 		DEBUG_PAGE_ACCESS_END(page);
348a25542e7Smilek7 
34918a27fe0SOwen Anderson 		// We only create mappings at the final level so we don't need to handle
35018a27fe0SOwen Anderson 		// splitting block mappings
351baf574c9SOwen Anderson 		ASSERT(type != kPteTypeL12Block);
352a25542e7Smilek7 
35318a27fe0SOwen Anderson 		// Ensure that writes to page being attached have completed
35418a27fe0SOwen Anderson 		asm("dsb ishst");
355a25542e7Smilek7 
35618a27fe0SOwen Anderson 		uint64_t oldPteRefetch = (uint64_t)atomic_test_and_set64((int64*) ptePtr,
35718a27fe0SOwen Anderson 			newTablePa | kPteTypeL012Table, oldPte);
35818a27fe0SOwen Anderson 		if (oldPteRefetch != oldPte) {
35918a27fe0SOwen Anderson 			// If the old PTE has mutated, it must be because another thread has allocated the
36018a27fe0SOwen Anderson 			// sub-table at the same time as us. If that has happened, deallocate the page we
36118a27fe0SOwen Anderson 			// setup and use the one they installed instead.
36218a27fe0SOwen Anderson 			ASSERT((oldPteRefetch & kPteTypeMask) == kPteTypeL012Table);
36318a27fe0SOwen Anderson 			DEBUG_PAGE_ACCESS_START(page);
36418a27fe0SOwen Anderson 			vm_page_set_state(page, PAGE_STATE_FREE);
36518a27fe0SOwen Anderson 			return oldPteRefetch & kPteAddrMask;
366a25542e7Smilek7 		}
367a25542e7Smilek7 
368a25542e7Smilek7 		return newTablePa;
369a25542e7Smilek7 	}
370a25542e7Smilek7 
37118a27fe0SOwen Anderson 	// There's no existing table and we have no reservation
372a25542e7Smilek7 	return 0;
373a25542e7Smilek7 }
374a25542e7Smilek7 
375a25542e7Smilek7 
376129bc12bSOwen Anderson bool
377129bc12bSOwen Anderson VMSAv8TranslationMap::FlushVAIfAccessed(uint64_t pte, addr_t va)
378baf574c9SOwen Anderson {
379129bc12bSOwen Anderson 	if (!is_pte_accessed(pte))
380129bc12bSOwen Anderson 		return false;
381129bc12bSOwen Anderson 
3824b9a9eabSOwen Anderson 	InterruptsSpinLocker locker(sAsidLock);
383*af5e461fSOwen Anderson 	if (fIsKernel) {
384*af5e461fSOwen Anderson 		// We can't flush by ASID for kernel space.
385*af5e461fSOwen Anderson 		asm("dsb ishst"); // Ensure PTE write completed
386*af5e461fSOwen Anderson 		asm("tlbi vaae1is, %0" ::"r"(((va >> 12) & kTLBIMask)));
387*af5e461fSOwen Anderson 		asm("dsb ish");
388*af5e461fSOwen Anderson 		asm("isb");
389*af5e461fSOwen Anderson 	} else if (fASID != -1) {
390129bc12bSOwen Anderson 		asm("dsb ishst"); // Ensure PTE write completed
391baf574c9SOwen Anderson         asm("tlbi vae1is, %0" ::"r"(((va >> 12) & kTLBIMask) | (uint64_t(fASID) << 48)));
392baf574c9SOwen Anderson 		asm("dsb ish"); // Wait for TLB flush to complete
393129bc12bSOwen Anderson 		asm("isb");
394129bc12bSOwen Anderson 		return true;
395baf574c9SOwen Anderson 	}
396129bc12bSOwen Anderson 
397129bc12bSOwen Anderson 	return false;
398baf574c9SOwen Anderson }
399baf574c9SOwen Anderson 
400baf574c9SOwen Anderson 
401129bc12bSOwen Anderson bool
4024bb796cfSOwen Anderson VMSAv8TranslationMap::AttemptPteBreakBeforeMake(uint64_t* ptePtr, uint64_t oldPte, addr_t va)
403baf574c9SOwen Anderson {
4044bb796cfSOwen Anderson 	uint64_t loadedPte = atomic_test_and_set64((int64_t*)ptePtr, 0, oldPte);
4054bb796cfSOwen Anderson 	if (loadedPte != oldPte)
406129bc12bSOwen Anderson 		return false;
4074bb796cfSOwen Anderson 
408129bc12bSOwen Anderson 	FlushVAIfAccessed(oldPte, va);
409129bc12bSOwen Anderson 
410129bc12bSOwen Anderson 	return true;
411baf574c9SOwen Anderson }
412baf574c9SOwen Anderson 
413baf574c9SOwen Anderson 
414baf574c9SOwen Anderson template<typename UpdatePte>
415baf574c9SOwen Anderson void
416baf574c9SOwen Anderson VMSAv8TranslationMap::ProcessRange(phys_addr_t ptPa, int level, addr_t va, size_t size,
417baf574c9SOwen Anderson     vm_page_reservation* reservation, UpdatePte&& updatePte)
418baf574c9SOwen Anderson {
419baf574c9SOwen Anderson 	ASSERT(level < 4);
420baf574c9SOwen Anderson 	ASSERT(ptPa != 0);
421baf574c9SOwen Anderson 
422*af5e461fSOwen Anderson 	uint64_t pageMask = (1UL << fPageBits) - 1;
423*af5e461fSOwen Anderson 	uint64_t vaMask = (1UL << fVaBits) - 1;
424*af5e461fSOwen Anderson 
425*af5e461fSOwen Anderson 	ASSERT((va & pageMask) == 0);
426*af5e461fSOwen Anderson 
427baf574c9SOwen Anderson 	int tableBits = fPageBits - 3;
428baf574c9SOwen Anderson 	uint64_t tableMask = (1UL << tableBits) - 1;
429baf574c9SOwen Anderson 
430baf574c9SOwen Anderson 	int shift = tableBits * (3 - level) + fPageBits;
431baf574c9SOwen Anderson 	uint64_t entrySize = 1UL << shift;
432baf574c9SOwen Anderson 	uint64_t entryMask = entrySize - 1;
433baf574c9SOwen Anderson 
434baf574c9SOwen Anderson 	uint64_t alignedDownVa = va & ~entryMask;
435baf574c9SOwen Anderson 	uint64_t alignedUpEnd = (va + size + (entrySize - 1)) & ~entryMask;
436baf574c9SOwen Anderson 	if (level == 3)
437baf574c9SOwen Anderson 		ASSERT(alignedDownVa == va);
438baf574c9SOwen Anderson 
439baf574c9SOwen Anderson     for (uint64_t effectiveVa = alignedDownVa; effectiveVa < alignedUpEnd;
440baf574c9SOwen Anderson         effectiveVa += entrySize) {
441*af5e461fSOwen Anderson 		int index = ((effectiveVa & vaMask) >> shift) & tableMask;
442baf574c9SOwen Anderson 		uint64_t* ptePtr = TableFromPa(ptPa) + index;
443baf574c9SOwen Anderson 
444baf574c9SOwen Anderson 		if (level == 3) {
445baf574c9SOwen Anderson 			updatePte(ptePtr, effectiveVa);
446baf574c9SOwen Anderson 		} else {
447baf574c9SOwen Anderson 			phys_addr_t subTable = GetOrMakeTable(ptPa, level, index, reservation);
448baf574c9SOwen Anderson 
449baf574c9SOwen Anderson 			// When reservation is null, we can't create a new subtable. This can be intentional,
450baf574c9SOwen Anderson 			// for example when called from Unmap().
451baf574c9SOwen Anderson 			if (subTable == 0)
452baf574c9SOwen Anderson 				continue;
453baf574c9SOwen Anderson 
454baf574c9SOwen Anderson 			uint64_t subVa = std::max(effectiveVa, va);
455baf574c9SOwen Anderson 			size_t subSize = std::min(size_t(entrySize - (subVa & entryMask)), size);
456baf574c9SOwen Anderson             ProcessRange(subTable, level + 1, subVa, subSize, reservation, updatePte);
457baf574c9SOwen Anderson 
458baf574c9SOwen Anderson 			size -= subSize;
459baf574c9SOwen Anderson 		}
460baf574c9SOwen Anderson 	}
461baf574c9SOwen Anderson }
462baf574c9SOwen Anderson 
463baf574c9SOwen Anderson 
464a25542e7Smilek7 uint8_t
465a25542e7Smilek7 VMSAv8TranslationMap::MairIndex(uint8_t type)
466a25542e7Smilek7 {
467a25542e7Smilek7 	for (int i = 0; i < 8; i++)
468a25542e7Smilek7 		if (((fMair >> (i * 8)) & 0xff) == type)
469a25542e7Smilek7 			return i;
470a25542e7Smilek7 
471a25542e7Smilek7 	panic("MAIR entry not found");
472a25542e7Smilek7 	return 0;
473a25542e7Smilek7 }
474a25542e7Smilek7 
475a25542e7Smilek7 
476a25542e7Smilek7 uint64_t
477a25542e7Smilek7 VMSAv8TranslationMap::GetMemoryAttr(uint32 attributes, uint32 memoryType, bool isKernel)
478a25542e7Smilek7 {
479a25542e7Smilek7 	uint64_t attr = 0;
480a25542e7Smilek7 
481a25542e7Smilek7 	if (!isKernel)
482a25542e7Smilek7 		attr |= kAttrNG;
483a25542e7Smilek7 
484a25542e7Smilek7 	if ((attributes & B_EXECUTE_AREA) == 0)
485a25542e7Smilek7 		attr |= kAttrUXN;
486a25542e7Smilek7 	if ((attributes & B_KERNEL_EXECUTE_AREA) == 0)
487a25542e7Smilek7 		attr |= kAttrPXN;
488a25542e7Smilek7 
489108f6fdcSOwen Anderson 	// SWDBM is software reserved bit that we use to mark that
490108f6fdcSOwen Anderson 	// writes are allowed, and fault handler should clear kAttrAPReadOnly.
491108f6fdcSOwen Anderson 	// In that case kAttrAPReadOnly doubles as not-dirty bit.
492108f6fdcSOwen Anderson 	// Additionally dirty state can be stored in SWDIRTY, in order not to lose
493108f6fdcSOwen Anderson 	// dirty state when changing protection from RW to RO.
494a25542e7Smilek7 
495108f6fdcSOwen Anderson 	// All page permissions begin life in RO state.
496108f6fdcSOwen Anderson 	attr |= kAttrAPReadOnly;
497108f6fdcSOwen Anderson 
498108f6fdcSOwen Anderson 	// User-Execute implies User-Read, because it would break PAN otherwise
499108f6fdcSOwen Anderson 	if ((attributes & B_READ_AREA) != 0 || (attributes & B_EXECUTE_AREA) != 0)
500108f6fdcSOwen Anderson 		attr |= kAttrAPUserAccess; // Allow user reads
501108f6fdcSOwen Anderson 
502108f6fdcSOwen Anderson 	if ((attributes & B_WRITE_AREA) != 0 || (attributes & B_KERNEL_WRITE_AREA) != 0)
503108f6fdcSOwen Anderson 		attr |= kAttrSWDBM; // Mark as writeable
504108f6fdcSOwen Anderson 
505108f6fdcSOwen Anderson 	// When supported by hardware copy our SWDBM bit into DBM,
506108f6fdcSOwen Anderson 	// so that kAttrAPReadOnly is cleared on write attempt automatically
507108f6fdcSOwen Anderson 	// without going through fault handler.
508108f6fdcSOwen Anderson 	if ((fHwFeature & HW_DIRTY) != 0 && (attr & kAttrSWDBM) != 0)
509a25542e7Smilek7 		attr |= kAttrDBM;
510a25542e7Smilek7 
511108f6fdcSOwen Anderson 	attr |= kAttrSHInnerShareable; // Inner Shareable
512a25542e7Smilek7 
513108f6fdcSOwen Anderson 	uint8_t type = MAIR_NORMAL_WB;
514108f6fdcSOwen Anderson 
5158cb8c3d7SOwen Anderson 	switch (memoryType & B_MTR_MASK) {
5168cb8c3d7SOwen Anderson 		case B_MTR_UC:
5178cb8c3d7SOwen Anderson 			// TODO: This probably should be nGnRE for PCI
5188cb8c3d7SOwen Anderson 			type = MAIR_DEVICE_nGnRnE;
5198cb8c3d7SOwen Anderson 			break;
5208cb8c3d7SOwen Anderson 		case B_MTR_WC:
521edb17c54SOwen Anderson 			type = MAIR_NORMAL_NC;
5228cb8c3d7SOwen Anderson 			break;
5238cb8c3d7SOwen Anderson 		case B_MTR_WT:
524108f6fdcSOwen Anderson 			type = MAIR_NORMAL_WT;
5258cb8c3d7SOwen Anderson 			break;
5268cb8c3d7SOwen Anderson 		case B_MTR_WP:
527108f6fdcSOwen Anderson 			type = MAIR_NORMAL_WT;
5288cb8c3d7SOwen Anderson 			break;
5298cb8c3d7SOwen Anderson 		default:
5308cb8c3d7SOwen Anderson 		case B_MTR_WB:
531108f6fdcSOwen Anderson 			type = MAIR_NORMAL_WB;
5328cb8c3d7SOwen Anderson 			break;
5338cb8c3d7SOwen Anderson 	}
534108f6fdcSOwen Anderson 
535108f6fdcSOwen Anderson 	attr |= MairIndex(type) << 2;
536a25542e7Smilek7 
537a25542e7Smilek7 	return attr;
538a25542e7Smilek7 }
539a25542e7Smilek7 
540a25542e7Smilek7 
541a25542e7Smilek7 status_t
542a25542e7Smilek7 VMSAv8TranslationMap::Map(addr_t va, phys_addr_t pa, uint32 attributes, uint32 memoryType,
543a25542e7Smilek7 	vm_page_reservation* reservation)
544a25542e7Smilek7 {
54532c542bdSOwen Anderson 	TRACE("VMSAv8TranslationMap::Map(0x%" B_PRIxADDR ", 0x%" B_PRIxADDR
54632c542bdSOwen Anderson 		", 0x%x, 0x%x)\n", va, pa, attributes, memoryType);
54732c542bdSOwen Anderson 
548a25542e7Smilek7 	ThreadCPUPinner pinner(thread_get_current_thread());
549a25542e7Smilek7 
550a25542e7Smilek7 	ASSERT(ValidateVa(va));
551a25542e7Smilek7 	uint64_t attr = GetMemoryAttr(attributes, memoryType, fIsKernel);
552a25542e7Smilek7 
553baf574c9SOwen Anderson 	// During first mapping we need to allocate root table
554baf574c9SOwen Anderson 	if (fPageTable == 0) {
555a25542e7Smilek7 		vm_page* page = vm_page_allocate_page(reservation, PAGE_STATE_WIRED | VM_PAGE_ALLOC_CLEAR);
556baf574c9SOwen Anderson 		DEBUG_PAGE_ACCESS_END(page);
557a25542e7Smilek7 		fPageTable = page->physical_page_number << fPageBits;
558a25542e7Smilek7 	}
559a25542e7Smilek7 
560*af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, va, B_PAGE_SIZE, reservation,
561baf574c9SOwen Anderson 		[=](uint64_t* ptePtr, uint64_t effectiveVa) {
5624bb796cfSOwen Anderson 			while (true) {
563*af5e461fSOwen Anderson 				phys_addr_t effectivePa = effectiveVa - va + pa;
564baf574c9SOwen Anderson 				uint64_t oldPte = atomic_get64((int64*)ptePtr);
565baf574c9SOwen Anderson 				uint64_t newPte = effectivePa | attr | kPteTypeL3Page;
566baf574c9SOwen Anderson 
567baf574c9SOwen Anderson 				if (newPte == oldPte)
568baf574c9SOwen Anderson 					return;
569baf574c9SOwen Anderson 
570*af5e461fSOwen Anderson 				if ((oldPte & kPteValidMask) != 0) {
571baf574c9SOwen Anderson 					// ARM64 requires "break-before-make". We must set the PTE to an invalid
572baf574c9SOwen Anderson 					// entry and flush the TLB as appropriate before we can write the new PTE.
573129bc12bSOwen Anderson 					if (!AttemptPteBreakBeforeMake(ptePtr, oldPte, effectiveVa))
5744bb796cfSOwen Anderson 						continue;
575baf574c9SOwen Anderson 				}
576baf574c9SOwen Anderson 
577baf574c9SOwen Anderson 				// Install the new PTE
578baf574c9SOwen Anderson 				atomic_set64((int64*)ptePtr, newPte);
579baf574c9SOwen Anderson 				asm("dsb ishst"); // Ensure PTE write completed
580129bc12bSOwen Anderson 				asm("isb");
5814bb796cfSOwen Anderson 				break;
5824bb796cfSOwen Anderson 			}
583baf574c9SOwen Anderson 		});
584a25542e7Smilek7 
585a25542e7Smilek7 	return B_OK;
586a25542e7Smilek7 }
587a25542e7Smilek7 
588a25542e7Smilek7 
589a25542e7Smilek7 status_t
590a25542e7Smilek7 VMSAv8TranslationMap::Unmap(addr_t start, addr_t end)
591a25542e7Smilek7 {
59232c542bdSOwen Anderson 	TRACE("VMSAv8TranslationMap::Unmap(0x%" B_PRIxADDR ", 0x%" B_PRIxADDR
59332c542bdSOwen Anderson 		")\n", start, end);
594a25542e7Smilek7 	ThreadCPUPinner pinner(thread_get_current_thread());
595a25542e7Smilek7 
596a25542e7Smilek7 	size_t size = end - start + 1;
597a25542e7Smilek7 	ASSERT(ValidateVa(start));
598a25542e7Smilek7 
599baf574c9SOwen Anderson 	if (fPageTable == 0)
600baf574c9SOwen Anderson 		return B_OK;
601baf574c9SOwen Anderson 
602*af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, start, size, nullptr,
603baf574c9SOwen Anderson 		[=](uint64_t* ptePtr, uint64_t effectiveVa) {
604129bc12bSOwen Anderson 			uint64_t oldPte = atomic_get_and_set64((int64_t*)ptePtr, 0);
605129bc12bSOwen Anderson 			FlushVAIfAccessed(oldPte, effectiveVa);
606baf574c9SOwen Anderson 		});
607a25542e7Smilek7 
608a25542e7Smilek7 	return B_OK;
609a25542e7Smilek7 }
610a25542e7Smilek7 
611a25542e7Smilek7 
612a25542e7Smilek7 status_t
613a25542e7Smilek7 VMSAv8TranslationMap::UnmapPage(VMArea* area, addr_t address, bool updatePageQueue)
614a25542e7Smilek7 {
61532c542bdSOwen Anderson 	TRACE("VMSAv8TranslationMap::UnmapPage(0x%" B_PRIxADDR "(%s), 0x%"
61632c542bdSOwen Anderson 		B_PRIxADDR ", %d)\n", (addr_t)area, area->name, address,
61732c542bdSOwen Anderson 		updatePageQueue);
61832c542bdSOwen Anderson 
61973c51743SOwen Anderson 	ASSERT(ValidateVa(address));
620a25542e7Smilek7 	ThreadCPUPinner pinner(thread_get_current_thread());
621a25542e7Smilek7 	RecursiveLocker locker(fLock);
622a25542e7Smilek7 
62373c51743SOwen Anderson 	uint64_t oldPte = 0;
624*af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, address, B_PAGE_SIZE, nullptr,
62573c51743SOwen Anderson 		[=, &oldPte](uint64_t* ptePtr, uint64_t effectiveVa) {
62673c51743SOwen Anderson 			oldPte = atomic_get_and_set64((int64_t*)ptePtr, 0);
627129bc12bSOwen Anderson 			FlushVAIfAccessed(oldPte, effectiveVa);
62873c51743SOwen Anderson 		});
629a25542e7Smilek7 
6304b9a9eabSOwen Anderson 	if ((oldPte & kPteValidMask) == 0)
6314b9a9eabSOwen Anderson 		return B_ENTRY_NOT_FOUND;
6324b9a9eabSOwen Anderson 
633a25542e7Smilek7 	pinner.Unlock();
634a25542e7Smilek7 	locker.Detach();
63573c51743SOwen Anderson 	PageUnmapped(area, (oldPte & kPteAddrMask) >> fPageBits, (oldPte & kAttrAF) != 0,
6366a2e4f41SOwen Anderson 		is_pte_dirty(oldPte), updatePageQueue);
637a25542e7Smilek7 
638a25542e7Smilek7 	return B_OK;
639a25542e7Smilek7 }
640a25542e7Smilek7 
641a25542e7Smilek7 
6423b098011SOwen Anderson void
6433b098011SOwen Anderson VMSAv8TranslationMap::UnmapPages(VMArea* area, addr_t address, size_t size, bool updatePageQueue)
6443b098011SOwen Anderson {
6453b098011SOwen Anderson 	TRACE("VMSAv8TranslationMap::UnmapPages(0x%" B_PRIxADDR "(%s), 0x%"
6463b098011SOwen Anderson 		B_PRIxADDR ", 0x%" B_PRIxSIZE ", %d)\n", (addr_t)area,
6473b098011SOwen Anderson 		area->name, address, size, updatePageQueue);
6483b098011SOwen Anderson 
6493b098011SOwen Anderson 	ASSERT(ValidateVa(address));
6503b098011SOwen Anderson 	VMAreaMappings queue;
6513b098011SOwen Anderson 	ThreadCPUPinner pinner(thread_get_current_thread());
6523b098011SOwen Anderson 	RecursiveLocker locker(fLock);
6533b098011SOwen Anderson 
654*af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, address, size, nullptr,
6553b098011SOwen Anderson 		[=, &queue](uint64_t* ptePtr, uint64_t effectiveVa) {
6563b098011SOwen Anderson 			uint64_t oldPte = atomic_get_and_set64((int64_t*)ptePtr, 0);
657*af5e461fSOwen Anderson 			FlushVAIfAccessed(oldPte, effectiveVa);
6583b098011SOwen Anderson 			if ((oldPte & kPteValidMask) == 0)
6593b098011SOwen Anderson 				return;
6603b098011SOwen Anderson 
6613b098011SOwen Anderson 			if (area->cache_type == CACHE_TYPE_DEVICE)
6623b098011SOwen Anderson 				return;
6633b098011SOwen Anderson 
6643b098011SOwen Anderson 			// get the page
6653b098011SOwen Anderson 			vm_page* page = vm_lookup_page((oldPte & kPteAddrMask) >> fPageBits);
6663b098011SOwen Anderson 			ASSERT(page != NULL);
6673b098011SOwen Anderson 
6683b098011SOwen Anderson 			DEBUG_PAGE_ACCESS_START(page);
6693b098011SOwen Anderson 
6703b098011SOwen Anderson 			// transfer the accessed/dirty flags to the page
6713b098011SOwen Anderson 			page->accessed = (oldPte & kAttrAF) != 0;
6723b098011SOwen Anderson 			page->modified = is_pte_dirty(oldPte);
6733b098011SOwen Anderson 
6743b098011SOwen Anderson 			// remove the mapping object/decrement the wired_count of the
6753b098011SOwen Anderson 			// page
6763b098011SOwen Anderson 			if (area->wiring == B_NO_LOCK) {
6773b098011SOwen Anderson 				vm_page_mapping* mapping = NULL;
6783b098011SOwen Anderson 				vm_page_mappings::Iterator iterator
6793b098011SOwen Anderson 					= page->mappings.GetIterator();
6803b098011SOwen Anderson 				while ((mapping = iterator.Next()) != NULL) {
6813b098011SOwen Anderson 					if (mapping->area == area)
6823b098011SOwen Anderson 						break;
6833b098011SOwen Anderson 				}
6843b098011SOwen Anderson 
6853b098011SOwen Anderson 				ASSERT(mapping != NULL);
6863b098011SOwen Anderson 
6873b098011SOwen Anderson 				area->mappings.Remove(mapping);
6883b098011SOwen Anderson 				page->mappings.Remove(mapping);
6893b098011SOwen Anderson 				queue.Add(mapping);
6903b098011SOwen Anderson 			} else
6913b098011SOwen Anderson 				page->DecrementWiredCount();
6923b098011SOwen Anderson 
6933b098011SOwen Anderson 			if (!page->IsMapped()) {
6943b098011SOwen Anderson 				atomic_add(&gMappedPagesCount, -1);
6953b098011SOwen Anderson 
6963b098011SOwen Anderson 				if (updatePageQueue) {
6973b098011SOwen Anderson 					if (page->Cache()->temporary)
6983b098011SOwen Anderson 						vm_page_set_state(page, PAGE_STATE_INACTIVE);
6993b098011SOwen Anderson 					else if (page->modified)
7003b098011SOwen Anderson 						vm_page_set_state(page, PAGE_STATE_MODIFIED);
7013b098011SOwen Anderson 					else
7023b098011SOwen Anderson 						vm_page_set_state(page, PAGE_STATE_CACHED);
7033b098011SOwen Anderson 				}
7043b098011SOwen Anderson 			}
7053b098011SOwen Anderson 
7063b098011SOwen Anderson 			DEBUG_PAGE_ACCESS_END(page);
7073b098011SOwen Anderson 		});
7083b098011SOwen Anderson 
7093b098011SOwen Anderson 	// TODO: As in UnmapPage() we can lose page dirty flags here. ATM it's not
7103b098011SOwen Anderson 	// really critical here, as in all cases this method is used, the unmapped
7113b098011SOwen Anderson 	// area range is unmapped for good (resized/cut) and the pages will likely
7123b098011SOwen Anderson 	// be freed.
7133b098011SOwen Anderson 
7143b098011SOwen Anderson 	locker.Unlock();
7153b098011SOwen Anderson 
7163b098011SOwen Anderson 	// free removed mappings
7173b098011SOwen Anderson 	bool isKernelSpace = area->address_space == VMAddressSpace::Kernel();
7183b098011SOwen Anderson 	uint32 freeFlags = CACHE_DONT_WAIT_FOR_MEMORY
7193b098011SOwen Anderson 		| (isKernelSpace ? CACHE_DONT_LOCK_KERNEL_SPACE : 0);
7203b098011SOwen Anderson 
7213b098011SOwen Anderson 	while (vm_page_mapping* mapping = queue.RemoveHead())
7223b098011SOwen Anderson 		vm_free_page_mapping(mapping->page->physical_page_number, mapping, freeFlags);
7233b098011SOwen Anderson }
7243b098011SOwen Anderson 
7253b098011SOwen Anderson 
7260a367809SOwen Anderson void
7270a367809SOwen Anderson VMSAv8TranslationMap::UnmapArea(VMArea* area, bool deletingAddressSpace,
7280a367809SOwen Anderson 	bool ignoreTopCachePageFlags)
7290a367809SOwen Anderson {
7300a367809SOwen Anderson 	TRACE("VMSAv8TranslationMap::UnmapArea(0x%" B_PRIxADDR "(%s), 0x%"
7310a367809SOwen Anderson 		B_PRIxADDR ", 0x%" B_PRIxSIZE ", %d, %d)\n", (addr_t)area,
7320a367809SOwen Anderson 		area->name, area->Base(), area->Size(), deletingAddressSpace,
7330a367809SOwen Anderson 		ignoreTopCachePageFlags);
7340a367809SOwen Anderson 
7350a367809SOwen Anderson 	if (area->cache_type == CACHE_TYPE_DEVICE || area->wiring != B_NO_LOCK) {
7360a367809SOwen Anderson 		UnmapPages(area, area->Base(), area->Size(), true);
7370a367809SOwen Anderson 		return;
7380a367809SOwen Anderson 	}
7390a367809SOwen Anderson 
7400a367809SOwen Anderson 	bool unmapPages = !deletingAddressSpace || !ignoreTopCachePageFlags;
7410a367809SOwen Anderson 
7420a367809SOwen Anderson 	RecursiveLocker locker(fLock);
7430a367809SOwen Anderson 	ThreadCPUPinner pinner(thread_get_current_thread());
7440a367809SOwen Anderson 
7450a367809SOwen Anderson 	VMAreaMappings mappings;
7460a367809SOwen Anderson 	mappings.MoveFrom(&area->mappings);
7470a367809SOwen Anderson 
7480a367809SOwen Anderson 	for (VMAreaMappings::Iterator it = mappings.GetIterator();
7490a367809SOwen Anderson 			vm_page_mapping* mapping = it.Next();) {
7500a367809SOwen Anderson 
7510a367809SOwen Anderson 		vm_page* page = mapping->page;
7520a367809SOwen Anderson 		page->mappings.Remove(mapping);
7530a367809SOwen Anderson 
7540a367809SOwen Anderson 		VMCache* cache = page->Cache();
7550a367809SOwen Anderson 
7560a367809SOwen Anderson 		bool pageFullyUnmapped = false;
7570a367809SOwen Anderson 		if (!page->IsMapped()) {
7580a367809SOwen Anderson 			atomic_add(&gMappedPagesCount, -1);
7590a367809SOwen Anderson 			pageFullyUnmapped = true;
7600a367809SOwen Anderson 		}
7610a367809SOwen Anderson 
7620a367809SOwen Anderson 		if (unmapPages || cache != area->cache) {
7630a367809SOwen Anderson 			addr_t address = area->Base()
7640a367809SOwen Anderson 				+ ((page->cache_offset * B_PAGE_SIZE)
7650a367809SOwen Anderson 				- area->cache_offset);
7660a367809SOwen Anderson 
7670a367809SOwen Anderson 			uint64_t oldPte = 0;
768*af5e461fSOwen Anderson 			ProcessRange(fPageTable, fInitialLevel, address, B_PAGE_SIZE, nullptr,
7690a367809SOwen Anderson 				[=, &oldPte](uint64_t* ptePtr, uint64_t effectiveVa) {
7700a367809SOwen Anderson 					oldPte = atomic_get_and_set64((int64_t*)ptePtr, 0);
771129bc12bSOwen Anderson 					if (!deletingAddressSpace)
772129bc12bSOwen Anderson 						FlushVAIfAccessed(oldPte, effectiveVa);
7730a367809SOwen Anderson 				});
7740a367809SOwen Anderson 
7750a367809SOwen Anderson 			if ((oldPte & kPteValidMask) == 0) {
7760a367809SOwen Anderson 				panic("page %p has mapping for area %p "
7770a367809SOwen Anderson 					"(%#" B_PRIxADDR "), but has no "
7780a367809SOwen Anderson 					"page table", page, area, address);
7790a367809SOwen Anderson 				continue;
7800a367809SOwen Anderson 			}
7810a367809SOwen Anderson 
7820a367809SOwen Anderson 			// transfer the accessed/dirty flags to the page and
7830a367809SOwen Anderson 			// invalidate the mapping, if necessary
7840a367809SOwen Anderson 			if (is_pte_dirty(oldPte))
7850a367809SOwen Anderson 				page->modified = true;
7860a367809SOwen Anderson 			if (oldPte & kAttrAF)
7870a367809SOwen Anderson 				page->accessed = true;
7880a367809SOwen Anderson 
7890a367809SOwen Anderson 			if (pageFullyUnmapped) {
7900a367809SOwen Anderson 				DEBUG_PAGE_ACCESS_START(page);
7910a367809SOwen Anderson 
7920a367809SOwen Anderson 				if (cache->temporary) {
7930a367809SOwen Anderson 					vm_page_set_state(page,
7940a367809SOwen Anderson 						PAGE_STATE_INACTIVE);
7950a367809SOwen Anderson 				} else if (page->modified) {
7960a367809SOwen Anderson 					vm_page_set_state(page,
7970a367809SOwen Anderson 						PAGE_STATE_MODIFIED);
7980a367809SOwen Anderson 				} else {
7990a367809SOwen Anderson 					vm_page_set_state(page,
8000a367809SOwen Anderson 						PAGE_STATE_CACHED);
8010a367809SOwen Anderson 				}
8020a367809SOwen Anderson 
8030a367809SOwen Anderson 				DEBUG_PAGE_ACCESS_END(page);
8040a367809SOwen Anderson 			}
8050a367809SOwen Anderson 		}
8060a367809SOwen Anderson 	}
8070a367809SOwen Anderson 
8080a367809SOwen Anderson 	locker.Unlock();
8090a367809SOwen Anderson 
8100a367809SOwen Anderson 	bool isKernelSpace = area->address_space == VMAddressSpace::Kernel();
8110a367809SOwen Anderson 	uint32 freeFlags = CACHE_DONT_WAIT_FOR_MEMORY
8120a367809SOwen Anderson 		| (isKernelSpace ? CACHE_DONT_LOCK_KERNEL_SPACE : 0);
8130a367809SOwen Anderson 
8140a367809SOwen Anderson 	while (vm_page_mapping* mapping = mappings.RemoveHead())
8150a367809SOwen Anderson 		vm_free_page_mapping(mapping->page->physical_page_number, mapping, freeFlags);
8160a367809SOwen Anderson }
8170a367809SOwen Anderson 
8180a367809SOwen Anderson 
819a25542e7Smilek7 bool
820a25542e7Smilek7 VMSAv8TranslationMap::ValidateVa(addr_t va)
821a25542e7Smilek7 {
822a25542e7Smilek7 	uint64_t vaMask = (1UL << fVaBits) - 1;
823a25542e7Smilek7 	bool kernelAddr = (va & (1UL << 63)) != 0;
824a25542e7Smilek7 	if (kernelAddr != fIsKernel)
825a25542e7Smilek7 		return false;
826a25542e7Smilek7 	if ((va & ~vaMask) != (fIsKernel ? ~vaMask : 0))
827a25542e7Smilek7 		return false;
828a25542e7Smilek7 	return true;
829a25542e7Smilek7 }
830a25542e7Smilek7 
831a25542e7Smilek7 
832a25542e7Smilek7 status_t
833a25542e7Smilek7 VMSAv8TranslationMap::Query(addr_t va, phys_addr_t* pa, uint32* flags)
834a25542e7Smilek7 {
83573c51743SOwen Anderson 	*flags = 0;
83673c51743SOwen Anderson 	*pa = 0;
83773c51743SOwen Anderson 
83873c51743SOwen Anderson 	uint64_t pageMask = (1UL << fPageBits) - 1;
839088b72e7SOwen Anderson 	va &= ~pageMask;
840*af5e461fSOwen Anderson 
841*af5e461fSOwen Anderson 	ThreadCPUPinner pinner(thread_get_current_thread());
842a25542e7Smilek7 	ASSERT(ValidateVa(va));
843a25542e7Smilek7 
844*af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, va, B_PAGE_SIZE, nullptr,
84573c51743SOwen Anderson 		[=](uint64_t* ptePtr, uint64_t effectiveVa) {
84673c51743SOwen Anderson 			uint64_t pte = atomic_get64((int64_t*)ptePtr);
84773c51743SOwen Anderson 			*pa = pte & kPteAddrMask;
84873c51743SOwen Anderson 			*flags |= PAGE_PRESENT | B_KERNEL_READ_AREA;
849a25542e7Smilek7 			if ((pte & kAttrAF) != 0)
85073c51743SOwen Anderson 				*flags |= PAGE_ACCESSED;
8516a2e4f41SOwen Anderson 			if (is_pte_dirty(pte))
85273c51743SOwen Anderson 				*flags |= PAGE_MODIFIED;
853a25542e7Smilek7 
854a25542e7Smilek7 			if ((pte & kAttrUXN) == 0)
85573c51743SOwen Anderson 				*flags |= B_EXECUTE_AREA;
856a25542e7Smilek7 			if ((pte & kAttrPXN) == 0)
85773c51743SOwen Anderson 				*flags |= B_KERNEL_EXECUTE_AREA;
858a25542e7Smilek7 
859108f6fdcSOwen Anderson 			if ((pte & kAttrAPUserAccess) != 0)
86073c51743SOwen Anderson 				*flags |= B_READ_AREA;
861a25542e7Smilek7 
8626a2e4f41SOwen Anderson 			if ((pte & kAttrSWDBM) != 0) {
86373c51743SOwen Anderson 				*flags |= B_KERNEL_WRITE_AREA;
864108f6fdcSOwen Anderson 				if ((pte & kAttrAPUserAccess) != 0)
86573c51743SOwen Anderson 					*flags |= B_WRITE_AREA;
866a25542e7Smilek7 			}
86773c51743SOwen Anderson 		});
868a25542e7Smilek7 
869a25542e7Smilek7 	return B_OK;
870a25542e7Smilek7 }
871a25542e7Smilek7 
872a25542e7Smilek7 
873a25542e7Smilek7 status_t
874a25542e7Smilek7 VMSAv8TranslationMap::QueryInterrupt(
875a25542e7Smilek7 	addr_t virtualAddress, phys_addr_t* _physicalAddress, uint32* _flags)
876a25542e7Smilek7 {
877a25542e7Smilek7 	return Query(virtualAddress, _physicalAddress, _flags);
878a25542e7Smilek7 }
879a25542e7Smilek7 
880a25542e7Smilek7 
881a25542e7Smilek7 status_t
882a25542e7Smilek7 VMSAv8TranslationMap::Protect(addr_t start, addr_t end, uint32 attributes, uint32 memoryType)
883a25542e7Smilek7 {
88432c542bdSOwen Anderson 	TRACE("VMSAv8TranslationMap::Protect(0x%" B_PRIxADDR ", 0x%"
88532c542bdSOwen Anderson 		B_PRIxADDR ", 0x%x, 0x%x)\n", start, end, attributes, memoryType);
88632c542bdSOwen Anderson 
887f73ff202SOwen Anderson 	uint64_t attr = GetMemoryAttr(attributes, memoryType, fIsKernel);
888a25542e7Smilek7 	size_t size = end - start + 1;
889a25542e7Smilek7 	ASSERT(ValidateVa(start));
890a25542e7Smilek7 
891*af5e461fSOwen Anderson 	ThreadCPUPinner pinner(thread_get_current_thread());
892*af5e461fSOwen Anderson 
893*af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, start, size, nullptr,
894f73ff202SOwen Anderson 		[=](uint64_t* ptePtr, uint64_t effectiveVa) {
895f73ff202SOwen Anderson 			// We need to use an atomic compare-swap loop because we must
896f73ff202SOwen Anderson 			// need to clear somes bits while setting others.
897f73ff202SOwen Anderson 			while (true) {
898f73ff202SOwen Anderson 				uint64_t oldPte = atomic_get64((int64_t*)ptePtr);
899f73ff202SOwen Anderson 				uint64_t newPte = oldPte & ~kPteAttrMask;
900f73ff202SOwen Anderson 				newPte |= attr;
901f73ff202SOwen Anderson 
9024bb796cfSOwen Anderson 				// Preserve access bit.
9034bb796cfSOwen Anderson 				newPte |= oldPte & kAttrAF;
9044bb796cfSOwen Anderson 
9056a2e4f41SOwen Anderson 				// Preserve the dirty bit.
9066a2e4f41SOwen Anderson 				if (is_pte_dirty(oldPte))
9076a2e4f41SOwen Anderson 					newPte = set_pte_dirty(newPte);
9084bb796cfSOwen Anderson 
9094bb796cfSOwen Anderson 				uint64_t oldMemoryType = oldPte & (kAttrShareability | kAttrMemoryAttrIdx);
9104bb796cfSOwen Anderson 				uint64_t newMemoryType = newPte & (kAttrShareability | kAttrMemoryAttrIdx);
9114bb796cfSOwen Anderson 				if (oldMemoryType != newMemoryType) {
9124bb796cfSOwen Anderson 					// ARM64 requires "break-before-make". We must set the PTE to an invalid
9134bb796cfSOwen Anderson 					// entry and flush the TLB as appropriate before we can write the new PTE.
9144bb796cfSOwen Anderson 					// In this case specifically, it applies any time we change cacheability or
9154bb796cfSOwen Anderson 					// shareability.
916129bc12bSOwen Anderson 					if (!AttemptPteBreakBeforeMake(ptePtr, oldPte, effectiveVa))
9174bb796cfSOwen Anderson 						continue;
9184bb796cfSOwen Anderson 
9194bb796cfSOwen Anderson 					atomic_set64((int64_t*)ptePtr, newPte);
9204bb796cfSOwen Anderson 					asm("dsb ishst"); // Ensure PTE write completed
921129bc12bSOwen Anderson 					asm("isb");
9224bb796cfSOwen Anderson 
9234bb796cfSOwen Anderson 					// No compare-exchange loop required in this case.
9244bb796cfSOwen Anderson 					break;
9254bb796cfSOwen Anderson 				} else {
926f73ff202SOwen Anderson 					if ((uint64_t)atomic_test_and_set64((int64_t*)ptePtr, newPte, oldPte) == oldPte) {
927129bc12bSOwen Anderson 						FlushVAIfAccessed(oldPte, effectiveVa);
928f73ff202SOwen Anderson 						break;
929f73ff202SOwen Anderson 					}
930f73ff202SOwen Anderson 				}
9314bb796cfSOwen Anderson 			}
932f73ff202SOwen Anderson 		});
933a25542e7Smilek7 
934a25542e7Smilek7 	return B_OK;
935a25542e7Smilek7 }
936a25542e7Smilek7 
937a25542e7Smilek7 
938a25542e7Smilek7 status_t
939a25542e7Smilek7 VMSAv8TranslationMap::ClearFlags(addr_t va, uint32 flags)
940a25542e7Smilek7 {
941a25542e7Smilek7 	ASSERT(ValidateVa(va));
942a25542e7Smilek7 
9434bb796cfSOwen Anderson 	bool clearAF = flags & PAGE_ACCESSED;
9444bb796cfSOwen Anderson 	bool setRO = flags & PAGE_MODIFIED;
945a25542e7Smilek7 
946744bdd73SOwen Anderson 	if (!clearAF && !setRO)
947744bdd73SOwen Anderson 		return B_OK;
948744bdd73SOwen Anderson 
949*af5e461fSOwen Anderson 	ThreadCPUPinner pinner(thread_get_current_thread());
950*af5e461fSOwen Anderson 
951129bc12bSOwen Anderson 	uint64_t oldPte = 0;
952*af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, va, B_PAGE_SIZE, nullptr,
953129bc12bSOwen Anderson 		[=, &oldPte](uint64_t* ptePtr, uint64_t effectiveVa) {
954744bdd73SOwen Anderson 			if (clearAF && setRO) {
955744bdd73SOwen Anderson 				// We need to use an atomic compare-swap loop because we must
956744bdd73SOwen Anderson 				// need to clear one bit while setting the other.
957744bdd73SOwen Anderson 				while (true) {
958129bc12bSOwen Anderson 					oldPte = atomic_get64((int64_t*)ptePtr);
959744bdd73SOwen Anderson 					uint64_t newPte = oldPte & ~kAttrAF;
9606a2e4f41SOwen Anderson 					newPte = set_pte_clean(newPte);
961744bdd73SOwen Anderson 
962744bdd73SOwen Anderson                     if ((uint64_t)atomic_test_and_set64((int64_t*)ptePtr, newPte, oldPte) == oldPte)
963744bdd73SOwen Anderson 						break;
964744bdd73SOwen Anderson 				}
965744bdd73SOwen Anderson 			} else if (clearAF) {
966129bc12bSOwen Anderson 				oldPte = atomic_and64((int64_t*)ptePtr, ~kAttrAF);
967744bdd73SOwen Anderson 			} else {
9686a2e4f41SOwen Anderson 				while (true) {
969129bc12bSOwen Anderson 					oldPte = atomic_get64((int64_t*)ptePtr);
970129bc12bSOwen Anderson 					if (!is_pte_dirty(oldPte)) {
971129bc12bSOwen Anderson 						// Avoid a TLB flush
972129bc12bSOwen Anderson 						oldPte = 0;
9736a2e4f41SOwen Anderson 						return;
974129bc12bSOwen Anderson 					}
9756a2e4f41SOwen Anderson 					uint64_t newPte = set_pte_clean(oldPte);
9766a2e4f41SOwen Anderson                     if ((uint64_t)atomic_test_and_set64((int64_t*)ptePtr, newPte, oldPte) == oldPte)
9776a2e4f41SOwen Anderson 						break;
9786a2e4f41SOwen Anderson 				}
979744bdd73SOwen Anderson 			}
980744bdd73SOwen Anderson 		});
981744bdd73SOwen Anderson 
982129bc12bSOwen Anderson 	FlushVAIfAccessed(oldPte, va);
983129bc12bSOwen Anderson 
984a25542e7Smilek7 	return B_OK;
985a25542e7Smilek7 }
986a25542e7Smilek7 
987a25542e7Smilek7 
988a25542e7Smilek7 bool
989a25542e7Smilek7 VMSAv8TranslationMap::ClearAccessedAndModified(
990a25542e7Smilek7 	VMArea* area, addr_t address, bool unmapIfUnaccessed, bool& _modified)
991a25542e7Smilek7 {
99232c542bdSOwen Anderson 	TRACE("VMSAv8TranslationMap::ClearAccessedAndModified(0x%"
99332c542bdSOwen Anderson 		B_PRIxADDR "(%s), 0x%" B_PRIxADDR ", %d)\n", (addr_t)area,
99432c542bdSOwen Anderson 		area->name, address, unmapIfUnaccessed);
995*af5e461fSOwen Anderson 	ASSERT(ValidateVa(address));
99632c542bdSOwen Anderson 
997bb67bf75SOwen Anderson 	RecursiveLocker locker(fLock);
998bb67bf75SOwen Anderson 	ThreadCPUPinner pinner(thread_get_current_thread());
999bb67bf75SOwen Anderson 
1000bb67bf75SOwen Anderson 	uint64_t oldPte = 0;
1001*af5e461fSOwen Anderson 	ProcessRange(fPageTable, fInitialLevel, address, B_PAGE_SIZE, nullptr,
10024bb796cfSOwen Anderson 		[=, &oldPte](uint64_t* ptePtr, uint64_t effectiveVa) {
1003bb67bf75SOwen Anderson 			// We need to use an atomic compare-swap loop because we must
1004bb67bf75SOwen Anderson 			// first read the old PTE and make decisions based on the AF
1005bb67bf75SOwen Anderson 			// bit to proceed.
1006bb67bf75SOwen Anderson 			while (true) {
1007bb67bf75SOwen Anderson 				oldPte = atomic_get64((int64_t*)ptePtr);
1008bb67bf75SOwen Anderson 				uint64_t newPte = oldPte & ~kAttrAF;
10096a2e4f41SOwen Anderson 				newPte = set_pte_clean(newPte);
1010bb67bf75SOwen Anderson 
1011bb67bf75SOwen Anderson 				// If the page has been not be accessed, then unmap it.
1012bb67bf75SOwen Anderson 				if (unmapIfUnaccessed && (oldPte & kAttrAF) == 0)
1013bb67bf75SOwen Anderson 					newPte = 0;
1014bb67bf75SOwen Anderson 
1015bb67bf75SOwen Anderson 				if ((uint64_t)atomic_test_and_set64((int64_t*)ptePtr, newPte, oldPte) == oldPte)
1016bb67bf75SOwen Anderson 					break;
1017bb67bf75SOwen Anderson 			}
1018bb67bf75SOwen Anderson 			asm("dsb ishst"); // Ensure PTE write completed
1019bb67bf75SOwen Anderson 		});
1020bb67bf75SOwen Anderson 
1021bb67bf75SOwen Anderson 	pinner.Unlock();
10226a2e4f41SOwen Anderson 	_modified = is_pte_dirty(oldPte);
1023129bc12bSOwen Anderson 
1024129bc12bSOwen Anderson 	if (FlushVAIfAccessed(oldPte, address))
1025bb67bf75SOwen Anderson 		return true;
1026bb67bf75SOwen Anderson 
1027bb67bf75SOwen Anderson 	if (!unmapIfUnaccessed)
1028bb67bf75SOwen Anderson 		return false;
1029bb67bf75SOwen Anderson 
1030bb67bf75SOwen Anderson 	locker.Detach(); // UnaccessedPageUnmapped takes ownership
1031bb67bf75SOwen Anderson 	phys_addr_t oldPa = oldPte & kPteAddrMask;
1032bb67bf75SOwen Anderson 	UnaccessedPageUnmapped(area, oldPa >> fPageBits);
1033bb67bf75SOwen Anderson 	return false;
1034a25542e7Smilek7 }
1035a25542e7Smilek7 
1036a25542e7Smilek7 
1037a25542e7Smilek7 void
1038a25542e7Smilek7 VMSAv8TranslationMap::Flush()
1039a25542e7Smilek7 {
1040a25542e7Smilek7 	ThreadCPUPinner pinner(thread_get_current_thread());
1041a25542e7Smilek7 
1042a25542e7Smilek7 	arch_cpu_global_TLB_invalidate();
1043a25542e7Smilek7 }
1044