memory.cpp 42 KB

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