summaryrefslogtreecommitdiffstats
path: root/src/video_core/buffer_cache/buffer_cache.h
blob: e36f85705f2d39fd827fe7189cea62d69778d74f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// Copyright 2019 yuzu Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#pragma once

#include <array>
#include <memory>
#include <mutex>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#include "common/alignment.h"
#include "common/common_types.h"
#include "core/core.h"
#include "video_core/buffer_cache/buffer_block.h"
#include "video_core/buffer_cache/map_interval.h"
#include "video_core/memory_manager.h"

namespace VideoCore {
class RasterizerInterface;
}

namespace VideoCommon {

template <typename TBuffer, typename TBufferType, typename StreamBuffer>
class BufferCache {
public:
    using BufferInfo = std::pair<const TBufferType*, u64>;

    BufferInfo UploadMemory(GPUVAddr gpu_addr, std::size_t size, std::size_t alignment = 4,
                            bool is_written = false) {
        std::lock_guard lock{mutex};

        auto& memory_manager = system.GPU().MemoryManager();
        const auto host_ptr = memory_manager.GetPointer(gpu_addr);
        if (!host_ptr) {
            return {GetEmptyBuffer(size), 0};
        }
        const auto cache_addr = ToCacheAddr(host_ptr);

        auto block = GetBlock(cache_addr, size);
        MapAddress(block, gpu_addr, cache_addr, size);

        const u64 offset = static_cast<u64>(block->GetOffset(cache_addr));

        return {ToHandle(block), offset};
    }

    /// Uploads from a host memory. Returns the OpenGL buffer where it's located and its offset.
    BufferInfo UploadHostMemory(const void* raw_pointer, std::size_t size,
                                std::size_t alignment = 4) {
        std::lock_guard lock{mutex};
        return StreamBufferUpload(raw_pointer, size, alignment);
    }

    void Map(std::size_t max_size) {
        std::tie(buffer_ptr, buffer_offset_base, invalidated) = stream_buffer->Map(max_size, 4);
        buffer_offset = buffer_offset_base;
    }

    /// Finishes the upload stream, returns true on bindings invalidation.
    bool Unmap() {
        stream_buffer->Unmap(buffer_offset - buffer_offset_base);
        return std::exchange(invalidated, false);
    }

    void TickFrame() {
        ++epoch;
        while (!pending_destruction.empty()) {
            if (pending_destruction.front()->GetEpoch() + 1 > epoch) {
                break;
            }
            pending_destruction.pop_front();
        }
    }

    /// Write any cached resources overlapping the specified region back to memory
    void FlushRegion(CacheAddr addr, std::size_t size) {
        std::lock_guard lock{mutex};

        // TODO
    }

    /// Mark the specified region as being invalidated
    void InvalidateRegion(CacheAddr addr, u64 size) {
        std::lock_guard lock{mutex};

        std::vector<MapInterval> objects = GetMapsInRange(addr, size);
        for (auto& object : objects) {
            Unregister(object);
        }
    }

    virtual const TBufferType* GetEmptyBuffer(std::size_t size) = 0;

protected:
    explicit BufferCache(VideoCore::RasterizerInterface& rasterizer, Core::System& system,
                         std::unique_ptr<StreamBuffer> stream_buffer)
        : rasterizer{rasterizer}, system{system}, stream_buffer{std::move(stream_buffer)},
          stream_buffer_handle{this->stream_buffer->GetHandle()} {}

    ~BufferCache() = default;

    virtual const TBufferType* ToHandle(const TBuffer& storage) = 0;

    virtual void WriteBarrier() = 0;

    virtual TBuffer CreateBlock(CacheAddr cache_addr, std::size_t size) = 0;

    virtual void UploadBlockData(const TBuffer& buffer, std::size_t offset, std::size_t size,
                                 const u8* data) = 0;

    virtual void DownloadBlockData(const TBuffer& buffer, std::size_t offset, std::size_t size,
                                   u8* data) = 0;

    virtual void CopyBlock(const TBuffer& src, const TBuffer& dst, std::size_t src_offset,
                           std::size_t dst_offset, std::size_t size) = 0;

    /// Register an object into the cache
    void Register(const MapInterval& new_interval, const GPUVAddr gpu_addr) {
        const CacheAddr cache_ptr = new_interval.start;
        const std::size_t size = new_interval.end - new_interval.start;
        const std::optional<VAddr> cpu_addr =
            system.GPU().MemoryManager().GpuToCpuAddress(gpu_addr);
        if (!cache_ptr || !cpu_addr) {
            LOG_CRITICAL(HW_GPU, "Failed to register buffer with unmapped gpu_address 0x{:016x}",
                         gpu_addr);
            return;
        }
        const IntervalType interval{new_interval.start, new_interval.end};
        mapped_addresses.insert(interval);
        map_storage[new_interval] = MapInfo{gpu_addr, *cpu_addr};

        rasterizer.UpdatePagesCachedCount(*cpu_addr, size, 1);
    }

    /// Unregisters an object from the cache
    void Unregister(const MapInterval& interval) {
        const MapInfo info = map_storage[interval];
        const std::size_t size = interval.end - interval.start;
        rasterizer.UpdatePagesCachedCount(info.cpu_addr, size, -1);
        const IntervalType delete_interval{interval.start, interval.end};
        mapped_addresses.erase(delete_interval);
        map_storage.erase(interval);
    }

private:
    void MapAddress(const TBuffer& block, const GPUVAddr gpu_addr, const CacheAddr cache_addr,
                    const std::size_t size) {

        std::vector<MapInterval> overlaps = GetMapsInRange(cache_addr, size);
        if (overlaps.empty()) {
            const CacheAddr cache_addr_end = cache_addr + size;
            MapInterval new_interval{cache_addr, cache_addr_end};
            u8* host_ptr = FromCacheAddr(cache_addr);
            UploadBlockData(block, block->GetOffset(cache_addr), size, host_ptr);
            Register(new_interval, gpu_addr);
            return;
        }

        const CacheAddr cache_addr_end = cache_addr + size;
        if (overlaps.size() == 1) {
            const MapInterval& current_map = overlaps[0];
            if (current_map.IsInside(cache_addr, cache_addr_end)) {
                return;
            }
        }
        CacheAddr new_start = cache_addr;
        CacheAddr new_end = cache_addr_end;
        // Calculate new buffer parameters
        for (auto& overlap : overlaps) {
            new_start = std::min(overlap.start, new_start);
            new_end = std::max(overlap.end, new_end);
        }
        GPUVAddr new_gpu_addr = gpu_addr + new_start - cache_addr;
        for (auto& overlap : overlaps) {
            Unregister(overlap);
        }
        UpdateBlock(block, new_start, new_end, overlaps);
        MapInterval new_interval{new_start, new_end};
        Register(new_interval, new_gpu_addr);
    }

    void UpdateBlock(const TBuffer& block, CacheAddr start, CacheAddr end,
                     std::vector<MapInterval>& overlaps) {
        const IntervalType base_interval{start, end};
        IntervalCache interval_set{};
        interval_set.add(base_interval);
        for (auto& overlap : overlaps) {
            const IntervalType subtract{overlap.start, overlap.end};
            interval_set.subtract(subtract);
        }
        for (auto& interval : interval_set) {
            std::size_t size = interval.upper() - interval.lower();
            if (size > 0) {
                u8* host_ptr = FromCacheAddr(interval.lower());
                UploadBlockData(block, block->GetOffset(interval.lower()), size, host_ptr);
            }
        }
    }

    std::vector<MapInterval> GetMapsInRange(CacheAddr addr, std::size_t size) {
        if (size == 0) {
            return {};
        }

        std::vector<MapInterval> objects{};
        const IntervalType interval{addr, addr + size};
        for (auto& pair : boost::make_iterator_range(mapped_addresses.equal_range(interval))) {
            objects.emplace_back(pair.lower(), pair.upper());
        }

        return objects;
    }

    /// Returns a ticks counter used for tracking when cached objects were last modified
    u64 GetModifiedTicks() {
        return ++modified_ticks;
    }

    BufferInfo StreamBufferUpload(const void* raw_pointer, std::size_t size,
                                  std::size_t alignment) {
        AlignBuffer(alignment);
        const std::size_t uploaded_offset = buffer_offset;
        std::memcpy(buffer_ptr, raw_pointer, size);

        buffer_ptr += size;
        buffer_offset += size;
        return {&stream_buffer_handle, uploaded_offset};
    }

    void AlignBuffer(std::size_t alignment) {
        // Align the offset, not the mapped pointer
        const std::size_t offset_aligned = Common::AlignUp(buffer_offset, alignment);
        buffer_ptr += offset_aligned - buffer_offset;
        buffer_offset = offset_aligned;
    }

    TBuffer EnlargeBlock(TBuffer buffer) {
        const std::size_t old_size = buffer->GetSize();
        const std::size_t new_size = old_size + block_page_size;
        const CacheAddr cache_addr = buffer->GetCacheAddr();
        TBuffer new_buffer = CreateBlock(cache_addr, new_size);
        CopyBlock(buffer, new_buffer, 0, 0, old_size);
        buffer->SetEpoch(epoch);
        pending_destruction.push_back(buffer);
        const CacheAddr cache_addr_end = cache_addr + new_size - 1;
        u64 page_start = cache_addr >> block_page_bits;
        const u64 page_end = cache_addr_end >> block_page_bits;
        while (page_start <= page_end) {
            blocks[page_start] = new_buffer;
            ++page_start;
        }
        return new_buffer;
    }

    TBuffer MergeBlocks(TBuffer first, TBuffer second) {
        const std::size_t size_1 = first->GetSize();
        const std::size_t size_2 = second->GetSize();
        const CacheAddr first_addr = first->GetCacheAddr();
        const CacheAddr second_addr = second->GetCacheAddr();
        const CacheAddr new_addr = std::min(first_addr, second_addr);
        const std::size_t new_size = size_1 + size_2;
        TBuffer new_buffer = CreateBlock(new_addr, new_size);
        CopyBlock(first, new_buffer, 0, new_buffer->GetOffset(first_addr), size_1);
        CopyBlock(second, new_buffer, 0, new_buffer->GetOffset(second_addr), size_2);
        first->SetEpoch(epoch);
        second->SetEpoch(epoch);
        pending_destruction.push_back(first);
        pending_destruction.push_back(second);
        const CacheAddr cache_addr_end = new_addr + new_size - 1;
        u64 page_start = new_addr >> block_page_bits;
        const u64 page_end = cache_addr_end >> block_page_bits;
        while (page_start <= page_end) {
            blocks[page_start] = new_buffer;
            ++page_start;
        }
        return new_buffer;
    }

    TBuffer GetBlock(const CacheAddr cache_addr, const std::size_t size) {
        TBuffer found{};
        const CacheAddr cache_addr_end = cache_addr + size - 1;
        u64 page_start = cache_addr >> block_page_bits;
        const u64 page_end = cache_addr_end >> block_page_bits;
        const u64 num_pages = page_end - page_start + 1;
        while (page_start <= page_end) {
            auto it = blocks.find(page_start);
            if (it == blocks.end()) {
                if (found) {
                    found = EnlargeBlock(found);
                } else {
                    const CacheAddr start_addr = (page_start << block_page_bits);
                    found = CreateBlock(start_addr, block_page_size);
                    blocks[page_start] = found;
                }
            } else {
                if (found) {
                    if (found == it->second) {
                        ++page_start;
                        continue;
                    }
                    found = MergeBlocks(found, it->second);
                } else {
                    found = it->second;
                }
            }
            ++page_start;
        }
        return found;
    }

    std::unique_ptr<StreamBuffer> stream_buffer;
    TBufferType stream_buffer_handle{};

    bool invalidated = false;

    u8* buffer_ptr = nullptr;
    u64 buffer_offset = 0;
    u64 buffer_offset_base = 0;

    using IntervalCache = boost::icl::interval_set<CacheAddr>;
    using IntervalType = typename IntervalCache::interval_type;
    IntervalCache mapped_addresses{};
    std::unordered_map<MapInterval, MapInfo> map_storage;

    static constexpr u64 block_page_bits{24};
    static constexpr u64 block_page_size{1 << block_page_bits};
    std::unordered_map<u64, TBuffer> blocks;

    std::list<TBuffer> pending_destruction;
    u64 epoch{};
    u64 modified_ticks{};
    VideoCore::RasterizerInterface& rasterizer;
    Core::System& system;
    std::recursive_mutex mutex;
};

} // namespace VideoCommon