memory.cpp 39 KB

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