buffer_cache.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. // Copyright 2019 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <list>
  6. #include <memory>
  7. #include <mutex>
  8. #include <unordered_map>
  9. #include <unordered_set>
  10. #include <utility>
  11. #include <vector>
  12. #include <boost/icl/interval_map.hpp>
  13. #include <boost/icl/interval_set.hpp>
  14. #include <boost/range/iterator_range.hpp>
  15. #include "common/alignment.h"
  16. #include "common/common_types.h"
  17. #include "common/logging/log.h"
  18. #include "core/core.h"
  19. #include "core/memory.h"
  20. #include "core/settings.h"
  21. #include "video_core/buffer_cache/buffer_block.h"
  22. #include "video_core/buffer_cache/map_interval.h"
  23. #include "video_core/memory_manager.h"
  24. #include "video_core/rasterizer_interface.h"
  25. namespace VideoCommon {
  26. template <typename OwnerBuffer, typename BufferType, typename StreamBuffer>
  27. class BufferCache {
  28. public:
  29. using BufferInfo = std::pair<BufferType, u64>;
  30. BufferInfo UploadMemory(GPUVAddr gpu_addr, std::size_t size, std::size_t alignment = 4,
  31. bool is_written = false, bool use_fast_cbuf = false) {
  32. std::lock_guard lock{mutex};
  33. const auto& memory_manager = system.GPU().MemoryManager();
  34. const std::optional<VAddr> cpu_addr_opt = memory_manager.GpuToCpuAddress(gpu_addr);
  35. if (!cpu_addr_opt) {
  36. return {GetEmptyBuffer(size), 0};
  37. }
  38. const VAddr cpu_addr = *cpu_addr_opt;
  39. // Cache management is a big overhead, so only cache entries with a given size.
  40. // TODO: Figure out which size is the best for given games.
  41. constexpr std::size_t max_stream_size = 0x800;
  42. if (use_fast_cbuf || size < max_stream_size) {
  43. if (!is_written && !IsRegionWritten(cpu_addr, cpu_addr + size - 1)) {
  44. auto& memory_manager = system.GPU().MemoryManager();
  45. if (use_fast_cbuf) {
  46. if (memory_manager.IsGranularRange(gpu_addr, size)) {
  47. const auto host_ptr = memory_manager.GetPointer(gpu_addr);
  48. return ConstBufferUpload(host_ptr, size);
  49. } else {
  50. staging_buffer.resize(size);
  51. memory_manager.ReadBlockUnsafe(gpu_addr, staging_buffer.data(), size);
  52. return ConstBufferUpload(staging_buffer.data(), size);
  53. }
  54. } else {
  55. if (memory_manager.IsGranularRange(gpu_addr, size)) {
  56. const auto host_ptr = memory_manager.GetPointer(gpu_addr);
  57. return StreamBufferUpload(host_ptr, size, alignment);
  58. } else {
  59. staging_buffer.resize(size);
  60. memory_manager.ReadBlockUnsafe(gpu_addr, staging_buffer.data(), size);
  61. return StreamBufferUpload(staging_buffer.data(), size, alignment);
  62. }
  63. }
  64. }
  65. }
  66. auto block = GetBlock(cpu_addr, size);
  67. MapInterval* const map = MapAddress(block, gpu_addr, cpu_addr, size);
  68. if (!map) {
  69. return {GetEmptyBuffer(size), 0};
  70. }
  71. if (is_written) {
  72. map->MarkAsModified(true, GetModifiedTicks());
  73. if (Settings::IsGPULevelHigh() && Settings::values.use_asynchronous_gpu_emulation) {
  74. MarkForAsyncFlush(map);
  75. }
  76. if (!map->is_written) {
  77. map->is_written = true;
  78. MarkRegionAsWritten(map->start, map->end - 1);
  79. }
  80. }
  81. return {ToHandle(block), static_cast<u64>(block->GetOffset(cpu_addr))};
  82. }
  83. /// Uploads from a host memory. Returns the OpenGL buffer where it's located and its offset.
  84. BufferInfo UploadHostMemory(const void* raw_pointer, std::size_t size,
  85. std::size_t alignment = 4) {
  86. std::lock_guard lock{mutex};
  87. return StreamBufferUpload(raw_pointer, size, alignment);
  88. }
  89. void Map(std::size_t max_size) {
  90. std::lock_guard lock{mutex};
  91. std::tie(buffer_ptr, buffer_offset_base, invalidated) = stream_buffer->Map(max_size, 4);
  92. buffer_offset = buffer_offset_base;
  93. }
  94. /// Finishes the upload stream, returns true on bindings invalidation.
  95. bool Unmap() {
  96. std::lock_guard lock{mutex};
  97. stream_buffer->Unmap(buffer_offset - buffer_offset_base);
  98. return std::exchange(invalidated, false);
  99. }
  100. void TickFrame() {
  101. ++epoch;
  102. while (!pending_destruction.empty()) {
  103. // Delay at least 4 frames before destruction.
  104. // This is due to triple buffering happening on some drivers.
  105. static constexpr u64 epochs_to_destroy = 5;
  106. if (pending_destruction.front()->GetEpoch() + epochs_to_destroy > epoch) {
  107. break;
  108. }
  109. pending_destruction.pop_front();
  110. }
  111. }
  112. /// Write any cached resources overlapping the specified region back to memory
  113. void FlushRegion(VAddr addr, std::size_t size) {
  114. std::lock_guard lock{mutex};
  115. std::vector<MapInterval*> objects = GetMapsInRange(addr, size);
  116. std::sort(objects.begin(), objects.end(),
  117. [](MapInterval* lhs, MapInterval* rhs) { return lhs->ticks < rhs->ticks; });
  118. for (MapInterval* object : objects) {
  119. if (object->is_modified && object->is_registered) {
  120. mutex.unlock();
  121. FlushMap(object);
  122. mutex.lock();
  123. }
  124. }
  125. }
  126. bool MustFlushRegion(VAddr addr, std::size_t size) {
  127. std::lock_guard lock{mutex};
  128. const std::vector<MapInterval*> objects = GetMapsInRange(addr, size);
  129. return std::any_of(objects.cbegin(), objects.cend(), [](const MapInterval* map) {
  130. return map->is_modified && map->is_registered;
  131. });
  132. }
  133. /// Mark the specified region as being invalidated
  134. void InvalidateRegion(VAddr addr, u64 size) {
  135. std::lock_guard lock{mutex};
  136. std::vector<MapInterval*> objects = GetMapsInRange(addr, size);
  137. for (auto& object : objects) {
  138. if (object->is_registered) {
  139. Unregister(object);
  140. }
  141. }
  142. }
  143. void OnCPUWrite(VAddr addr, std::size_t size) {
  144. std::lock_guard lock{mutex};
  145. for (MapInterval* object : GetMapsInRange(addr, size)) {
  146. if (object->is_memory_marked && object->is_registered) {
  147. UnmarkMemory(object);
  148. object->is_sync_pending = true;
  149. marked_for_unregister.emplace_back(object);
  150. }
  151. }
  152. }
  153. void SyncGuestHost() {
  154. std::lock_guard lock{mutex};
  155. for (auto& object : marked_for_unregister) {
  156. if (object->is_registered) {
  157. object->is_sync_pending = false;
  158. Unregister(object);
  159. }
  160. }
  161. marked_for_unregister.clear();
  162. }
  163. void CommitAsyncFlushes() {
  164. if (uncommitted_flushes) {
  165. auto commit_list = std::make_shared<std::list<MapInterval*>>();
  166. for (MapInterval* map : *uncommitted_flushes) {
  167. if (map->is_registered && map->is_modified) {
  168. // TODO(Blinkhawk): Implement backend asynchronous flushing
  169. // AsyncFlushMap(map)
  170. commit_list->push_back(map);
  171. }
  172. }
  173. if (!commit_list->empty()) {
  174. committed_flushes.push_back(commit_list);
  175. } else {
  176. committed_flushes.emplace_back();
  177. }
  178. } else {
  179. committed_flushes.emplace_back();
  180. }
  181. uncommitted_flushes.reset();
  182. }
  183. bool ShouldWaitAsyncFlushes() const {
  184. return !committed_flushes.empty() && committed_flushes.front() != nullptr;
  185. }
  186. bool HasUncommittedFlushes() const {
  187. return uncommitted_flushes != nullptr;
  188. }
  189. void PopAsyncFlushes() {
  190. if (committed_flushes.empty()) {
  191. return;
  192. }
  193. auto& flush_list = committed_flushes.front();
  194. if (!flush_list) {
  195. committed_flushes.pop_front();
  196. return;
  197. }
  198. for (MapInterval* map : *flush_list) {
  199. if (map->is_registered) {
  200. // TODO(Blinkhawk): Replace this for reading the asynchronous flush
  201. FlushMap(map);
  202. }
  203. }
  204. committed_flushes.pop_front();
  205. }
  206. virtual BufferType GetEmptyBuffer(std::size_t size) = 0;
  207. protected:
  208. explicit BufferCache(VideoCore::RasterizerInterface& rasterizer, Core::System& system,
  209. std::unique_ptr<StreamBuffer> stream_buffer)
  210. : rasterizer{rasterizer}, system{system}, stream_buffer{std::move(stream_buffer)},
  211. stream_buffer_handle{this->stream_buffer->GetHandle()} {}
  212. ~BufferCache() = default;
  213. virtual BufferType ToHandle(const OwnerBuffer& storage) = 0;
  214. virtual OwnerBuffer CreateBlock(VAddr cpu_addr, std::size_t size) = 0;
  215. virtual void UploadBlockData(const OwnerBuffer& buffer, std::size_t offset, std::size_t size,
  216. const u8* data) = 0;
  217. virtual void DownloadBlockData(const OwnerBuffer& buffer, std::size_t offset, std::size_t size,
  218. u8* data) = 0;
  219. virtual void CopyBlock(const OwnerBuffer& src, const OwnerBuffer& dst, std::size_t src_offset,
  220. std::size_t dst_offset, std::size_t size) = 0;
  221. virtual BufferInfo ConstBufferUpload(const void* raw_pointer, std::size_t size) {
  222. return {};
  223. }
  224. /// Register an object into the cache
  225. MapInterval* Register(MapInterval new_map, bool inherit_written = false) {
  226. const VAddr cpu_addr = new_map.start;
  227. if (!cpu_addr) {
  228. LOG_CRITICAL(HW_GPU, "Failed to register buffer with unmapped gpu_address 0x{:016x}",
  229. new_map.gpu_addr);
  230. return nullptr;
  231. }
  232. const std::size_t size = new_map.end - new_map.start;
  233. new_map.is_registered = true;
  234. const IntervalType interval{new_map.start, new_map.end};
  235. rasterizer.UpdatePagesCachedCount(cpu_addr, size, 1);
  236. new_map.is_memory_marked = true;
  237. if (inherit_written) {
  238. MarkRegionAsWritten(new_map.start, new_map.end - 1);
  239. new_map.is_written = true;
  240. }
  241. mapped_addresses.insert({interval, new_map});
  242. // Temporary hack until this is replaced with boost::intrusive::rbtree
  243. return const_cast<MapInterval*>(&mapped_addresses.find(interval)->second);
  244. }
  245. void UnmarkMemory(MapInterval* map) {
  246. if (!map->is_memory_marked) {
  247. return;
  248. }
  249. const std::size_t size = map->end - map->start;
  250. rasterizer.UpdatePagesCachedCount(map->start, size, -1);
  251. map->is_memory_marked = false;
  252. }
  253. /// Unregisters an object from the cache
  254. void Unregister(MapInterval* map) {
  255. UnmarkMemory(map);
  256. map->is_registered = false;
  257. if (map->is_sync_pending) {
  258. map->is_sync_pending = false;
  259. marked_for_unregister.remove(map);
  260. }
  261. if (map->is_written) {
  262. UnmarkRegionAsWritten(map->start, map->end - 1);
  263. }
  264. const IntervalType delete_interval{map->start, map->end};
  265. mapped_addresses.erase(delete_interval);
  266. }
  267. private:
  268. MapInterval* MapAddress(const OwnerBuffer& block, GPUVAddr gpu_addr, VAddr cpu_addr,
  269. std::size_t size) {
  270. std::vector<MapInterval*> overlaps = GetMapsInRange(cpu_addr, size);
  271. if (overlaps.empty()) {
  272. auto& memory_manager = system.GPU().MemoryManager();
  273. const VAddr cpu_addr_end = cpu_addr + size;
  274. if (memory_manager.IsGranularRange(gpu_addr, size)) {
  275. u8* host_ptr = memory_manager.GetPointer(gpu_addr);
  276. UploadBlockData(block, block->GetOffset(cpu_addr), size, host_ptr);
  277. } else {
  278. staging_buffer.resize(size);
  279. memory_manager.ReadBlockUnsafe(gpu_addr, staging_buffer.data(), size);
  280. UploadBlockData(block, block->GetOffset(cpu_addr), size, staging_buffer.data());
  281. }
  282. return Register(MapInterval(cpu_addr, cpu_addr_end, gpu_addr));
  283. }
  284. const VAddr cpu_addr_end = cpu_addr + size;
  285. if (overlaps.size() == 1) {
  286. MapInterval* const current_map = overlaps[0];
  287. if (current_map->IsInside(cpu_addr, cpu_addr_end)) {
  288. return current_map;
  289. }
  290. }
  291. VAddr new_start = cpu_addr;
  292. VAddr new_end = cpu_addr_end;
  293. bool write_inheritance = false;
  294. bool modified_inheritance = false;
  295. // Calculate new buffer parameters
  296. for (MapInterval* overlap : overlaps) {
  297. new_start = std::min(overlap->start, new_start);
  298. new_end = std::max(overlap->end, new_end);
  299. write_inheritance |= overlap->is_written;
  300. modified_inheritance |= overlap->is_modified;
  301. }
  302. GPUVAddr new_gpu_addr = gpu_addr + new_start - cpu_addr;
  303. for (auto& overlap : overlaps) {
  304. Unregister(overlap);
  305. }
  306. UpdateBlock(block, new_start, new_end, overlaps);
  307. const MapInterval new_map{new_start, new_end, new_gpu_addr};
  308. MapInterval* const map = Register(new_map, write_inheritance);
  309. if (!map) {
  310. return nullptr;
  311. }
  312. if (modified_inheritance) {
  313. map->MarkAsModified(true, GetModifiedTicks());
  314. if (Settings::IsGPULevelHigh() && Settings::values.use_asynchronous_gpu_emulation) {
  315. MarkForAsyncFlush(map);
  316. }
  317. }
  318. return map;
  319. }
  320. void UpdateBlock(const OwnerBuffer& block, VAddr start, VAddr end,
  321. std::vector<MapInterval*>& overlaps) {
  322. const IntervalType base_interval{start, end};
  323. IntervalSet interval_set{};
  324. interval_set.add(base_interval);
  325. for (auto& overlap : overlaps) {
  326. const IntervalType subtract{overlap->start, overlap->end};
  327. interval_set.subtract(subtract);
  328. }
  329. for (auto& interval : interval_set) {
  330. std::size_t size = interval.upper() - interval.lower();
  331. if (size > 0) {
  332. staging_buffer.resize(size);
  333. system.Memory().ReadBlockUnsafe(interval.lower(), staging_buffer.data(), size);
  334. UploadBlockData(block, block->GetOffset(interval.lower()), size,
  335. staging_buffer.data());
  336. }
  337. }
  338. }
  339. std::vector<MapInterval*> GetMapsInRange(VAddr addr, std::size_t size) {
  340. if (size == 0) {
  341. return {};
  342. }
  343. std::vector<MapInterval*> objects;
  344. const IntervalType interval{addr, addr + size};
  345. for (auto& pair : boost::make_iterator_range(mapped_addresses.equal_range(interval))) {
  346. objects.push_back(&pair.second);
  347. }
  348. return objects;
  349. }
  350. /// Returns a ticks counter used for tracking when cached objects were last modified
  351. u64 GetModifiedTicks() {
  352. return ++modified_ticks;
  353. }
  354. void FlushMap(MapInterval* map) {
  355. const std::size_t size = map->end - map->start;
  356. OwnerBuffer block = blocks[map->start >> block_page_bits];
  357. staging_buffer.resize(size);
  358. DownloadBlockData(block, block->GetOffset(map->start), size, staging_buffer.data());
  359. system.Memory().WriteBlockUnsafe(map->start, staging_buffer.data(), size);
  360. map->MarkAsModified(false, 0);
  361. }
  362. BufferInfo StreamBufferUpload(const void* raw_pointer, std::size_t size,
  363. std::size_t alignment) {
  364. AlignBuffer(alignment);
  365. const std::size_t uploaded_offset = buffer_offset;
  366. std::memcpy(buffer_ptr, raw_pointer, size);
  367. buffer_ptr += size;
  368. buffer_offset += size;
  369. return {stream_buffer_handle, uploaded_offset};
  370. }
  371. void AlignBuffer(std::size_t alignment) {
  372. // Align the offset, not the mapped pointer
  373. const std::size_t offset_aligned = Common::AlignUp(buffer_offset, alignment);
  374. buffer_ptr += offset_aligned - buffer_offset;
  375. buffer_offset = offset_aligned;
  376. }
  377. OwnerBuffer EnlargeBlock(OwnerBuffer buffer) {
  378. const std::size_t old_size = buffer->GetSize();
  379. const std::size_t new_size = old_size + block_page_size;
  380. const VAddr cpu_addr = buffer->GetCpuAddr();
  381. OwnerBuffer new_buffer = CreateBlock(cpu_addr, new_size);
  382. CopyBlock(buffer, new_buffer, 0, 0, old_size);
  383. buffer->SetEpoch(epoch);
  384. pending_destruction.push_back(buffer);
  385. const VAddr cpu_addr_end = cpu_addr + new_size - 1;
  386. u64 page_start = cpu_addr >> block_page_bits;
  387. const u64 page_end = cpu_addr_end >> block_page_bits;
  388. while (page_start <= page_end) {
  389. blocks[page_start] = new_buffer;
  390. ++page_start;
  391. }
  392. return new_buffer;
  393. }
  394. OwnerBuffer MergeBlocks(OwnerBuffer first, OwnerBuffer second) {
  395. const std::size_t size_1 = first->GetSize();
  396. const std::size_t size_2 = second->GetSize();
  397. const VAddr first_addr = first->GetCpuAddr();
  398. const VAddr second_addr = second->GetCpuAddr();
  399. const VAddr new_addr = std::min(first_addr, second_addr);
  400. const std::size_t new_size = size_1 + size_2;
  401. OwnerBuffer new_buffer = CreateBlock(new_addr, new_size);
  402. CopyBlock(first, new_buffer, 0, new_buffer->GetOffset(first_addr), size_1);
  403. CopyBlock(second, new_buffer, 0, new_buffer->GetOffset(second_addr), size_2);
  404. first->SetEpoch(epoch);
  405. second->SetEpoch(epoch);
  406. pending_destruction.push_back(first);
  407. pending_destruction.push_back(second);
  408. const VAddr cpu_addr_end = new_addr + new_size - 1;
  409. u64 page_start = new_addr >> block_page_bits;
  410. const u64 page_end = cpu_addr_end >> block_page_bits;
  411. while (page_start <= page_end) {
  412. blocks[page_start] = new_buffer;
  413. ++page_start;
  414. }
  415. return new_buffer;
  416. }
  417. OwnerBuffer GetBlock(const VAddr cpu_addr, const std::size_t size) {
  418. OwnerBuffer found;
  419. const VAddr cpu_addr_end = cpu_addr + size - 1;
  420. u64 page_start = cpu_addr >> block_page_bits;
  421. const u64 page_end = cpu_addr_end >> block_page_bits;
  422. while (page_start <= page_end) {
  423. auto it = blocks.find(page_start);
  424. if (it == blocks.end()) {
  425. if (found) {
  426. found = EnlargeBlock(found);
  427. } else {
  428. const VAddr start_addr = (page_start << block_page_bits);
  429. found = CreateBlock(start_addr, block_page_size);
  430. blocks[page_start] = found;
  431. }
  432. } else {
  433. if (found) {
  434. if (found == it->second) {
  435. ++page_start;
  436. continue;
  437. }
  438. found = MergeBlocks(found, it->second);
  439. } else {
  440. found = it->second;
  441. }
  442. }
  443. ++page_start;
  444. }
  445. return found;
  446. }
  447. void MarkRegionAsWritten(const VAddr start, const VAddr end) {
  448. u64 page_start = start >> write_page_bit;
  449. const u64 page_end = end >> write_page_bit;
  450. while (page_start <= page_end) {
  451. auto it = written_pages.find(page_start);
  452. if (it != written_pages.end()) {
  453. it->second = it->second + 1;
  454. } else {
  455. written_pages[page_start] = 1;
  456. }
  457. ++page_start;
  458. }
  459. }
  460. void UnmarkRegionAsWritten(const VAddr start, const VAddr end) {
  461. u64 page_start = start >> write_page_bit;
  462. const u64 page_end = end >> write_page_bit;
  463. while (page_start <= page_end) {
  464. auto it = written_pages.find(page_start);
  465. if (it != written_pages.end()) {
  466. if (it->second > 1) {
  467. it->second = it->second - 1;
  468. } else {
  469. written_pages.erase(it);
  470. }
  471. }
  472. ++page_start;
  473. }
  474. }
  475. bool IsRegionWritten(const VAddr start, const VAddr end) const {
  476. u64 page_start = start >> write_page_bit;
  477. const u64 page_end = end >> write_page_bit;
  478. while (page_start <= page_end) {
  479. if (written_pages.count(page_start) > 0) {
  480. return true;
  481. }
  482. ++page_start;
  483. }
  484. return false;
  485. }
  486. void MarkForAsyncFlush(MapInterval* map) {
  487. if (!uncommitted_flushes) {
  488. uncommitted_flushes = std::make_shared<std::unordered_set<MapInterval*>>();
  489. }
  490. uncommitted_flushes->insert(map);
  491. }
  492. VideoCore::RasterizerInterface& rasterizer;
  493. Core::System& system;
  494. std::unique_ptr<StreamBuffer> stream_buffer;
  495. BufferType stream_buffer_handle{};
  496. bool invalidated = false;
  497. u8* buffer_ptr = nullptr;
  498. u64 buffer_offset = 0;
  499. u64 buffer_offset_base = 0;
  500. using IntervalSet = boost::icl::interval_set<VAddr>;
  501. using IntervalCache = boost::icl::interval_map<VAddr, MapInterval>;
  502. using IntervalType = typename IntervalCache::interval_type;
  503. IntervalCache mapped_addresses;
  504. static constexpr u64 write_page_bit = 11;
  505. std::unordered_map<u64, u32> written_pages;
  506. static constexpr u64 block_page_bits = 21;
  507. static constexpr u64 block_page_size = 1ULL << block_page_bits;
  508. std::unordered_map<u64, OwnerBuffer> blocks;
  509. std::list<OwnerBuffer> pending_destruction;
  510. u64 epoch = 0;
  511. u64 modified_ticks = 0;
  512. std::vector<u8> staging_buffer;
  513. std::list<MapInterval*> marked_for_unregister;
  514. std::shared_ptr<std::unordered_set<MapInterval*>> uncommitted_flushes;
  515. std::list<std::shared_ptr<std::list<MapInterval*>>> committed_flushes;
  516. std::recursive_mutex mutex;
  517. };
  518. } // namespace VideoCommon