Debian Codegraph @

Source/Core/DiscIO/CachedBlob.cpp

raw symbols SCIP
1 // Copyright 2025 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "DiscIO/CachedBlob.h"
5
6 #include <atomic>
7 #include <chrono>
8 #include <thread>
9
10 #include "Common/CommonTypes.h"
11 #include "Common/Logging/Log.h"
12 #include "Common/MemArena.h"
13
14 #include "DiscIO/DiscScrubber.h"
15 #include "DiscIO/Volume.h"
16
17 namespace DiscIO
18 {
19 class CacheFiller final
20 {
21 public:
22 explicit CacheFiller(std::unique_ptr<BlobReader> reader, bool attempt_to_scrub)
23 : m_thread{&CacheFiller::ThreadFunc, this, std::move(reader), attempt_to_scrub}
24 {
25 }
26
27 ~CacheFiller()
28 {
29 m_stop_thread.store(true, std::memory_order_relaxed);
30 m_thread.join();
31 }
32
33 bool Read(u64 offset, u64 size, u8* out_ptr)
34 {
35 if (size == 0)
36 {
37 // Just return early to safely handle a read of zero if that were to happen.
38 // This avoids a m_memory_region_data initialization race.
39 return true;
40 }
41
42 switch (GetCacheState(offset, size))
43 {
44 case CacheState::Cached:
45 std::memcpy(out_ptr, m_memory_region_data + offset, size);
46 return true;
47
48 case CacheState::Scrubbed:
49 WARN_LOG_FMT(DISCIO,
50 "CachedBlobReader: Read({}, {}) hits a scrubbed cluster which is not cached.",
51 offset, size);
52 return false;
53
54 default:
55 return false;
56 }
57 }
58
59 private:
60 enum class CacheState
61 {
62 Cached,
63 NotCached,
64 Scrubbed,
65 };
66
67 CacheState GetCacheState(u64 offset, u64 size)
68 {
69 const auto cache_pos = m_cache_filled_pos.load(std::memory_order_acquire);
70
71 const auto end_pos = offset + size;
72 if (end_pos > cache_pos)
73 return CacheState::NotCached;
74
75 for (u64 i = offset; i < end_pos; i += DiscScrubber::CLUSTER_SIZE)
76 {
77 if (m_scrubber.CanBlockBeScrubbed(i))
78 return CacheState::Scrubbed;
79 }
80
81 return CacheState::Cached;
82 }
83
84 void ThreadFunc(std::unique_ptr<BlobReader> reader, bool attempt_to_scrub)
85 {
86 static constexpr auto PERIODIC_LOG_TIME = std::chrono::seconds{1};
87
88 const auto start_time = Clock::now();
89 const u64 total_size = reader->GetDataSize();
90
91 m_memory_region_data = static_cast<u8*>(m_memory_region.Create(total_size));
92 if (m_memory_region_data == nullptr)
93 {
94 ERROR_LOG_FMT(DISCIO, "CachedBlobReader: Failed to create memory region.");
95 return;
96 }
97
98 // Returns CLUSTER_SIZE or smaller at the end of the file.
99 const auto get_read_size = [&](u64 pos) {
100 return std::min<u64>(total_size - pos, DiscScrubber::CLUSTER_SIZE);
101 };
102
103 // Used for periodic progress logging.
104 u64 total_bytes_to_commit = total_size;
105
106 if (attempt_to_scrub)
107 {
108 const auto volume = CreateVolume(reader->CopyReader());
109 if (volume != nullptr && m_scrubber.SetupScrub(*volume))
110 {
111 for (u64 i = 0; i < total_size; i += DiscScrubber::CLUSTER_SIZE)
112 {
113 if (m_scrubber.CanBlockBeScrubbed(i))
114 total_bytes_to_commit -= get_read_size(i);
115 }
116 }
117 else
118 {
119 WARN_LOG_FMT(DISCIO, "CachedBlobReader: Failed to scrub. The entire file will be cached.");
120 }
121 }
122
123 auto next_log_time = start_time + PERIODIC_LOG_TIME;
124 u64 read_offset = 0;
125 u64 committed_count = 0;
126
127 while (true)
128 {
129 if (m_stop_thread.load(std::memory_order_relaxed))
130 {
131 INFO_LOG_FMT(DISCIO, "CachedBlobReader: Stopped");
132 break;
133 }
134
135 const auto read_size = get_read_size(read_offset);
136 if (read_size == 0)
137 {
138 const auto total_time = DT_s{Clock::now() - start_time}.count();
139
140 static constexpr auto mib_scale = double(1 << 20);
141
142 NOTICE_LOG_FMT(
143 DISCIO, "CachedBlobReader: Completed. Cached {:.2f} of {:.2f} MiB in {:.2f} seconds.",
144 committed_count / mib_scale, total_size / mib_scale, total_time);
145 break;
146 }
147
148 if (!m_scrubber.CanBlockBeScrubbed(read_offset))
149 {
150 m_memory_region.EnsureMemoryPagesWritable(read_offset, read_size);
151
152 if (!reader->Read(read_offset, read_size, m_memory_region_data + read_offset))
153 {
154 ERROR_LOG_FMT(DISCIO, "CachedBlobReader: Read({}, {}) failed.", read_offset, read_size);
155 break;
156 }
157
158 committed_count += read_size;
159 }
160
161 read_offset += read_size;
162 m_cache_filled_pos.store(read_offset, std::memory_order_release);
163
164 if (const auto now = Clock::now(); now >= next_log_time)
165 {
166 INFO_LOG_FMT(DISCIO, "CachedBlobReader: Progress: {}%",
167 committed_count * 100 / total_bytes_to_commit);
168 next_log_time = now + PERIODIC_LOG_TIME;
169 }
170 }
171 }
172
173 // The thread has read non-scrubbed bytes into memory up to this point.
174 std::atomic<u64> m_cache_filled_pos{};
175
176 Common::LazyMemoryRegion m_memory_region;
177 u8* m_memory_region_data{};
178
179 DiscScrubber m_scrubber;
180
181 std::atomic_bool m_stop_thread{};
182 std::thread m_thread;
183 };
184
185 class CachedBlobReader final : public BlobReader
186 {
187 public:
188 explicit CachedBlobReader(std::unique_ptr<BlobReader> reader, bool attempt_to_scrub)
189 : m_cache_filler{std::make_shared<CacheFiller>(reader->CopyReader(), attempt_to_scrub)},
190 m_reader{std::move(reader)}
191
192 {
193 INFO_LOG_FMT(DISCIO, "CachedBlobReader: Created");
194 }
195
196 CachedBlobReader(std::shared_ptr<CacheFiller> cache_filler, std::unique_ptr<BlobReader> reader)
197 : m_cache_filler{std::move(cache_filler)}, m_reader{std::move(reader)}
198 {
199 INFO_LOG_FMT(DISCIO, "CachedBlobReader: Copied");
200 }
201
202 std::unique_ptr<BlobReader> CopyReader() const override
203 {
204 return std::make_unique<CachedBlobReader>(m_cache_filler, m_reader->CopyReader());
205 }
206
207 BlobType GetBlobType() const override { return m_reader->GetBlobType(); }
208 u64 GetRawSize() const override { return GetDataSize(); }
209 u64 GetDataSize() const override { return m_reader->GetDataSize(); }
210 DataSizeType GetDataSizeType() const override { return m_reader->GetDataSizeType(); }
211
212 u64 GetBlockSize() const override { return 0; }
213 bool HasFastRandomAccessInBlock() const override { return true; }
214 std::string GetCompressionMethod() const override { return {}; }
215 std::optional<int> GetCompressionLevel() const override { return std::nullopt; }
216
217 bool Read(u64 offset, u64 size, u8* out_ptr) override
218 {
219 return m_cache_filler->Read(offset, size, out_ptr) || m_reader->Read(offset, size, out_ptr);
220 }
221
222 bool IsCached() const override { return true; }
223
224 private:
225 // A shared object does the cache filling for sensible CopyReader behavior.
226 const std::shared_ptr<CacheFiller> m_cache_filler;
227
228 const std::unique_ptr<BlobReader> m_reader;
229 };
230
231 std::unique_ptr<BlobReader> CreateCachedBlobReader(std::unique_ptr<BlobReader> reader)
232 {
233 if (reader->IsCached()) // This is already CachedBlobReader.
234 return reader;
235
236 return std::make_unique<CachedBlobReader>(std::move(reader), false);
237 }
238
239 std::unique_ptr<BlobReader> CreateScrubbingCachedBlobReader(std::unique_ptr<BlobReader> reader)
240 {
241 if (reader->IsCached()) // This reader is already a CachedBlobReader.
242 return reader;
243
244 return std::make_unique<CachedBlobReader>(std::move(reader), true);
245 }
246
247 } // namespace DiscIO