buffer_cache.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 <array>
  6. #include <memory>
  7. #include <mutex>
  8. #include <unordered_map>
  9. #include <unordered_set>
  10. #include <utility>
  11. #include <vector>
  12. #include "common/alignment.h"
  13. #include "common/common_types.h"
  14. #include "core/core.h"
  15. #include "video_core/buffer_cache/buffer_block.h"
  16. #include "video_core/buffer_cache/map_interval.h"
  17. #include "video_core/memory_manager.h"
  18. #include "video_core/rasterizer_interface.h"
  19. namespace VideoCommon {
  20. using MapInterval = std::shared_ptr<MapIntervalBase>;
  21. template <typename TBuffer, typename TBufferType, typename StreamBuffer>
  22. class BufferCache {
  23. public:
  24. using BufferInfo = std::pair<const TBufferType*, u64>;
  25. BufferInfo UploadMemory(GPUVAddr gpu_addr, std::size_t size, std::size_t alignment = 4,
  26. bool is_written = false) {
  27. std::lock_guard lock{mutex};
  28. auto& memory_manager = system.GPU().MemoryManager();
  29. const auto host_ptr = memory_manager.GetPointer(gpu_addr);
  30. if (!host_ptr) {
  31. return {GetEmptyBuffer(size), 0};
  32. }
  33. const auto cache_addr = ToCacheAddr(host_ptr);
  34. // Cache management is a big overhead, so only cache entries with a given size.
  35. // TODO: Figure out which size is the best for given games.
  36. constexpr std::size_t max_stream_size = 0x800;
  37. if (size < max_stream_size) {
  38. if (!is_written && !IsRegionWritten(cache_addr, cache_addr + size - 1)) {
  39. return StreamBufferUpload(host_ptr, size, alignment);
  40. }
  41. }
  42. auto block = GetBlock(cache_addr, size);
  43. auto map = MapAddress(block, gpu_addr, cache_addr, size);
  44. if (is_written) {
  45. map->MarkAsModified(true, GetModifiedTicks());
  46. if (!map->IsWritten()) {
  47. map->MarkAsWritten(true);
  48. MarkRegionAsWritten(map->GetStart(), map->GetEnd() - 1);
  49. }
  50. } else {
  51. if (map->IsWritten()) {
  52. WriteBarrier();
  53. }
  54. }
  55. const u64 offset = static_cast<u64>(block->GetOffset(cache_addr));
  56. return {ToHandle(block), offset};
  57. }
  58. /// Uploads from a host memory. Returns the OpenGL buffer where it's located and its offset.
  59. BufferInfo UploadHostMemory(const void* raw_pointer, std::size_t size,
  60. std::size_t alignment = 4) {
  61. std::lock_guard lock{mutex};
  62. return StreamBufferUpload(raw_pointer, size, alignment);
  63. }
  64. void Map(std::size_t max_size) {
  65. std::lock_guard lock{mutex};
  66. std::tie(buffer_ptr, buffer_offset_base, invalidated) = stream_buffer->Map(max_size, 4);
  67. buffer_offset = buffer_offset_base;
  68. }
  69. /// Finishes the upload stream, returns true on bindings invalidation.
  70. bool Unmap() {
  71. std::lock_guard lock{mutex};
  72. stream_buffer->Unmap(buffer_offset - buffer_offset_base);
  73. return std::exchange(invalidated, false);
  74. }
  75. void TickFrame() {
  76. ++epoch;
  77. while (!pending_destruction.empty()) {
  78. if (pending_destruction.front()->GetEpoch() + 1 > epoch) {
  79. break;
  80. }
  81. pending_destruction.pop_front();
  82. }
  83. }
  84. /// Write any cached resources overlapping the specified region back to memory
  85. void FlushRegion(CacheAddr addr, std::size_t size) {
  86. std::lock_guard lock{mutex};
  87. std::vector<MapInterval> objects = GetMapsInRange(addr, size);
  88. std::sort(objects.begin(), objects.end(), [](const MapInterval& a, const MapInterval& b) {
  89. return a->GetModificationTick() < b->GetModificationTick();
  90. });
  91. for (auto& object : objects) {
  92. if (object->IsModified() && object->IsRegistered()) {
  93. FlushMap(object);
  94. }
  95. }
  96. }
  97. /// Mark the specified region as being invalidated
  98. void InvalidateRegion(CacheAddr addr, u64 size) {
  99. std::lock_guard lock{mutex};
  100. std::vector<MapInterval> objects = GetMapsInRange(addr, size);
  101. for (auto& object : objects) {
  102. if (object->IsRegistered()) {
  103. Unregister(object);
  104. }
  105. }
  106. }
  107. virtual const TBufferType* GetEmptyBuffer(std::size_t size) = 0;
  108. protected:
  109. explicit BufferCache(VideoCore::RasterizerInterface& rasterizer, Core::System& system,
  110. std::unique_ptr<StreamBuffer> stream_buffer)
  111. : rasterizer{rasterizer}, system{system}, stream_buffer{std::move(stream_buffer)},
  112. stream_buffer_handle{this->stream_buffer->GetHandle()} {}
  113. ~BufferCache() = default;
  114. virtual const TBufferType* ToHandle(const TBuffer& storage) = 0;
  115. virtual void WriteBarrier() = 0;
  116. virtual TBuffer CreateBlock(CacheAddr cache_addr, std::size_t size) = 0;
  117. virtual void UploadBlockData(const TBuffer& buffer, std::size_t offset, std::size_t size,
  118. const u8* data) = 0;
  119. virtual void DownloadBlockData(const TBuffer& buffer, std::size_t offset, std::size_t size,
  120. u8* data) = 0;
  121. virtual void CopyBlock(const TBuffer& src, const TBuffer& dst, std::size_t src_offset,
  122. std::size_t dst_offset, std::size_t size) = 0;
  123. /// Register an object into the cache
  124. void Register(const MapInterval& new_map, bool inherit_written = false) {
  125. const CacheAddr cache_ptr = new_map->GetStart();
  126. const std::optional<VAddr> cpu_addr =
  127. system.GPU().MemoryManager().GpuToCpuAddress(new_map->GetGpuAddress());
  128. if (!cache_ptr || !cpu_addr) {
  129. LOG_CRITICAL(HW_GPU, "Failed to register buffer with unmapped gpu_address 0x{:016x}",
  130. new_map->GetGpuAddress());
  131. return;
  132. }
  133. const std::size_t size = new_map->GetEnd() - new_map->GetStart();
  134. new_map->SetCpuAddress(*cpu_addr);
  135. new_map->MarkAsRegistered(true);
  136. const IntervalType interval{new_map->GetStart(), new_map->GetEnd()};
  137. mapped_addresses.insert({interval, new_map});
  138. rasterizer.UpdatePagesCachedCount(*cpu_addr, size, 1);
  139. if (inherit_written) {
  140. MarkRegionAsWritten(new_map->GetStart(), new_map->GetEnd() - 1);
  141. new_map->MarkAsWritten(true);
  142. }
  143. }
  144. /// Unregisters an object from the cache
  145. void Unregister(MapInterval& map) {
  146. const std::size_t size = map->GetEnd() - map->GetStart();
  147. rasterizer.UpdatePagesCachedCount(map->GetCpuAddress(), size, -1);
  148. map->MarkAsRegistered(false);
  149. if (map->IsWritten()) {
  150. UnmarkRegionAsWritten(map->GetStart(), map->GetEnd() - 1);
  151. }
  152. const IntervalType delete_interval{map->GetStart(), map->GetEnd()};
  153. mapped_addresses.erase(delete_interval);
  154. }
  155. private:
  156. MapInterval CreateMap(const CacheAddr start, const CacheAddr end, const GPUVAddr gpu_addr) {
  157. return std::make_shared<MapIntervalBase>(start, end, gpu_addr);
  158. }
  159. MapInterval MapAddress(const TBuffer& block, const GPUVAddr gpu_addr,
  160. const CacheAddr cache_addr, const std::size_t size) {
  161. std::vector<MapInterval> overlaps = GetMapsInRange(cache_addr, size);
  162. if (overlaps.empty()) {
  163. const CacheAddr cache_addr_end = cache_addr + size;
  164. MapInterval new_map = CreateMap(cache_addr, cache_addr_end, gpu_addr);
  165. u8* host_ptr = FromCacheAddr(cache_addr);
  166. UploadBlockData(block, block->GetOffset(cache_addr), size, host_ptr);
  167. Register(new_map);
  168. return new_map;
  169. }
  170. const CacheAddr cache_addr_end = cache_addr + size;
  171. if (overlaps.size() == 1) {
  172. MapInterval& current_map = overlaps[0];
  173. if (current_map->IsInside(cache_addr, cache_addr_end)) {
  174. return current_map;
  175. }
  176. }
  177. CacheAddr new_start = cache_addr;
  178. CacheAddr new_end = cache_addr_end;
  179. bool write_inheritance = false;
  180. bool modified_inheritance = false;
  181. // Calculate new buffer parameters
  182. for (auto& overlap : overlaps) {
  183. new_start = std::min(overlap->GetStart(), new_start);
  184. new_end = std::max(overlap->GetEnd(), new_end);
  185. write_inheritance |= overlap->IsWritten();
  186. modified_inheritance |= overlap->IsModified();
  187. }
  188. GPUVAddr new_gpu_addr = gpu_addr + new_start - cache_addr;
  189. for (auto& overlap : overlaps) {
  190. Unregister(overlap);
  191. }
  192. UpdateBlock(block, new_start, new_end, overlaps);
  193. MapInterval new_map = CreateMap(new_start, new_end, new_gpu_addr);
  194. if (modified_inheritance) {
  195. new_map->MarkAsModified(true, GetModifiedTicks());
  196. }
  197. Register(new_map, write_inheritance);
  198. return new_map;
  199. }
  200. void UpdateBlock(const TBuffer& block, CacheAddr start, CacheAddr end,
  201. std::vector<MapInterval>& overlaps) {
  202. const IntervalType base_interval{start, end};
  203. IntervalSet interval_set{};
  204. interval_set.add(base_interval);
  205. for (auto& overlap : overlaps) {
  206. const IntervalType subtract{overlap->GetStart(), overlap->GetEnd()};
  207. interval_set.subtract(subtract);
  208. }
  209. for (auto& interval : interval_set) {
  210. std::size_t size = interval.upper() - interval.lower();
  211. if (size > 0) {
  212. u8* host_ptr = FromCacheAddr(interval.lower());
  213. UploadBlockData(block, block->GetOffset(interval.lower()), size, host_ptr);
  214. }
  215. }
  216. }
  217. std::vector<MapInterval> GetMapsInRange(CacheAddr addr, std::size_t size) {
  218. if (size == 0) {
  219. return {};
  220. }
  221. std::vector<MapInterval> objects{};
  222. const IntervalType interval{addr, addr + size};
  223. for (auto& pair : boost::make_iterator_range(mapped_addresses.equal_range(interval))) {
  224. objects.push_back(pair.second);
  225. }
  226. return objects;
  227. }
  228. /// Returns a ticks counter used for tracking when cached objects were last modified
  229. u64 GetModifiedTicks() {
  230. return ++modified_ticks;
  231. }
  232. void FlushMap(MapInterval map) {
  233. std::size_t size = map->GetEnd() - map->GetStart();
  234. TBuffer block = blocks[map->GetStart() >> block_page_bits];
  235. u8* host_ptr = FromCacheAddr(map->GetStart());
  236. DownloadBlockData(block, block->GetOffset(map->GetStart()), size, host_ptr);
  237. map->MarkAsModified(false, 0);
  238. }
  239. BufferInfo StreamBufferUpload(const void* raw_pointer, std::size_t size,
  240. std::size_t alignment) {
  241. AlignBuffer(alignment);
  242. const std::size_t uploaded_offset = buffer_offset;
  243. std::memcpy(buffer_ptr, raw_pointer, size);
  244. buffer_ptr += size;
  245. buffer_offset += size;
  246. return {&stream_buffer_handle, uploaded_offset};
  247. }
  248. void AlignBuffer(std::size_t alignment) {
  249. // Align the offset, not the mapped pointer
  250. const std::size_t offset_aligned = Common::AlignUp(buffer_offset, alignment);
  251. buffer_ptr += offset_aligned - buffer_offset;
  252. buffer_offset = offset_aligned;
  253. }
  254. TBuffer EnlargeBlock(TBuffer buffer) {
  255. const std::size_t old_size = buffer->GetSize();
  256. const std::size_t new_size = old_size + block_page_size;
  257. const CacheAddr cache_addr = buffer->GetCacheAddr();
  258. TBuffer new_buffer = CreateBlock(cache_addr, new_size);
  259. CopyBlock(buffer, new_buffer, 0, 0, old_size);
  260. buffer->SetEpoch(epoch);
  261. pending_destruction.push_back(buffer);
  262. const CacheAddr cache_addr_end = cache_addr + new_size - 1;
  263. u64 page_start = cache_addr >> block_page_bits;
  264. const u64 page_end = cache_addr_end >> block_page_bits;
  265. while (page_start <= page_end) {
  266. blocks[page_start] = new_buffer;
  267. ++page_start;
  268. }
  269. return new_buffer;
  270. }
  271. TBuffer MergeBlocks(TBuffer first, TBuffer second) {
  272. const std::size_t size_1 = first->GetSize();
  273. const std::size_t size_2 = second->GetSize();
  274. const CacheAddr first_addr = first->GetCacheAddr();
  275. const CacheAddr second_addr = second->GetCacheAddr();
  276. const CacheAddr new_addr = std::min(first_addr, second_addr);
  277. const std::size_t new_size = size_1 + size_2;
  278. TBuffer new_buffer = CreateBlock(new_addr, new_size);
  279. CopyBlock(first, new_buffer, 0, new_buffer->GetOffset(first_addr), size_1);
  280. CopyBlock(second, new_buffer, 0, new_buffer->GetOffset(second_addr), size_2);
  281. first->SetEpoch(epoch);
  282. second->SetEpoch(epoch);
  283. pending_destruction.push_back(first);
  284. pending_destruction.push_back(second);
  285. const CacheAddr cache_addr_end = new_addr + new_size - 1;
  286. u64 page_start = new_addr >> block_page_bits;
  287. const u64 page_end = cache_addr_end >> block_page_bits;
  288. while (page_start <= page_end) {
  289. blocks[page_start] = new_buffer;
  290. ++page_start;
  291. }
  292. return new_buffer;
  293. }
  294. TBuffer GetBlock(const CacheAddr cache_addr, const std::size_t size) {
  295. TBuffer found{};
  296. const CacheAddr cache_addr_end = cache_addr + size - 1;
  297. u64 page_start = cache_addr >> block_page_bits;
  298. const u64 page_end = cache_addr_end >> block_page_bits;
  299. while (page_start <= page_end) {
  300. auto it = blocks.find(page_start);
  301. if (it == blocks.end()) {
  302. if (found) {
  303. found = EnlargeBlock(found);
  304. } else {
  305. const CacheAddr start_addr = (page_start << block_page_bits);
  306. found = CreateBlock(start_addr, block_page_size);
  307. blocks[page_start] = found;
  308. }
  309. } else {
  310. if (found) {
  311. if (found == it->second) {
  312. ++page_start;
  313. continue;
  314. }
  315. found = MergeBlocks(found, it->second);
  316. } else {
  317. found = it->second;
  318. }
  319. }
  320. ++page_start;
  321. }
  322. return found;
  323. }
  324. void MarkRegionAsWritten(const CacheAddr start, const CacheAddr end) {
  325. u64 page_start = start >> write_page_bit;
  326. const u64 page_end = end >> write_page_bit;
  327. while (page_start <= page_end) {
  328. auto it = written_pages.find(page_start);
  329. if (it != written_pages.end()) {
  330. it->second = it->second + 1;
  331. } else {
  332. written_pages[page_start] = 1;
  333. }
  334. page_start++;
  335. }
  336. }
  337. void UnmarkRegionAsWritten(const CacheAddr start, const CacheAddr end) {
  338. u64 page_start = start >> write_page_bit;
  339. const u64 page_end = end >> write_page_bit;
  340. while (page_start <= page_end) {
  341. auto it = written_pages.find(page_start);
  342. if (it != written_pages.end()) {
  343. if (it->second > 1) {
  344. it->second = it->second - 1;
  345. } else {
  346. written_pages.erase(it);
  347. }
  348. }
  349. page_start++;
  350. }
  351. }
  352. bool IsRegionWritten(const CacheAddr start, const CacheAddr end) const {
  353. u64 page_start = start >> write_page_bit;
  354. const u64 page_end = end >> write_page_bit;
  355. while (page_start <= page_end) {
  356. if (written_pages.count(page_start) > 0) {
  357. return true;
  358. }
  359. page_start++;
  360. }
  361. return false;
  362. }
  363. VideoCore::RasterizerInterface& rasterizer;
  364. Core::System& system;
  365. std::unique_ptr<StreamBuffer> stream_buffer;
  366. TBufferType stream_buffer_handle{};
  367. bool invalidated = false;
  368. u8* buffer_ptr = nullptr;
  369. u64 buffer_offset = 0;
  370. u64 buffer_offset_base = 0;
  371. using IntervalSet = boost::icl::interval_set<CacheAddr>;
  372. using IntervalCache = boost::icl::interval_map<CacheAddr, MapInterval>;
  373. using IntervalType = typename IntervalCache::interval_type;
  374. IntervalCache mapped_addresses{};
  375. static constexpr u64 write_page_bit{11};
  376. std::unordered_map<u64, u32> written_pages{};
  377. static constexpr u64 block_page_bits{21};
  378. static constexpr u64 block_page_size{1 << block_page_bits};
  379. std::unordered_map<u64, TBuffer> blocks{};
  380. std::list<TBuffer> pending_destruction{};
  381. u64 epoch{};
  382. u64 modified_ticks{};
  383. std::recursive_mutex mutex;
  384. };
  385. } // namespace VideoCommon