memory.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. // SPDX-FileCopyrightText: 2015 Citra Emulator Project
  2. // SPDX-FileCopyrightText: 2018 yuzu Emulator Project
  3. // SPDX-License-Identifier: GPL-2.0-or-later
  4. #include <algorithm>
  5. #include <cstring>
  6. #include <mutex>
  7. #include <span>
  8. #include "common/assert.h"
  9. #include "common/atomic_ops.h"
  10. #include "common/common_types.h"
  11. #include "common/heap_tracker.h"
  12. #include "common/logging/log.h"
  13. #include "common/page_table.h"
  14. #include "common/scope_exit.h"
  15. #include "common/settings.h"
  16. #include "common/swap.h"
  17. #include "core/core.h"
  18. #include "core/device_memory.h"
  19. #include "core/gpu_dirty_memory_manager.h"
  20. #include "core/hardware_properties.h"
  21. #include "core/hle/kernel/k_page_table.h"
  22. #include "core/hle/kernel/k_process.h"
  23. #include "core/memory.h"
  24. #include "video_core/gpu.h"
  25. #include "video_core/rasterizer_download_area.h"
  26. namespace Core::Memory {
  27. namespace {
  28. bool AddressSpaceContains(const Common::PageTable& table, const Common::ProcessAddress addr,
  29. const std::size_t size) {
  30. const Common::ProcessAddress max_addr = 1ULL << table.GetAddressSpaceBits();
  31. return addr + size >= addr && addr + size <= max_addr;
  32. }
  33. } // namespace
  34. // Implementation class used to keep the specifics of the memory subsystem hidden
  35. // from outside classes. This also allows modification to the internals of the memory
  36. // subsystem without needing to rebuild all files that make use of the memory interface.
  37. struct Memory::Impl {
  38. explicit Impl(Core::System& system_) : system{system_} {}
  39. void SetCurrentPageTable(Kernel::KProcess& process) {
  40. current_page_table = &process.GetPageTable().GetImpl();
  41. if (std::addressof(process) == system.ApplicationProcess() &&
  42. Settings::IsFastmemEnabled()) {
  43. current_page_table->fastmem_arena = system.DeviceMemory().buffer.VirtualBasePointer();
  44. } else {
  45. current_page_table->fastmem_arena = nullptr;
  46. }
  47. #ifdef __linux__
  48. heap_tracker.emplace(system.DeviceMemory().buffer);
  49. buffer = std::addressof(*heap_tracker);
  50. #else
  51. buffer = std::addressof(system.DeviceMemory().buffer);
  52. #endif
  53. }
  54. void MapMemoryRegion(Common::PageTable& page_table, Common::ProcessAddress base, u64 size,
  55. Common::PhysicalAddress target, Common::MemoryPermission perms,
  56. bool separate_heap) {
  57. ASSERT_MSG((size & YUZU_PAGEMASK) == 0, "non-page aligned size: {:016X}", size);
  58. ASSERT_MSG((base & YUZU_PAGEMASK) == 0, "non-page aligned base: {:016X}", GetInteger(base));
  59. ASSERT_MSG(target >= DramMemoryMap::Base, "Out of bounds target: {:016X}",
  60. GetInteger(target));
  61. MapPages(page_table, base / YUZU_PAGESIZE, size / YUZU_PAGESIZE, target,
  62. Common::PageType::Memory);
  63. if (current_page_table->fastmem_arena) {
  64. buffer->Map(GetInteger(base), GetInteger(target) - DramMemoryMap::Base, size, perms,
  65. separate_heap);
  66. }
  67. }
  68. void UnmapRegion(Common::PageTable& page_table, Common::ProcessAddress base, u64 size,
  69. bool separate_heap) {
  70. ASSERT_MSG((size & YUZU_PAGEMASK) == 0, "non-page aligned size: {:016X}", size);
  71. ASSERT_MSG((base & YUZU_PAGEMASK) == 0, "non-page aligned base: {:016X}", GetInteger(base));
  72. MapPages(page_table, base / YUZU_PAGESIZE, size / YUZU_PAGESIZE, 0,
  73. Common::PageType::Unmapped);
  74. if (current_page_table->fastmem_arena) {
  75. buffer->Unmap(GetInteger(base), size, separate_heap);
  76. }
  77. }
  78. void ProtectRegion(Common::PageTable& page_table, VAddr vaddr, u64 size,
  79. Common::MemoryPermission perms) {
  80. ASSERT_MSG((size & YUZU_PAGEMASK) == 0, "non-page aligned size: {:016X}", size);
  81. ASSERT_MSG((vaddr & YUZU_PAGEMASK) == 0, "non-page aligned base: {:016X}", vaddr);
  82. if (!current_page_table->fastmem_arena) {
  83. return;
  84. }
  85. u64 protect_bytes{};
  86. u64 protect_begin{};
  87. for (u64 addr = vaddr; addr < vaddr + size; addr += YUZU_PAGESIZE) {
  88. const Common::PageType page_type{
  89. current_page_table->pointers[addr >> YUZU_PAGEBITS].Type()};
  90. switch (page_type) {
  91. case Common::PageType::RasterizerCachedMemory:
  92. if (protect_bytes > 0) {
  93. buffer->Protect(protect_begin, protect_bytes, perms);
  94. protect_bytes = 0;
  95. }
  96. break;
  97. default:
  98. if (protect_bytes == 0) {
  99. protect_begin = addr;
  100. }
  101. protect_bytes += YUZU_PAGESIZE;
  102. }
  103. }
  104. if (protect_bytes > 0) {
  105. buffer->Protect(protect_begin, protect_bytes, perms);
  106. }
  107. }
  108. [[nodiscard]] u8* GetPointerFromRasterizerCachedMemory(u64 vaddr) const {
  109. const Common::PhysicalAddress paddr{
  110. current_page_table->backing_addr[vaddr >> YUZU_PAGEBITS]};
  111. if (!paddr) {
  112. return {};
  113. }
  114. return system.DeviceMemory().GetPointer<u8>(paddr + vaddr);
  115. }
  116. [[nodiscard]] u8* GetPointerFromDebugMemory(u64 vaddr) const {
  117. const Common::PhysicalAddress paddr{
  118. current_page_table->backing_addr[vaddr >> YUZU_PAGEBITS]};
  119. if (paddr == 0) {
  120. return {};
  121. }
  122. return system.DeviceMemory().GetPointer<u8>(paddr + vaddr);
  123. }
  124. u8 Read8(const Common::ProcessAddress addr) {
  125. return Read<u8>(addr);
  126. }
  127. u16 Read16(const Common::ProcessAddress addr) {
  128. if ((addr & 1) == 0) {
  129. return Read<u16_le>(addr);
  130. } else {
  131. const u32 a{Read<u8>(addr)};
  132. const u32 b{Read<u8>(addr + sizeof(u8))};
  133. return static_cast<u16>((b << 8) | a);
  134. }
  135. }
  136. u32 Read32(const Common::ProcessAddress addr) {
  137. if ((addr & 3) == 0) {
  138. return Read<u32_le>(addr);
  139. } else {
  140. const u32 a{Read16(addr)};
  141. const u32 b{Read16(addr + sizeof(u16))};
  142. return (b << 16) | a;
  143. }
  144. }
  145. u64 Read64(const Common::ProcessAddress addr) {
  146. if ((addr & 7) == 0) {
  147. return Read<u64_le>(addr);
  148. } else {
  149. const u32 a{Read32(addr)};
  150. const u32 b{Read32(addr + sizeof(u32))};
  151. return (static_cast<u64>(b) << 32) | a;
  152. }
  153. }
  154. void Write8(const Common::ProcessAddress addr, const u8 data) {
  155. Write<u8>(addr, data);
  156. }
  157. void Write16(const Common::ProcessAddress addr, const u16 data) {
  158. if ((addr & 1) == 0) {
  159. Write<u16_le>(addr, data);
  160. } else {
  161. Write<u8>(addr, static_cast<u8>(data));
  162. Write<u8>(addr + sizeof(u8), static_cast<u8>(data >> 8));
  163. }
  164. }
  165. void Write32(const Common::ProcessAddress addr, const u32 data) {
  166. if ((addr & 3) == 0) {
  167. Write<u32_le>(addr, data);
  168. } else {
  169. Write16(addr, static_cast<u16>(data));
  170. Write16(addr + sizeof(u16), static_cast<u16>(data >> 16));
  171. }
  172. }
  173. void Write64(const Common::ProcessAddress addr, const u64 data) {
  174. if ((addr & 7) == 0) {
  175. Write<u64_le>(addr, data);
  176. } else {
  177. Write32(addr, static_cast<u32>(data));
  178. Write32(addr + sizeof(u32), static_cast<u32>(data >> 32));
  179. }
  180. }
  181. bool WriteExclusive8(const Common::ProcessAddress addr, const u8 data, const u8 expected) {
  182. return WriteExclusive<u8>(addr, data, expected);
  183. }
  184. bool WriteExclusive16(const Common::ProcessAddress addr, const u16 data, const u16 expected) {
  185. return WriteExclusive<u16_le>(addr, data, expected);
  186. }
  187. bool WriteExclusive32(const Common::ProcessAddress addr, const u32 data, const u32 expected) {
  188. return WriteExclusive<u32_le>(addr, data, expected);
  189. }
  190. bool WriteExclusive64(const Common::ProcessAddress addr, const u64 data, const u64 expected) {
  191. return WriteExclusive<u64_le>(addr, data, expected);
  192. }
  193. std::string ReadCString(Common::ProcessAddress vaddr, std::size_t max_length) {
  194. std::string string;
  195. string.reserve(max_length);
  196. for (std::size_t i = 0; i < max_length; ++i) {
  197. const char c = Read<s8>(vaddr);
  198. if (c == '\0') {
  199. break;
  200. }
  201. string.push_back(c);
  202. ++vaddr;
  203. }
  204. string.shrink_to_fit();
  205. return string;
  206. }
  207. bool WalkBlock(const Common::ProcessAddress addr, const std::size_t size, auto on_unmapped,
  208. auto on_memory, auto on_rasterizer, auto increment) {
  209. const auto& page_table = *current_page_table;
  210. std::size_t remaining_size = size;
  211. std::size_t page_index = addr >> YUZU_PAGEBITS;
  212. std::size_t page_offset = addr & YUZU_PAGEMASK;
  213. bool user_accessible = true;
  214. if (!AddressSpaceContains(page_table, addr, size)) [[unlikely]] {
  215. on_unmapped(size, addr);
  216. return false;
  217. }
  218. while (remaining_size) {
  219. const std::size_t copy_amount =
  220. std::min(static_cast<std::size_t>(YUZU_PAGESIZE) - page_offset, remaining_size);
  221. const auto current_vaddr =
  222. static_cast<u64>((page_index << YUZU_PAGEBITS) + page_offset);
  223. const auto [pointer, type] = page_table.pointers[page_index].PointerType();
  224. switch (type) {
  225. case Common::PageType::Unmapped: {
  226. user_accessible = false;
  227. on_unmapped(copy_amount, current_vaddr);
  228. break;
  229. }
  230. case Common::PageType::Memory: {
  231. u8* mem_ptr =
  232. reinterpret_cast<u8*>(pointer + page_offset + (page_index << YUZU_PAGEBITS));
  233. on_memory(copy_amount, mem_ptr);
  234. break;
  235. }
  236. case Common::PageType::DebugMemory: {
  237. u8* const mem_ptr{GetPointerFromDebugMemory(current_vaddr)};
  238. on_memory(copy_amount, mem_ptr);
  239. break;
  240. }
  241. case Common::PageType::RasterizerCachedMemory: {
  242. u8* const host_ptr{GetPointerFromRasterizerCachedMemory(current_vaddr)};
  243. on_rasterizer(current_vaddr, copy_amount, host_ptr);
  244. break;
  245. }
  246. default:
  247. UNREACHABLE();
  248. }
  249. page_index++;
  250. page_offset = 0;
  251. increment(copy_amount);
  252. remaining_size -= copy_amount;
  253. }
  254. return user_accessible;
  255. }
  256. template <bool UNSAFE>
  257. bool ReadBlockImpl(const Common::ProcessAddress src_addr, void* dest_buffer,
  258. const std::size_t size) {
  259. return WalkBlock(
  260. src_addr, size,
  261. [src_addr, size, &dest_buffer](const std::size_t copy_amount,
  262. const Common::ProcessAddress current_vaddr) {
  263. LOG_ERROR(HW_Memory,
  264. "Unmapped ReadBlock @ 0x{:016X} (start address = 0x{:016X}, size = {})",
  265. GetInteger(current_vaddr), GetInteger(src_addr), size);
  266. std::memset(dest_buffer, 0, copy_amount);
  267. },
  268. [&](const std::size_t copy_amount, const u8* const src_ptr) {
  269. std::memcpy(dest_buffer, src_ptr, copy_amount);
  270. },
  271. [&](const Common::ProcessAddress current_vaddr, const std::size_t copy_amount,
  272. const u8* const host_ptr) {
  273. if constexpr (!UNSAFE) {
  274. HandleRasterizerDownload(GetInteger(current_vaddr), copy_amount);
  275. }
  276. std::memcpy(dest_buffer, host_ptr, copy_amount);
  277. },
  278. [&](const std::size_t copy_amount) {
  279. dest_buffer = static_cast<u8*>(dest_buffer) + copy_amount;
  280. });
  281. }
  282. bool ReadBlock(const Common::ProcessAddress src_addr, void* dest_buffer,
  283. const std::size_t size) {
  284. return ReadBlockImpl<false>(src_addr, dest_buffer, size);
  285. }
  286. bool ReadBlockUnsafe(const Common::ProcessAddress src_addr, void* dest_buffer,
  287. const std::size_t size) {
  288. return ReadBlockImpl<true>(src_addr, dest_buffer, size);
  289. }
  290. const u8* GetSpan(const VAddr src_addr, const std::size_t size) const {
  291. if (current_page_table->blocks[src_addr >> YUZU_PAGEBITS] ==
  292. current_page_table->blocks[(src_addr + size) >> YUZU_PAGEBITS]) {
  293. return GetPointerSilent(src_addr);
  294. }
  295. return nullptr;
  296. }
  297. u8* GetSpan(const VAddr src_addr, const std::size_t size) {
  298. if (current_page_table->blocks[src_addr >> YUZU_PAGEBITS] ==
  299. current_page_table->blocks[(src_addr + size) >> YUZU_PAGEBITS]) {
  300. return GetPointerSilent(src_addr);
  301. }
  302. return nullptr;
  303. }
  304. template <bool UNSAFE>
  305. bool WriteBlockImpl(const Common::ProcessAddress dest_addr, const void* src_buffer,
  306. const std::size_t size) {
  307. return WalkBlock(
  308. dest_addr, size,
  309. [dest_addr, size](const std::size_t copy_amount,
  310. const Common::ProcessAddress current_vaddr) {
  311. LOG_ERROR(HW_Memory,
  312. "Unmapped WriteBlock @ 0x{:016X} (start address = 0x{:016X}, size = {})",
  313. GetInteger(current_vaddr), GetInteger(dest_addr), size);
  314. },
  315. [&](const std::size_t copy_amount, u8* const dest_ptr) {
  316. std::memcpy(dest_ptr, src_buffer, copy_amount);
  317. },
  318. [&](const Common::ProcessAddress current_vaddr, const std::size_t copy_amount,
  319. u8* const host_ptr) {
  320. if constexpr (!UNSAFE) {
  321. HandleRasterizerWrite(GetInteger(current_vaddr), copy_amount);
  322. }
  323. std::memcpy(host_ptr, src_buffer, copy_amount);
  324. },
  325. [&](const std::size_t copy_amount) {
  326. src_buffer = static_cast<const u8*>(src_buffer) + copy_amount;
  327. });
  328. }
  329. bool WriteBlock(const Common::ProcessAddress dest_addr, const void* src_buffer,
  330. const std::size_t size) {
  331. return WriteBlockImpl<false>(dest_addr, src_buffer, size);
  332. }
  333. bool WriteBlockUnsafe(const Common::ProcessAddress dest_addr, const void* src_buffer,
  334. const std::size_t size) {
  335. return WriteBlockImpl<true>(dest_addr, src_buffer, size);
  336. }
  337. bool ZeroBlock(const Common::ProcessAddress dest_addr, const std::size_t size) {
  338. return WalkBlock(
  339. dest_addr, size,
  340. [dest_addr, size](const std::size_t copy_amount,
  341. const Common::ProcessAddress current_vaddr) {
  342. LOG_ERROR(HW_Memory,
  343. "Unmapped ZeroBlock @ 0x{:016X} (start address = 0x{:016X}, size = {})",
  344. GetInteger(current_vaddr), GetInteger(dest_addr), size);
  345. },
  346. [](const std::size_t copy_amount, u8* const dest_ptr) {
  347. std::memset(dest_ptr, 0, copy_amount);
  348. },
  349. [&](const Common::ProcessAddress current_vaddr, const std::size_t copy_amount,
  350. u8* const host_ptr) {
  351. HandleRasterizerWrite(GetInteger(current_vaddr), copy_amount);
  352. std::memset(host_ptr, 0, copy_amount);
  353. },
  354. [](const std::size_t copy_amount) {});
  355. }
  356. bool CopyBlock(Common::ProcessAddress dest_addr, Common::ProcessAddress src_addr,
  357. const std::size_t size) {
  358. return WalkBlock(
  359. dest_addr, size,
  360. [&](const std::size_t copy_amount, const Common::ProcessAddress current_vaddr) {
  361. LOG_ERROR(HW_Memory,
  362. "Unmapped CopyBlock @ 0x{:016X} (start address = 0x{:016X}, size = {})",
  363. GetInteger(current_vaddr), GetInteger(src_addr), size);
  364. ZeroBlock(dest_addr, copy_amount);
  365. },
  366. [&](const std::size_t copy_amount, const u8* const src_ptr) {
  367. WriteBlockImpl<false>(dest_addr, src_ptr, copy_amount);
  368. },
  369. [&](const Common::ProcessAddress current_vaddr, const std::size_t copy_amount,
  370. u8* const host_ptr) {
  371. HandleRasterizerDownload(GetInteger(current_vaddr), copy_amount);
  372. WriteBlockImpl<false>(dest_addr, host_ptr, copy_amount);
  373. },
  374. [&](const std::size_t copy_amount) {
  375. dest_addr += copy_amount;
  376. src_addr += copy_amount;
  377. });
  378. }
  379. template <typename Callback>
  380. Result PerformCacheOperation(Common::ProcessAddress dest_addr, std::size_t size,
  381. Callback&& cb) {
  382. class InvalidMemoryException : public std::exception {};
  383. try {
  384. WalkBlock(
  385. dest_addr, size,
  386. [&](const std::size_t block_size, const Common::ProcessAddress current_vaddr) {
  387. LOG_ERROR(HW_Memory, "Unmapped cache maintenance @ {:#018X}",
  388. GetInteger(current_vaddr));
  389. throw InvalidMemoryException();
  390. },
  391. [&](const std::size_t block_size, u8* const host_ptr) {},
  392. [&](const Common::ProcessAddress current_vaddr, const std::size_t block_size,
  393. u8* const host_ptr) { cb(current_vaddr, block_size); },
  394. [](const std::size_t block_size) {});
  395. } catch (InvalidMemoryException&) {
  396. return Kernel::ResultInvalidCurrentMemory;
  397. }
  398. return ResultSuccess;
  399. }
  400. Result InvalidateDataCache(Common::ProcessAddress dest_addr, std::size_t size) {
  401. auto on_rasterizer = [&](const Common::ProcessAddress current_vaddr,
  402. const std::size_t block_size) {
  403. // dc ivac: Invalidate to point of coherency
  404. // GPU flush -> CPU invalidate
  405. HandleRasterizerDownload(GetInteger(current_vaddr), block_size);
  406. };
  407. return PerformCacheOperation(dest_addr, size, on_rasterizer);
  408. }
  409. Result StoreDataCache(Common::ProcessAddress dest_addr, std::size_t size) {
  410. auto on_rasterizer = [&](const Common::ProcessAddress current_vaddr,
  411. const std::size_t block_size) {
  412. // dc cvac: Store to point of coherency
  413. // CPU flush -> GPU invalidate
  414. HandleRasterizerWrite(GetInteger(current_vaddr), block_size);
  415. };
  416. return PerformCacheOperation(dest_addr, size, on_rasterizer);
  417. }
  418. Result FlushDataCache(Common::ProcessAddress dest_addr, std::size_t size) {
  419. auto on_rasterizer = [&](const Common::ProcessAddress current_vaddr,
  420. const std::size_t block_size) {
  421. // dc civac: Store to point of coherency, and invalidate from cache
  422. // CPU flush -> GPU invalidate
  423. HandleRasterizerWrite(GetInteger(current_vaddr), block_size);
  424. };
  425. return PerformCacheOperation(dest_addr, size, on_rasterizer);
  426. }
  427. void MarkRegionDebug(u64 vaddr, u64 size, bool debug) {
  428. if (vaddr == 0 || !AddressSpaceContains(*current_page_table, vaddr, size)) {
  429. return;
  430. }
  431. if (current_page_table->fastmem_arena) {
  432. const auto perm{debug ? Common::MemoryPermission{}
  433. : Common::MemoryPermission::ReadWrite};
  434. buffer->Protect(vaddr, size, perm);
  435. }
  436. // Iterate over a contiguous CPU address space, marking/unmarking the region.
  437. // The region is at a granularity of CPU pages.
  438. const u64 num_pages = ((vaddr + size - 1) >> YUZU_PAGEBITS) - (vaddr >> YUZU_PAGEBITS) + 1;
  439. for (u64 i = 0; i < num_pages; ++i, vaddr += YUZU_PAGESIZE) {
  440. const Common::PageType page_type{
  441. current_page_table->pointers[vaddr >> YUZU_PAGEBITS].Type()};
  442. if (debug) {
  443. // Switch page type to debug if now debug
  444. switch (page_type) {
  445. case Common::PageType::Unmapped:
  446. ASSERT_MSG(false, "Attempted to mark unmapped pages as debug");
  447. break;
  448. case Common::PageType::RasterizerCachedMemory:
  449. case Common::PageType::DebugMemory:
  450. // Page is already marked.
  451. break;
  452. case Common::PageType::Memory:
  453. current_page_table->pointers[vaddr >> YUZU_PAGEBITS].Store(
  454. 0, Common::PageType::DebugMemory);
  455. break;
  456. default:
  457. UNREACHABLE();
  458. }
  459. } else {
  460. // Switch page type to non-debug if now non-debug
  461. switch (page_type) {
  462. case Common::PageType::Unmapped:
  463. ASSERT_MSG(false, "Attempted to mark unmapped pages as non-debug");
  464. break;
  465. case Common::PageType::RasterizerCachedMemory:
  466. case Common::PageType::Memory:
  467. // Don't mess with already non-debug or rasterizer memory.
  468. break;
  469. case Common::PageType::DebugMemory: {
  470. u8* const pointer{GetPointerFromDebugMemory(vaddr & ~YUZU_PAGEMASK)};
  471. current_page_table->pointers[vaddr >> YUZU_PAGEBITS].Store(
  472. reinterpret_cast<uintptr_t>(pointer) - (vaddr & ~YUZU_PAGEMASK),
  473. Common::PageType::Memory);
  474. break;
  475. }
  476. default:
  477. UNREACHABLE();
  478. }
  479. }
  480. }
  481. }
  482. void RasterizerMarkRegionCached(u64 vaddr, u64 size, bool cached) {
  483. if (vaddr == 0 || !AddressSpaceContains(*current_page_table, vaddr, size)) {
  484. return;
  485. }
  486. if (current_page_table->fastmem_arena) {
  487. Common::MemoryPermission perm{};
  488. if (!Settings::values.use_reactive_flushing.GetValue() || !cached) {
  489. perm |= Common::MemoryPermission::Read;
  490. }
  491. if (!cached) {
  492. perm |= Common::MemoryPermission::Write;
  493. }
  494. buffer->Protect(vaddr, size, perm);
  495. }
  496. // Iterate over a contiguous CPU address space, which corresponds to the specified GPU
  497. // address space, marking the region as un/cached. The region is marked un/cached at a
  498. // granularity of CPU pages, hence why we iterate on a CPU page basis (note: GPU page size
  499. // is different). This assumes the specified GPU address region is contiguous as well.
  500. const u64 num_pages = ((vaddr + size - 1) >> YUZU_PAGEBITS) - (vaddr >> YUZU_PAGEBITS) + 1;
  501. for (u64 i = 0; i < num_pages; ++i, vaddr += YUZU_PAGESIZE) {
  502. const Common::PageType page_type{
  503. current_page_table->pointers[vaddr >> YUZU_PAGEBITS].Type()};
  504. if (cached) {
  505. // Switch page type to cached if now cached
  506. switch (page_type) {
  507. case Common::PageType::Unmapped:
  508. // It is not necessary for a process to have this region mapped into its address
  509. // space, for example, a system module need not have a VRAM mapping.
  510. break;
  511. case Common::PageType::DebugMemory:
  512. case Common::PageType::Memory:
  513. current_page_table->pointers[vaddr >> YUZU_PAGEBITS].Store(
  514. 0, Common::PageType::RasterizerCachedMemory);
  515. break;
  516. case Common::PageType::RasterizerCachedMemory:
  517. // There can be more than one GPU region mapped per CPU region, so it's common
  518. // that this area is already marked as cached.
  519. break;
  520. default:
  521. UNREACHABLE();
  522. }
  523. } else {
  524. // Switch page type to uncached if now uncached
  525. switch (page_type) {
  526. case Common::PageType::Unmapped: // NOLINT(bugprone-branch-clone)
  527. // It is not necessary for a process to have this region mapped into its address
  528. // space, for example, a system module need not have a VRAM mapping.
  529. break;
  530. case Common::PageType::DebugMemory:
  531. case Common::PageType::Memory:
  532. // There can be more than one GPU region mapped per CPU region, so it's common
  533. // that this area is already unmarked as cached.
  534. break;
  535. case Common::PageType::RasterizerCachedMemory: {
  536. u8* const pointer{GetPointerFromRasterizerCachedMemory(vaddr & ~YUZU_PAGEMASK)};
  537. if (pointer == nullptr) {
  538. // It's possible that this function has been called while updating the
  539. // pagetable after unmapping a VMA. In that case the underlying VMA will no
  540. // longer exist, and we should just leave the pagetable entry blank.
  541. current_page_table->pointers[vaddr >> YUZU_PAGEBITS].Store(
  542. 0, Common::PageType::Unmapped);
  543. } else {
  544. current_page_table->pointers[vaddr >> YUZU_PAGEBITS].Store(
  545. reinterpret_cast<uintptr_t>(pointer) - (vaddr & ~YUZU_PAGEMASK),
  546. Common::PageType::Memory);
  547. }
  548. break;
  549. }
  550. default:
  551. UNREACHABLE();
  552. }
  553. }
  554. }
  555. }
  556. /**
  557. * Maps a region of pages as a specific type.
  558. *
  559. * @param page_table The page table to use to perform the mapping.
  560. * @param base The base address to begin mapping at.
  561. * @param size The total size of the range in bytes.
  562. * @param target The target address to begin mapping from.
  563. * @param type The page type to map the memory as.
  564. */
  565. void MapPages(Common::PageTable& page_table, Common::ProcessAddress base_address, u64 size,
  566. Common::PhysicalAddress target, Common::PageType type) {
  567. auto base = GetInteger(base_address);
  568. LOG_DEBUG(HW_Memory, "Mapping {:016X} onto {:016X}-{:016X}", GetInteger(target),
  569. base * YUZU_PAGESIZE, (base + size) * YUZU_PAGESIZE);
  570. // During boot, current_page_table might not be set yet, in which case we need not flush
  571. if (system.IsPoweredOn()) {
  572. auto& gpu = system.GPU();
  573. for (u64 i = 0; i < size; i++) {
  574. const auto page = base + i;
  575. if (page_table.pointers[page].Type() == Common::PageType::RasterizerCachedMemory) {
  576. gpu.FlushAndInvalidateRegion(page << YUZU_PAGEBITS, YUZU_PAGESIZE);
  577. }
  578. }
  579. }
  580. const auto end = base + size;
  581. ASSERT_MSG(end <= page_table.pointers.size(), "out of range mapping at {:016X}",
  582. base + page_table.pointers.size());
  583. if (!target) {
  584. ASSERT_MSG(type != Common::PageType::Memory,
  585. "Mapping memory page without a pointer @ {:016x}", base * YUZU_PAGESIZE);
  586. while (base != end) {
  587. page_table.pointers[base].Store(0, type);
  588. page_table.backing_addr[base] = 0;
  589. page_table.blocks[base] = 0;
  590. base += 1;
  591. }
  592. } else {
  593. auto orig_base = base;
  594. while (base != end) {
  595. auto host_ptr =
  596. reinterpret_cast<uintptr_t>(system.DeviceMemory().GetPointer<u8>(target)) -
  597. (base << YUZU_PAGEBITS);
  598. auto backing = GetInteger(target) - (base << YUZU_PAGEBITS);
  599. page_table.pointers[base].Store(host_ptr, type);
  600. page_table.backing_addr[base] = backing;
  601. page_table.blocks[base] = orig_base << YUZU_PAGEBITS;
  602. ASSERT_MSG(page_table.pointers[base].Pointer(),
  603. "memory mapping base yield a nullptr within the table");
  604. base += 1;
  605. target += YUZU_PAGESIZE;
  606. }
  607. }
  608. }
  609. [[nodiscard]] u8* GetPointerImpl(u64 vaddr, auto on_unmapped, auto on_rasterizer) const {
  610. // AARCH64 masks the upper 16 bit of all memory accesses
  611. vaddr = vaddr & 0xffffffffffffULL;
  612. if (!AddressSpaceContains(*current_page_table, vaddr, 1)) [[unlikely]] {
  613. on_unmapped();
  614. return nullptr;
  615. }
  616. // Avoid adding any extra logic to this fast-path block
  617. const uintptr_t raw_pointer = current_page_table->pointers[vaddr >> YUZU_PAGEBITS].Raw();
  618. if (const uintptr_t pointer = Common::PageTable::PageInfo::ExtractPointer(raw_pointer)) {
  619. return reinterpret_cast<u8*>(pointer + vaddr);
  620. }
  621. switch (Common::PageTable::PageInfo::ExtractType(raw_pointer)) {
  622. case Common::PageType::Unmapped:
  623. on_unmapped();
  624. return nullptr;
  625. case Common::PageType::Memory:
  626. ASSERT_MSG(false, "Mapped memory page without a pointer @ 0x{:016X}", vaddr);
  627. return nullptr;
  628. case Common::PageType::DebugMemory:
  629. return GetPointerFromDebugMemory(vaddr);
  630. case Common::PageType::RasterizerCachedMemory: {
  631. u8* const host_ptr{GetPointerFromRasterizerCachedMemory(vaddr)};
  632. on_rasterizer();
  633. return host_ptr;
  634. }
  635. default:
  636. UNREACHABLE();
  637. }
  638. return nullptr;
  639. }
  640. [[nodiscard]] u8* GetPointer(const Common::ProcessAddress vaddr) const {
  641. return GetPointerImpl(
  642. GetInteger(vaddr),
  643. [vaddr]() {
  644. LOG_ERROR(HW_Memory, "Unmapped GetPointer @ 0x{:016X}", GetInteger(vaddr));
  645. },
  646. []() {});
  647. }
  648. [[nodiscard]] u8* GetPointerSilent(const Common::ProcessAddress vaddr) const {
  649. return GetPointerImpl(
  650. GetInteger(vaddr), []() {}, []() {});
  651. }
  652. /**
  653. * Reads a particular data type out of memory at the given virtual address.
  654. *
  655. * @param vaddr The virtual address to read the data type from.
  656. *
  657. * @tparam T The data type to read out of memory. This type *must* be
  658. * trivially copyable, otherwise the behavior of this function
  659. * is undefined.
  660. *
  661. * @returns The instance of T read from the specified virtual address.
  662. */
  663. template <typename T>
  664. T Read(Common::ProcessAddress vaddr) {
  665. T result = 0;
  666. const u8* const ptr = GetPointerImpl(
  667. GetInteger(vaddr),
  668. [vaddr]() {
  669. LOG_ERROR(HW_Memory, "Unmapped Read{} @ 0x{:016X}", sizeof(T) * 8,
  670. GetInteger(vaddr));
  671. },
  672. [&]() { HandleRasterizerDownload(GetInteger(vaddr), sizeof(T)); });
  673. if (ptr) {
  674. std::memcpy(&result, ptr, sizeof(T));
  675. }
  676. return result;
  677. }
  678. /**
  679. * Writes a particular data type to memory at the given virtual address.
  680. *
  681. * @param vaddr The virtual address to write the data type to.
  682. *
  683. * @tparam T The data type to write to memory. This type *must* be
  684. * trivially copyable, otherwise the behavior of this function
  685. * is undefined.
  686. */
  687. template <typename T>
  688. void Write(Common::ProcessAddress vaddr, const T data) {
  689. u8* const ptr = GetPointerImpl(
  690. GetInteger(vaddr),
  691. [vaddr, data]() {
  692. LOG_ERROR(HW_Memory, "Unmapped Write{} @ 0x{:016X} = 0x{:016X}", sizeof(T) * 8,
  693. GetInteger(vaddr), static_cast<u64>(data));
  694. },
  695. [&]() { HandleRasterizerWrite(GetInteger(vaddr), sizeof(T)); });
  696. if (ptr) {
  697. std::memcpy(ptr, &data, sizeof(T));
  698. }
  699. }
  700. template <typename T>
  701. bool WriteExclusive(Common::ProcessAddress vaddr, const T data, const T expected) {
  702. u8* const ptr = GetPointerImpl(
  703. GetInteger(vaddr),
  704. [vaddr, data]() {
  705. LOG_ERROR(HW_Memory, "Unmapped WriteExclusive{} @ 0x{:016X} = 0x{:016X}",
  706. sizeof(T) * 8, GetInteger(vaddr), static_cast<u64>(data));
  707. },
  708. [&]() { HandleRasterizerWrite(GetInteger(vaddr), sizeof(T)); });
  709. if (ptr) {
  710. const auto volatile_pointer = reinterpret_cast<volatile T*>(ptr);
  711. return Common::AtomicCompareAndSwap(volatile_pointer, data, expected);
  712. }
  713. return true;
  714. }
  715. bool WriteExclusive128(Common::ProcessAddress vaddr, const u128 data, const u128 expected) {
  716. u8* const ptr = GetPointerImpl(
  717. GetInteger(vaddr),
  718. [vaddr, data]() {
  719. LOG_ERROR(HW_Memory, "Unmapped WriteExclusive128 @ 0x{:016X} = 0x{:016X}{:016X}",
  720. GetInteger(vaddr), static_cast<u64>(data[1]), static_cast<u64>(data[0]));
  721. },
  722. [&]() { HandleRasterizerWrite(GetInteger(vaddr), sizeof(u128)); });
  723. if (ptr) {
  724. const auto volatile_pointer = reinterpret_cast<volatile u64*>(ptr);
  725. return Common::AtomicCompareAndSwap(volatile_pointer, data, expected);
  726. }
  727. return true;
  728. }
  729. void HandleRasterizerDownload(VAddr address, size_t size) {
  730. const size_t core = system.GetCurrentHostThreadID();
  731. auto& current_area = rasterizer_read_areas[core];
  732. const VAddr end_address = address + size;
  733. if (current_area.start_address <= address && end_address <= current_area.end_address)
  734. [[likely]] {
  735. return;
  736. }
  737. current_area = system.GPU().OnCPURead(address, size);
  738. }
  739. void HandleRasterizerWrite(VAddr address, size_t size) {
  740. constexpr size_t sys_core = Core::Hardware::NUM_CPU_CORES - 1;
  741. const size_t core = std::min(system.GetCurrentHostThreadID(),
  742. sys_core); // any other calls threads go to syscore.
  743. // Guard on sys_core;
  744. if (core == sys_core) [[unlikely]] {
  745. sys_core_guard.lock();
  746. }
  747. SCOPE_EXIT({
  748. if (core == sys_core) [[unlikely]] {
  749. sys_core_guard.unlock();
  750. }
  751. });
  752. auto& current_area = rasterizer_write_areas[core];
  753. VAddr subaddress = address >> YUZU_PAGEBITS;
  754. bool do_collection = current_area.last_address == subaddress;
  755. if (!do_collection) [[unlikely]] {
  756. do_collection = system.GPU().OnCPUWrite(address, size);
  757. if (!do_collection) {
  758. return;
  759. }
  760. current_area.last_address = subaddress;
  761. }
  762. gpu_dirty_managers[core].Collect(address, size);
  763. }
  764. struct GPUDirtyState {
  765. VAddr last_address;
  766. };
  767. void InvalidateRegion(Common::ProcessAddress dest_addr, size_t size) {
  768. system.GPU().InvalidateRegion(GetInteger(dest_addr), size);
  769. }
  770. void FlushRegion(Common::ProcessAddress dest_addr, size_t size) {
  771. system.GPU().FlushRegion(GetInteger(dest_addr), size);
  772. }
  773. Core::System& system;
  774. Common::PageTable* current_page_table = nullptr;
  775. std::array<VideoCore::RasterizerDownloadArea, Core::Hardware::NUM_CPU_CORES>
  776. rasterizer_read_areas{};
  777. std::array<GPUDirtyState, Core::Hardware::NUM_CPU_CORES> rasterizer_write_areas{};
  778. std::span<Core::GPUDirtyMemoryManager> gpu_dirty_managers;
  779. std::mutex sys_core_guard;
  780. std::optional<Common::HeapTracker> heap_tracker;
  781. #ifdef __linux__
  782. Common::HeapTracker* buffer{};
  783. #else
  784. Common::HostMemory* buffer{};
  785. #endif
  786. };
  787. Memory::Memory(Core::System& system_) : system{system_} {
  788. Reset();
  789. }
  790. Memory::~Memory() = default;
  791. void Memory::Reset() {
  792. impl = std::make_unique<Impl>(system);
  793. }
  794. void Memory::SetCurrentPageTable(Kernel::KProcess& process) {
  795. impl->SetCurrentPageTable(process);
  796. }
  797. void Memory::MapMemoryRegion(Common::PageTable& page_table, Common::ProcessAddress base, u64 size,
  798. Common::PhysicalAddress target, Common::MemoryPermission perms,
  799. bool separate_heap) {
  800. impl->MapMemoryRegion(page_table, base, size, target, perms, separate_heap);
  801. }
  802. void Memory::UnmapRegion(Common::PageTable& page_table, Common::ProcessAddress base, u64 size,
  803. bool separate_heap) {
  804. impl->UnmapRegion(page_table, base, size, separate_heap);
  805. }
  806. void Memory::ProtectRegion(Common::PageTable& page_table, Common::ProcessAddress vaddr, u64 size,
  807. Common::MemoryPermission perms) {
  808. impl->ProtectRegion(page_table, GetInteger(vaddr), size, perms);
  809. }
  810. bool Memory::IsValidVirtualAddress(const Common::ProcessAddress vaddr) const {
  811. const auto& page_table = *impl->current_page_table;
  812. const size_t page = vaddr >> YUZU_PAGEBITS;
  813. if (page >= page_table.pointers.size()) {
  814. return false;
  815. }
  816. const auto [pointer, type] = page_table.pointers[page].PointerType();
  817. return pointer != 0 || type == Common::PageType::RasterizerCachedMemory ||
  818. type == Common::PageType::DebugMemory;
  819. }
  820. bool Memory::IsValidVirtualAddressRange(Common::ProcessAddress base, u64 size) const {
  821. Common::ProcessAddress end = base + size;
  822. Common::ProcessAddress page = Common::AlignDown(GetInteger(base), YUZU_PAGESIZE);
  823. for (; page < end; page += YUZU_PAGESIZE) {
  824. if (!IsValidVirtualAddress(page)) {
  825. return false;
  826. }
  827. }
  828. return true;
  829. }
  830. u8* Memory::GetPointer(Common::ProcessAddress vaddr) {
  831. return impl->GetPointer(vaddr);
  832. }
  833. u8* Memory::GetPointerSilent(Common::ProcessAddress vaddr) {
  834. return impl->GetPointerSilent(vaddr);
  835. }
  836. const u8* Memory::GetPointer(Common::ProcessAddress vaddr) const {
  837. return impl->GetPointer(vaddr);
  838. }
  839. u8 Memory::Read8(const Common::ProcessAddress addr) {
  840. return impl->Read8(addr);
  841. }
  842. u16 Memory::Read16(const Common::ProcessAddress addr) {
  843. return impl->Read16(addr);
  844. }
  845. u32 Memory::Read32(const Common::ProcessAddress addr) {
  846. return impl->Read32(addr);
  847. }
  848. u64 Memory::Read64(const Common::ProcessAddress addr) {
  849. return impl->Read64(addr);
  850. }
  851. void Memory::Write8(Common::ProcessAddress addr, u8 data) {
  852. impl->Write8(addr, data);
  853. }
  854. void Memory::Write16(Common::ProcessAddress addr, u16 data) {
  855. impl->Write16(addr, data);
  856. }
  857. void Memory::Write32(Common::ProcessAddress addr, u32 data) {
  858. impl->Write32(addr, data);
  859. }
  860. void Memory::Write64(Common::ProcessAddress addr, u64 data) {
  861. impl->Write64(addr, data);
  862. }
  863. bool Memory::WriteExclusive8(Common::ProcessAddress addr, u8 data, u8 expected) {
  864. return impl->WriteExclusive8(addr, data, expected);
  865. }
  866. bool Memory::WriteExclusive16(Common::ProcessAddress addr, u16 data, u16 expected) {
  867. return impl->WriteExclusive16(addr, data, expected);
  868. }
  869. bool Memory::WriteExclusive32(Common::ProcessAddress addr, u32 data, u32 expected) {
  870. return impl->WriteExclusive32(addr, data, expected);
  871. }
  872. bool Memory::WriteExclusive64(Common::ProcessAddress addr, u64 data, u64 expected) {
  873. return impl->WriteExclusive64(addr, data, expected);
  874. }
  875. bool Memory::WriteExclusive128(Common::ProcessAddress addr, u128 data, u128 expected) {
  876. return impl->WriteExclusive128(addr, data, expected);
  877. }
  878. std::string Memory::ReadCString(Common::ProcessAddress vaddr, std::size_t max_length) {
  879. return impl->ReadCString(vaddr, max_length);
  880. }
  881. bool Memory::ReadBlock(const Common::ProcessAddress src_addr, void* dest_buffer,
  882. const std::size_t size) {
  883. return impl->ReadBlock(src_addr, dest_buffer, size);
  884. }
  885. bool Memory::ReadBlockUnsafe(const Common::ProcessAddress src_addr, void* dest_buffer,
  886. const std::size_t size) {
  887. return impl->ReadBlockUnsafe(src_addr, dest_buffer, size);
  888. }
  889. const u8* Memory::GetSpan(const VAddr src_addr, const std::size_t size) const {
  890. return impl->GetSpan(src_addr, size);
  891. }
  892. u8* Memory::GetSpan(const VAddr src_addr, const std::size_t size) {
  893. return impl->GetSpan(src_addr, size);
  894. }
  895. bool Memory::WriteBlock(const Common::ProcessAddress dest_addr, const void* src_buffer,
  896. const std::size_t size) {
  897. return impl->WriteBlock(dest_addr, src_buffer, size);
  898. }
  899. bool Memory::WriteBlockUnsafe(const Common::ProcessAddress dest_addr, const void* src_buffer,
  900. const std::size_t size) {
  901. return impl->WriteBlockUnsafe(dest_addr, src_buffer, size);
  902. }
  903. bool Memory::CopyBlock(Common::ProcessAddress dest_addr, Common::ProcessAddress src_addr,
  904. const std::size_t size) {
  905. return impl->CopyBlock(dest_addr, src_addr, size);
  906. }
  907. bool Memory::ZeroBlock(Common::ProcessAddress dest_addr, const std::size_t size) {
  908. return impl->ZeroBlock(dest_addr, size);
  909. }
  910. void Memory::SetGPUDirtyManagers(std::span<Core::GPUDirtyMemoryManager> managers) {
  911. impl->gpu_dirty_managers = managers;
  912. }
  913. Result Memory::InvalidateDataCache(Common::ProcessAddress dest_addr, const std::size_t size) {
  914. return impl->InvalidateDataCache(dest_addr, size);
  915. }
  916. Result Memory::StoreDataCache(Common::ProcessAddress dest_addr, const std::size_t size) {
  917. return impl->StoreDataCache(dest_addr, size);
  918. }
  919. Result Memory::FlushDataCache(Common::ProcessAddress dest_addr, const std::size_t size) {
  920. return impl->FlushDataCache(dest_addr, size);
  921. }
  922. void Memory::RasterizerMarkRegionCached(Common::ProcessAddress vaddr, u64 size, bool cached) {
  923. impl->RasterizerMarkRegionCached(GetInteger(vaddr), size, cached);
  924. }
  925. void Memory::MarkRegionDebug(Common::ProcessAddress vaddr, u64 size, bool debug) {
  926. impl->MarkRegionDebug(GetInteger(vaddr), size, debug);
  927. }
  928. void Memory::InvalidateRegion(Common::ProcessAddress dest_addr, size_t size) {
  929. impl->InvalidateRegion(dest_addr, size);
  930. }
  931. void Memory::FlushRegion(Common::ProcessAddress dest_addr, size_t size) {
  932. impl->FlushRegion(dest_addr, size);
  933. }
  934. bool Memory::InvalidateNCE(Common::ProcessAddress vaddr, size_t size) {
  935. [[maybe_unused]] bool mapped = true;
  936. [[maybe_unused]] bool rasterizer = false;
  937. u8* const ptr = impl->GetPointerImpl(
  938. GetInteger(vaddr),
  939. [&] {
  940. LOG_ERROR(HW_Memory, "Unmapped InvalidateNCE for {} bytes @ {:#x}", size,
  941. GetInteger(vaddr));
  942. mapped = false;
  943. },
  944. [&] {
  945. impl->system.GPU().InvalidateRegion(GetInteger(vaddr), size);
  946. rasterizer = true;
  947. });
  948. #ifdef __linux__
  949. if (!rasterizer && mapped) {
  950. impl->buffer->DeferredMapSeparateHeap(GetInteger(vaddr));
  951. }
  952. #endif
  953. return mapped && ptr != nullptr;
  954. }
  955. bool Memory::InvalidateSeparateHeap(void* fault_address) {
  956. #ifdef __linux__
  957. return impl->buffer->DeferredMapSeparateHeap(static_cast<u8*>(fault_address));
  958. #else
  959. return false;
  960. #endif
  961. }
  962. } // namespace Core::Memory