buffer_cache.h 16 KB

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