Skip to content

Runtime: buffer_at finds a buffer by binary search, not a scan of every resource - #2823

Merged
ItsNotRexed merged 4 commits into
ItsNotRexed:mainfrom
jsthope:perf/buffer-at-va-map
Nov 23, 2026
Merged

ItsNotRexed merged 4 commits into
ItsNotRexed:mainfrom
jsthope:perf/buffer-at-va-map

Conversation

@jsthope

@jsthope jsthope commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Item: D3D-322 (claimed in #2516)

VulkanContext::buffer_at walked every registered resource, images included, for each vertex-buffer slot, index
buffer and WriteBufferImmediate of every draw (runtime/src/vulkan_backend.h). Its own comment and the "Lookups"
known gap in docs/d3d12_vulkan.md already asked for an ordered map by VA once it showed.

Changes

  • runtime/src/buffer_va_index.h (new): BufferVaIndex, buffers' VA ranges in a std::map keyed by first VA. A
    lookup is a binary search that walks down from the nearest start only while a range can still reach the VA (bounded
    by the longest range). Standard library only, no Vulkan.
  • VulkanContext keeps it in step with resources_ in add_resource (both overloads), add_sparse_buffer and
    remove_resource; a re-registered ID drops its old range first. Indexed buffers are what the scan accepted: no
    image, a VkBuffer, a VA and a non-zero size.
  • docs/d3d12_vulkan.md: the "Lookups" known gap is gone; the WriteBufferImmediate paragraph says how the lookup
    works now.

Behaviour change

Placed buffers may alias, so ranges can overlap. The scan returned whichever matched first in unordered_map order;
the index returns the range that starts closest below the VA (the larger ID on a tie), every time. Buffer and offset
are the same when the aliasing buffers share the arena; only the size cut can differ.

Tests

  • buffer_va_index_test (new, CPU only, in CTest): edges, overlapping and nested ranges, same start, erase and
    re-registration, then 200 random tables checked against a linear scan with the same rule.
  • Full runtime build and ctest on top of ec8ec4c9: 113/113 passed (the skipped tests skip on main too: missing
    data or tools), including d3d12_vulkan_device, which goes through VulkanContext.
  • Lookup time, half the resources images (buffer_va_index_test --bench):
Resources Scan (before) Index
1 000 1.7 µs 43 ns ×41
10 000 44 µs 115 ns ×381
100 000 2.9 ms 165 ns ×17 590

Not measured with replay_cpu_bench as the claim said: its frame on main has no draws yet (#2123 adds them).

Windows 11, MSVC (Visual Studio 18), NVIDIA GeForce RTX 3060 Ti, driver 32.0.15.9186. No game files.

Checklist

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (Not applicable: no translator change.)

AI-assisted

Buffers' VA ranges kept in a std::map by first VA: a lookup is a binary
search, walking down from the nearest start only while a range can still
reach the VA (bounded by the longest range), so aliasing placed buffers
that overlap still resolve, to the range that starts closest below the VA
(the larger ID on a tie).

buffer_va_index_test checks edges, overlapping and nested ranges,
re-registration and erase, then 200 random tables against a linear scan
with the same rule, and prints the lookup time against the scan over every
resource that buffer_at does today (--bench for 50k and 100k resources).
…ry resource

VulkanContext::buffer_at walked every registered resource, images included,
for each vertex-buffer slot, index buffer and WriteBufferImmediate of every
draw. It now asks a BufferVaIndex of the addressable buffers (no image, a
VkBuffer, a VA and bytes: what the scan accepted), kept in step with
resources_ by add_resource, add_sparse_buffer and remove_resource; a
re-registered ID drops its old range first.

Where placed buffers alias, the scan returned whichever matched first in
unordered_map order; the index returns the range that starts closest below
the VA. docs/d3d12_vulkan.md drops the "Lookups" known gap.

@kacper-serewis kacper-serewis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independently tested df1ae87 on Windows with clang++ and synthetic Vulkan handles. A standalone harness called the actual VulkanContext replay buffer_at callback after each of 12 registration, replacement and removal operations. All 3,456 probes agreed with a separate linear reference on hit/miss and, for hits, VkBuffer, offset and clipped size. Cases included sparse registration, same-start and nested aliases, fallback after removal, same-ID relocation, buffer-to-image replacement, VA reuse, empty ranges, and addresses through UINT64_MAX. CPU only, no game files or GPU submission. No timing measurements. AI-assisted review.

@tupacfan04

Copy link
Copy Markdown
Contributor

Code read of df1ae87e (I didn't build it). Looks right. The only places resources_ is written are set_resource_locked (try_emplace, or unindex the old binding then overwrite) and the single erase in remove_resource, which unindexes first, so the VA index can't drift from the map. addressable() is exactly the old scan's filter. In find, the early offset >= longest_ exit is sound because longest_ is an upper bound on every range and only ever grows. It can make a miss walk further after large buffers are freed, but never gives a wrong hit. The one behaviour change is for aliased (overlapping) placed buffers: the old loop returned whichever matching entry unordered_map iteration reached first, and this returns the nearest start below (larger id on a tie). That's deterministic, so it's an improvement.

AI-assisted review (Claude Code).

@padhossein

Copy link
Copy Markdown
Contributor

Independent VA-index churn check (df1ae87e). The fixed cases and all 200 random tables agree with the scan on Linux/C++20. I also measured a case where the documented stale longest_ bound matters: two indexes with the same 20,000 disjoint 256-byte buffers, with a temporary 1 GiB overlapping range added and then removed in one index. After removal, misses one stride past the final buffer were about 64–78 ns each in the fresh index and 418–481 microseconds each in the previously enlarged index (three local runs). Results are correct, but the miss still walks the whole table even after the large buffer is gone. Consider updating the bound when the largest range is removed, or documenting that the miss path can retain this cost after transient large allocations.

AI-assisted (Codex).

The bound that stops a lookup's walk only grew: once a large buffer was
freed, every later miss still walked back as far as that buffer had
reached. With 20 000 buffers of 256 bytes, a 1 GiB range added then
removed left a miss past the last buffer at 250-600 us instead of ~50 ns
(found by @padhossein in review of ItsNotRexed#2823).

A multiset of the indexed sizes keeps the bound at the longest range
indexed now; insert and erase stay O(log n), find is unchanged. Inserting
the same (va, id) again replaces its size instead of leaving the old one
in the bound.

buffer_va_index_test checks the bound after erases (same sizes and a
smaller re-registration included), against the longest live range in all
200 random tables, and times the review's miss-after-free case.
@jsthope

jsthope commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

@padhossein thanks, fixed in 111b634c: the bound now follows the live ranges instead of only growing.

  • BufferVaIndex keeps a std::multiset of the indexed sizes, so longest_ is the longest range indexed now (0 when the index is empty). insert and erase stay O(log n) and find is unchanged. Inserting the same (va, id) again replaces its size instead of leaving the old one in the bound.
  • buffer_va_index_test now checks the bound after erases, including two ranges of the same size and a re-registration with a smaller size. It also compares longest() with the longest live range in all 200 random tables, and times your case: 20 000 buffers of 256 bytes, a 1 GiB range added then removed, then a miss one stride past the last buffer.
Miss past 20 000 buffers Fresh index After a freed 1 GiB range
df1ae87e 51-66 ns 251-595 µs (3 runs)
111b634c 45-97 ns 45-47 ns

The bound checks fail on df1ae87e (4 failures) and pass on 111b634c.

One limit remains, and the header comment now says so: while a large range is still live, a miss walks every start within that range below the VA. For example, a buffer that covers a whole heap with placed buffers inside it. That walk is never longer than the old scan over every resource, images included. Only an interval tree would remove it, and that can be a follow-up if a real frame shows it.

Tested on 111b634c: full runtime build and ctest, 113/113 passed (the skipped tests skip on main too), including buffer_va_index and d3d12_vulkan_device. Windows 11, MSVC 14.50 (Visual Studio 18), NVIDIA GeForce RTX 3060 Ti, driver 32.0.15.9186. Vulkan headers came from -DLEONIDA_VULKAN_HEADERS_FETCH=ON. No game files.

AI-assisted (Claude Code).

@Kam471 Kam471 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at head df1ae87e; the branch merges cleanly with current main and the diff is limited to the buffer index, its test, docs and CMake. Inspection found a correct ordered index: (va, id) ordering, upper_bound({va, max_id}) then walk back, nearest start wins, larger ID wins on ties, and offset >= longest_ is a safe early exit. The test covers null/zero skip, first/last byte, one-past-end, gaps, highest VA, nested and same-start aliases, erase/refill, plus 200x2000 randomized comparisons against a linear scan. No game data or host paths. Approve.

Not built here (no configured build dir in the worktree), so this is inspection-only. Non-blocking: longest_ is only recomputed when the index empties, so removing the longest range makes later misses walk every entry; that edge is untested.

@traeb0n

traeb0n commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Code review of 111b634 (read only, no runs): looks right to me.

What I checked:

  • The index can't go stale. Every write to resources_ in vulkan_backend.h now goes through set_resource_locked. Re-registering an ID unindexes its old range first, and remove_resource unindexes before erasing. Nothing else assigns into resources_ or edits a binding's va/size in place (I grepped the branch for both).
  • Locking: find is const and runs under the shared resource_mutex_ that prepare holds. insert/erase only run under the unique lock, as before.
  • addressable() accepts exactly what the old scan did: no image, a VkBuffer, a VA and a size.
  • The longest_ bound is right after erases: the multiset keeps one entry per range, and drop_size removes one copy.
  • Overlaps are now deterministic: the closest start below wins, then the larger ID. The old scan returned whichever buffer unordered_map iterated first.

One suggestion, not blocking, about that overlap rule. With placed buffers aliasing in one heap, say a big buffer B at heap offset 0 and a small S inside it, a vertex view that starts in S but runs past S's end will resolve to S, because S starts closer. The view is then cut at S's end, and the rest reads as out of bounds (zeros), even though B holds all of it. buffer_at gets the requested size, so find could prefer, among the ranges that hold va, one that also holds va + size, and fall back to the closest otherwise. The old code had the same exposure, only in hash order, so this PR doesn't make anything worse.

One note on measuring: replay_cpu_bench has its own buffer_at lambda over a single arena, so its draw rows won't show this change. The gain is in VulkanContext with many live resources, where the old scan visited every image and buffer for each vertex and index view.

AI-assisted (Claude Code).

With placed buffers aliasing in one heap, a large buffer B and a small S
inside it, a vertex or index view that starts in S and runs past its end
resolved to S, the closest start below the VA, and buffer_at cut it at
S's end: the rest read as out of bounds, though B holds all of it. Found
by traeb0n in the review of ItsNotRexed#2823.

BufferVaIndex::find takes the bytes the lookup needs and returns, among
the ranges that hold the VA, the closest start (larger ID on a tie) that
also holds all of them; when none does, the closest that holds the VA,
as before. Without overlaps the first range it looks at is still the
answer. With a fallback found, the walk stops once no range can hold all
the bytes, bounded by the longest live range. buffer_at passes the
requested size.

buffer_va_index_test checks views that fit in the small buffer, run past
it into the large one, run past every range and have size 0, and three
quarters of the random-table lookups now name a view of up to 32 KiB,
checked against a scan with the same rule.
@jsthope

jsthope commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

@traeb0n thanks for the review, and good catch on the aliasing case. I'd add one thing to "this PR doesn't make anything worse": the old scan picked B or S in hash order, so that view was sometimes right, while the nearest-start rule picks S every time. Deterministic, but that case is now wrong every time, so it was worth fixing here rather than in a follow-up.

Done in b8273c0, as you suggested:

  • BufferVaIndex::find(va, hit, bytes): among the ranges that hold va, it returns the closest start (larger ID on a tie) that also holds [va, va + bytes). When none does, it returns the closest one that holds va, as before. buffer_at passes the requested size, so a view that starts in S and runs past it now resolves to B and isn't cut.
  • Cost: without overlaps the first range looked at is still the answer. Once a fallback is found, the walk stops as soon as no range can hold all the bytes (bytes > longest_ - offset), so the extra walking only happens when ranges alias and is bounded by the longest live range, the same bound a miss already had.
  • buffer_va_index_test: new fixed cases (a view that fits in S stays in S, one byte past S goes to B, a view no range holds falls back to the closest start, size 0 counts as one byte). In the 200 random tables, three quarters of the lookups now name a view of up to 32 KiB, checked against a scan with the same rule.

Tested on b8273c0: full runtime build and ctest, 113/113 passed (gameinput disabled as on main). buffer_va_index_test --bench: 37 ns at 1 000 resources, 75 ns at 100 000, unchanged from before. The miss after a freed 1 GiB range is still 48 ns. Windows 11, MSVC (Visual Studio 18), Vulkan headers from -DLEONIDA_VULKAN_HEADERS_FETCH=ON, CPU only. No game files.

Agreed on replay_cpu_bench: its own buffer_at over one arena won't show this, which is why the PR measures with the standalone bench.

AI-assisted (Claude Code).

@dcastell1

Copy link
Copy Markdown
Contributor

Tested b8273c0 on RTX 5090, 621.24, Windows 11: pass. Built buffer_va_index_test from this tree and ran ctest -R buffer_va_index → 1/1 passed (0.52 s).

Swapping the linear scan for a binary search over the VA ranges is the kind of change that needs exactly this: a test that pins the found/not-found edges, since a wrong comparator only shows up as a missing buffer at runtime.

@ItsNotRexed
ItsNotRexed merged commit 6b38929 into ItsNotRexed:main Nov 23, 2026
2 of 4 checks passed
@emirduran707

Copy link
Copy Markdown
Contributor

Independent Windows check of the merged change (BUILD-821, claim): the real VulkanContext replay buffer_at callback against a linear reference, with synthetic Vulkan handles and no driver. 0 mismatches in 8,942,128 lookups.

Tree: main 3faac557 (it has all three commits of this pull request: 454ae063, 111b634c, b8273c0e). Windows 11, MSVC 14.44 (Visual Studio 2022), Ninja, RelWithDebInfo. No GPU is used; the machine has an AMD Radeon RX 9060 XT. No game files.

How. A standalone program (below, not for the repository) builds a VulkanContext on a fake device, registers, replaces and removes resources only through the public members (add_resource, both overloads, add_sparse_buffer, remove_resource), and calls replay_.buffer_at after every step. The reference is a scan of the live bindings written from the rule in the comment of buffer_va_index.h (lines 8-11), not from find. A lookup counts as equal when hit or miss agree and, for a hit, VkBuffer, offset and the clipped size agree. After each step it probes every edge of every live range (one byte before, first, second, middle, last, one past the end, two past) with nine byte counts from 0 to UINT64_MAX.

Part Lookups Hits Mismatches
Lifetime reuse 1,953 882 0
Clipping and aliasing 1,463 1,103 0
High-VA boundaries 1,116 657 0
Random churn, 20 seeds x 400 operations 8,937,596 5,836,514 0
  • Lifetime reuse: a freed VA taken by another ID and buffer; one ID moved to another VA, made smaller, larger, turned into an image and back into a buffer; bindings that are not addressable (no VkBuffer, no VA, no bytes) that later become addressable; a sparse buffer; removing twice and removing an ID that never existed.
  • Clipping and aliasing: small placed buffers inside a heap-sized one, a nested one, two with the same start and size, one that runs past the large one's end; a view that grows byte by byte out of the small buffers into the large one; then the large one removed, and a 1 TiB range added and removed.
  • High-VA boundaries: a 1-byte buffer at VA 1; ranges across 2^32, 2^47, 2^48 and 2^63; a range that ends exactly at 2^64, one that ends at 2^64 - 1, the last byte alone, and a range whose end wraps past 2^64.
  • Random churn: 24 IDs over four address clusters (one at the top of the address space), mixing buffers, images, sparse buffers and bindings that are not addressable.

At the end, with everything removed, the index holds 0 ranges and its longest-range bound is 0.

The check can fail. With one deliberate fault at a time in the tree, the same program exits 1:

Fault Mismatches
find stops at half the longest range (offset >= longest_ / 2) 834,683
upper_bound({va, 0}) in place of {va, max_id()} 1,173,280
set_resource_locked does not unindex a re-registered ID's old range 6,543,295
buffer_at calls find(va, hit) without the byte count 375,713

With the files restored it is 0 again.

Also run: buffer_va_index_test built from the same tree: exit 0, "fixed cases and 200 random tables agree with the scan".

Not covered: concurrency (the callback runs under resource_mutex_; this program is single-threaded), a real driver, and the callers in vulkan_replay.h. To reach the private replay_ member the program defines private as public around the include, so it does not belong in the repository as it is.

AI-assisted (Claude Code).

The program (va_check_821.cpp)
// BUILD-821: an independent check of VulkanContext's replay buffer_at callback (#2823) on Windows, with synthetic
// Vulkan handles and no driver. Not part of the repository: built from a scratch worktree for the check only.
// It registers, replaces and removes resources through the public VulkanContext members and compares every lookup
// of the real callback with a linear reference written from the documented rule (buffer_va_index.h, lines 8-11).
#define _ALLOW_KEYWORD_MACROS 1
#define private public      // the callback lives in the private replay_ member; nothing else is touched
#include "../src/vulkan_backend.h"
#undef private

#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include <map>
#include <random>
#include <vector>

using namespace leonida;

namespace {

template<class T>
T handle(std::uintptr_t n) { return reinterpret_cast<T>(n); }

VkResult VKAPI_CALL nothing() { return VK_SUCCESS; }
PFN_vkVoidFunction VKAPI_CALL get(VkDevice, const char*) { return reinterpret_cast<PFN_vkVoidFunction>(nothing); }

// The reference: what is registered now, by ID, and a scan of all of it.
struct Reference {
    std::map<ResourceId, ResourceBinding> live;

    static bool addressable(const ResourceBinding& b) { return !b.image && b.buffer && b.va && b.size; }

    // Among the buffers that hold va: the one that starts closest below va (larger ID on a tie) and holds all of
    // [va, va + bytes); when none holds all of it, the closest one that holds va.
    bool find(std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset, std::uint64_t& size) const {
        const std::uint64_t want = bytes ? bytes : 1;
        const ResourceBinding* whole = nullptr;
        const ResourceBinding* part = nullptr;
        ResourceId whole_id = 0, part_id = 0;
        for (const auto& [id, b] : live) {
            if (!addressable(b) || va < b.va || va - b.va >= b.size) continue;
            const bool all = want <= b.size - (va - b.va);
            const ResourceBinding*& best = all ? whole : part;
            ResourceId& best_id = all ? whole_id : part_id;
            if (!best || b.va > best->va || (b.va == best->va && id > best_id)) {
                best = &b;
                best_id = id;
            }
        }
        const ResourceBinding* b = whole ? whole : part;
        if (!b) return false;
        buffer = b->buffer;
        offset = b->buffer_offset + (va - b->va);
        size = bytes < b->size - (va - b->va) ? bytes : b->size - (va - b->va);
        return true;
    }
};

struct Check {
    VulkanContext context{get, handle<VkDevice>(1), true};
    Reference ref;
    std::uint64_t probes = 0, hits = 0, mismatches = 0;

    void add(ResourceId id, const ResourceBinding& b) {
        context.add_resource(id, b);
        ref.live[id] = b;
    }
    void add_with_layout(ResourceId id, const ResourceBinding& b) {
        context.add_resource(id, b, VK_IMAGE_LAYOUT_UNDEFINED);
        ref.live[id] = b;
    }
    void add_sparse(ResourceId id, const ResourceBinding& b) {
        context.add_sparse_buffer(id, b, nullptr);
        ref.live[id] = b;
    }
    void remove(ResourceId id) {
        context.remove_resource(id);
        ref.live.erase(id);
    }

    bool probe(std::uint64_t va, std::uint64_t bytes, const char* where) {
        std::uint64_t got_size = bytes, want_size = 0;
        VkBuffer got_buffer = handle<VkBuffer>(0xdead), want_buffer = VK_NULL_HANDLE;
        VkDeviceSize got_offset = 0xdead, want_offset = 0;
        const bool got = context.replay_.buffer_at(va, got_size, got_buffer, got_offset);
        const bool want = ref.find(va, bytes, want_buffer, want_offset, want_size);
        ++probes;
        if (want) ++hits;
        const bool same = got == want && (!want || (got_buffer == want_buffer && got_offset == want_offset &&
                                                    got_size == want_size));
        if (!same) {
            if (mismatches++ < 12)
                std::printf("MISMATCH %s: va %016" PRIx64 " bytes %" PRIx64 ": callback %d %p +%" PRIx64 " size %" PRIx64
                            ", reference %d %p +%" PRIx64 " size %" PRIx64 "\n",
                            where, va, bytes, int(got), static_cast<void*>(got_buffer), std::uint64_t(got_offset),
                            got_size, int(want), static_cast<void*>(want_buffer), std::uint64_t(want_offset), want_size);
        }
        return same;
    }

    // Every edge of every live range, one byte either side, with byte counts that fit, clip and overflow.
    void probe_all(const char* where) {
        std::vector<std::uint64_t> vas = {0, 1, ~0ull, ~0ull - 1};
        for (const auto& [id, b] : ref.live) {
            if (!b.va) continue;
            const std::uint64_t end = b.va + b.size;  // may wrap: the probes below are still valid addresses
            for (std::uint64_t v : {b.va - 1, b.va, b.va + 1, b.va + b.size / 2, end - 1, end, end + 1}) vas.push_back(v);
        }
        for (std::uint64_t va : vas)
            for (std::uint64_t bytes : {0ull, 1ull, 2ull, 4ull, 0x100ull, 0x1000ull, 0x10000ull, 1ull << 32, ~0ull})
                probe(va, bytes, where);
    }
};

ResourceBinding buffer(std::uintptr_t vk_buffer, std::uint64_t va, std::uint64_t size, std::uint64_t at = 0) {
    ResourceBinding b;
    b.buffer = handle<VkBuffer>(vk_buffer);
    b.va = va;
    b.size = size;
    b.buffer_offset = at;
    return b;
}

ResourceBinding image(std::uintptr_t vk_image, std::uint64_t va = 0, std::uint64_t size = 0) {
    ResourceBinding b;
    b.image = handle<VkImage>(vk_image);
    b.format = VK_FORMAT_R8G8B8A8_UNORM;
    b.buffer = va ? handle<VkBuffer>(0x777) : VK_NULL_HANDLE;  // an image that also names a buffer is still no buffer
    b.va = va;
    b.size = size;
    return b;
}

void lifetime(Check& c) {
    const std::uint64_t base = 0x0000'0001'0000'0000ull;
    c.probe_all("empty context");
    c.add(1, buffer(0x10, base, 0x1000));
    c.probe_all("one buffer");
    c.remove(1);
    c.probe_all("removed again");
    c.add(2, buffer(0x20, base, 0x800, 0x40));          // another ID and buffer at the freed VA, shorter
    c.probe_all("VA reused by another ID");
    c.add(2, buffer(0x21, base + 0x4000, 0x1000));      // the same ID moves: its old range must be gone
    c.probe_all("ID re-registered at another VA");
    c.add(2, buffer(0x22, base + 0x4000, 0x200));       // same ID and VA, smaller
    c.probe_all("ID re-registered smaller");
    c.add(2, buffer(0x22, base + 0x4000, 0x4000));      // and larger
    c.probe_all("ID re-registered larger");
    c.add_with_layout(2, image(0x30, base + 0x4000, 0x4000));  // the ID becomes an image: not addressable any more
    c.probe_all("ID became an image");
    c.add(2, buffer(0x23, base + 0x4000, 0x100));       // and a buffer again
    c.probe_all("ID became a buffer again");
    c.add(3, buffer(0, base + 0x8000, 0x1000));         // no VkBuffer
    c.add(4, buffer(0x40, 0, 0x1000));                  // no VA
    c.add(5, buffer(0x50, base + 0x9000, 0));           // no bytes
    c.probe_all("bindings that are not addressable");
    c.add(3, buffer(0x31, base + 0x8000, 0x1000));      // each of them becomes addressable
    c.add(4, buffer(0x40, base + 0xa000, 0x1000));
    c.add(5, buffer(0x50, base + 0x9000, 0x1000));
    c.probe_all("they became addressable");
    c.add_sparse(6, buffer(0x60, base + 0x10000, 0x100000));
    c.probe_all("sparse buffer");
    c.remove(6);
    c.remove(6);                                        // twice, and an ID that never existed
    c.remove(99);
    c.probe_all("sparse buffer removed");
    for (ResourceId id : {ResourceId(2), ResourceId(3), ResourceId(4), ResourceId(5)}) c.remove(id);
    c.probe_all("all removed");
}

void clipping(Check& c) {
    const std::uint64_t base = 0x0000'0002'0000'0000ull;
    c.add(10, buffer(0x100, base, 0x10000, 0x1000));        // a heap-sized buffer
    c.add(11, buffer(0x100, base + 0x100, 0x100, 0x1100));  // small placed buffers that alias it
    c.add(12, buffer(0x100, base + 0x180, 0x40, 0x1180));   // nested in 11
    c.add(13, buffer(0x101, base + 0x100, 0x100, 0));       // same start and size as 11, another VkBuffer, larger ID
    c.add(14, buffer(0x102, base + 0xff00, 0x200));         // runs past the end of 10
    c.probe_all("aliasing buffers");
    for (std::uint64_t bytes = 0; bytes <= 0x240; bytes += 0x10)  // a view that grows out of 12, then 11/13, then 10
        for (std::uint64_t va : {base + 0x180, base + 0x1bf, base + 0x1ff, base + 0xffff, base + 0x100ff})
            c.probe(va, bytes, "growing view");
    c.remove(10);                                           // the big one goes: views are cut at the small ones
    c.probe_all("aliasing buffers without the large one");
    c.add(15, buffer(0x103, base, 1ull << 40));             // a very long range, then gone: later misses stay misses
    c.probe_all("very long range added");
    c.remove(15);
    c.probe_all("very long range removed");
    for (ResourceId id : {ResourceId(11), ResourceId(12), ResourceId(13), ResourceId(14)}) c.remove(id);
}

void high_va(Check& c) {
    c.add(20, buffer(0x200, 1, 1));                                 // the lowest address a buffer can have
    c.add(21, buffer(0x201, 0x0000'7fff'ffff'f000ull, 0x2000));     // across the 47-bit boundary
    c.add(22, buffer(0x202, 0x0000'ffff'ffff'f000ull, 0x2000));     // across the 48-bit boundary
    c.add(23, buffer(0x203, 0x0000'0000'ffff'f000ull, 0x2000));     // across 4 GiB
    c.add(24, buffer(0x204, 0x7fff'ffff'ffff'f000ull, 0x2000));     // across the sign bit
    c.add(25, buffer(0x205, 0xffff'ffff'ffff'f000ull, 0x1000));     // ends exactly at 2^64
    c.add(26, buffer(0x206, 0xffff'ffff'ffff'ff00ull, 0xff));       // ends at 2^64 - 1, nested in 25
    c.add(27, buffer(0x207, 0xffff'ffff'ffff'ffffull, 1));          // the last byte
    c.add(28, buffer(0x208, 0xffff'ffff'ffff'e000ull, 0x4000));     // its end wraps past 2^64
    c.probe_all("high addresses");
    c.remove(28);
    c.remove(25);
    c.probe_all("high addresses, two removed");
    for (ResourceId id = 20; id <= 27; ++id) c.remove(id);
    c.probe_all("high addresses removed");
}

void churn(Check& c, unsigned seed, unsigned operations) {
    std::mt19937_64 rng(seed);
    const std::uint64_t bases[] = {0x1000, 0x0000'0003'0000'0000ull, 0x0000'ffff'fff0'0000ull, 0xffff'ffff'fff0'0000ull};
    const std::uint64_t sizes[] = {1, 0x10, 0x100, 0x1000, 0x10000, 0xfffff, 0x100000};
    for (unsigned op = 0; op < operations; ++op) {
        const ResourceId id = 1000 + rng() % 24;
        const unsigned what = rng() % 10;
        if (what < 2) {
            c.remove(id);
        } else {
            const std::uint64_t va = bases[rng() % 4] + (rng() % 0x40) * 0x4000 + (rng() % 3 ? 0 : rng() % 0x4000);
            const std::uint64_t size = sizes[rng() % 7];
            if (what == 2) c.add_with_layout(id, image(0x900 + id, va, size));
            else if (what == 3) c.add(id, buffer(rng() % 2 ? 0x800 + id : 0, rng() % 2 ? va : 0, rng() % 2 ? size : 0));
            else if (what == 4) c.add_sparse(id, buffer(0x800 + id, va, size, rng() % 0x1000));
            else c.add(id, buffer(0x800 + rng() % 4, va, size, rng() % 0x100000));
        }
        c.probe_all("random churn");
        for (int i = 0; i < 16; ++i) {
            const std::uint64_t va = bases[rng() % 4] + rng() % 0x110000;
            c.probe(va, rng() % 3 ? rng() % 0x20000 : rng(), "random churn, random address");
        }
    }
    for (ResourceId id = 1000; id < 1024; ++id) c.remove(id);
    c.probe_all("random churn, all removed");
}

} // namespace

int main() {
    Check c;
    struct Part { const char* name; std::uint64_t probes, hits, mismatches; };
    std::vector<Part> parts;
    std::uint64_t p = 0, h = 0, m = 0;
    const auto done = [&](const char* name) {
        parts.push_back({name, c.probes - p, c.hits - h, c.mismatches - m});
        p = c.probes, h = c.hits, m = c.mismatches;
    };
    lifetime(c);
    done("lifetime reuse");
    clipping(c);
    done("clipping and aliasing");
    high_va(c);
    done("high-VA boundaries");
    for (unsigned seed = 1; seed <= 20; ++seed) churn(c, seed, 400);
    done("random churn (20 seeds x 400 operations)");
    for (const Part& part : parts)
        std::printf("%-42s %9llu probes, %8llu hits, %llu mismatches\n", part.name,
                    static_cast<unsigned long long>(part.probes), static_cast<unsigned long long>(part.hits),
                    static_cast<unsigned long long>(part.mismatches));
    std::printf("index after everything was removed: %zu ranges, longest %llu\n", c.context.buffer_vas_.size(),
                static_cast<unsigned long long>(c.context.buffer_vas_.longest()));
    const bool ok = !c.mismatches && !c.context.buffer_vas_.size() && !c.context.buffer_vas_.longest();
    std::printf("%s: %llu probes, %llu mismatches\n", ok ? "OK" : "FAILED", static_cast<unsigned long long>(c.probes),
                static_cast<unsigned long long>(c.mismatches));
    return ok ? 0 : 1;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants