upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-26 14:47:29 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-26 14:47:29 -0500
commit84db5cd02736759eab9ffb4deedc98c52027c050 (patch)
tree115e98973ad46f1c4494eeaa991b8df358a3e88d /runtime/src
parent2d43417d49fdd8f2d8241f75ea8fd0cdd8811137 (diff)
d3d12: console heap slots record what their V#s resolved to; a release re-fixes only the slots naming it (RT-VSHARP-SLOT-RECORDS)
After any arena release, title-window or geometry block destroyed, or alias change, the next submission walked every live V# slot of the console heap (about 580,000 in world runs), reading each from the copy in ReBAR VRAM: 1.1-1.5 s a walk whatever the scene, about 2.9 s of a 4.6 s frame. It existed only because nothing recorded which slot resolved into which backing. Each V# half of a console resource heap's copy now has a record in host RAM (src/console_heap_slot_records.h): the title's base and span, the device address its copy names, and whether it resolved or waits. Two indexes (by base, by target; per power-of-two span class and 64 KiB-or-larger granule) find the halves near a range. fix_console_slot, the only writer of a slot's copy, writes them; a zeroed range, a deferred slot and a rewritten slot drop theirs; a destroyed heap takes them with it. Releases (backing(), title_block_gone), alias ranges removed or replaced (TitleVaAliases tells its listeners as it happens, forget_copy included) and additions (backings, alias ranges, title memory) go on an unbounded per-device list. refresh_console_heaps takes it whole; every heap re-fixes exactly the slots it touches: a release or removal every half naming the range, an addition the waiting halves over it. A new heap log line gives the changes, slots looked at, slots fixed again and ms per submission. Removed: the live_vsharps walk and its bitset (console_heap_vsharp_slots.h and its test), the release generation checks (released_backings, TitleVaAliases::invalidations), LEONIDA_CONSOLE_RELEASE_FILTER, the 4,096-entry DescriptorRangeChanges ring with its full-sweep overflow and changed_ranges(), the empty-slot probe and retry_unmapped_slots (unreachable: nothing set its flag). LEONIDA_CONSOLE_GPU_FILTER now defaults to unset instead of the removed variable's value. The T# retries (retry_console_slots) stay. Tests: console_heap_slot_records_test (portable): releasing a buffer 10 of 60,010 slots name looks at 10 entries and fixes 10 slots; an alias moved, removed and added back; overwritten and zeroed slots; partial overlap; two slots on one backing; a buffer back; a refused alias copy backed later; a large span; a destroyed heap; and 400 random rounds compared with a full re-resolution of every slot. d3d12_unmapped_vsharp_test now expects all 128 waiting slots restored at the first submission after their alias comes (was: 16 by the probe in 64 submissions), none after it goes, and the slots naming a released buffer null. title_va_alias_test and geometry_views_test check the listener in place of the ring. Linux ctest 113/113; Windows suite under Wine (clang-cl, iGPU, RADV) equal to main 2d43417d4 test by test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/console_heap_slot_records.h227
-rw-r--r--runtime/src/console_heap_vsharp_slots.h115
-rw-r--r--runtime/src/descriptor_range_changes.h46
-rw-r--r--runtime/src/title_va_alias.h47
4 files changed, 258 insertions, 177 deletions
diff --git a/runtime/src/console_heap_slot_records.h b/runtime/src/console_heap_slot_records.h
new file mode 100644
index 000000000..4ab3c3b9d
--- /dev/null
+++ b/runtime/src/console_heap_slot_records.h
@@ -0,0 +1,227 @@
1#pragma once
2// What each buffer V# of a console resource heap's GPU copy resolved to (docs/d3d12_vulkan.md section 3.4), kept in
3// host RAM so that a change of the address space re-fixes exactly the slots it touches.
4//
5// A slot of the copy is the title's descriptor with its V# bases rewritten (DeviceState::fix_console_slot). What a
6// base became depends on things that change after the slot was written: a buffer or window released, an alias range
7// removed, a geometry copy retired, or (for a base nothing backed yet) a buffer, alias or title memory added. Without
8// a record of which slot resolved into which range, a change could only be applied by walking every live slot. Here
9// each V# half (the buffer V# and the UAV counter V# of a slot) records:
10// - base and span: the bytes the title's V# names, [base, base + span) (the base is the V#'s 48 bits);
11// - target: the device address its GPU copy names, [target, target + span); for a half that resolved to nothing,
12// the device address of a copy that was found but refused (not backed yet), or 0;
13// - state: resolved, waiting (written with no base and no records until something backs it) or none.
14// Two indexes find the halves a change touches: by base ("source") and by target. Each holds a half once, under the
15// power-of-two class of its span and the granule of its start (a granule is at least 64 KiB and at least the class),
16// so a range [lo, hi) is answered by visiting, per class in use, the granules from lo - 2^class to hi: the cost is the
17// halves near the range, never the heap. An entry is checked against the record when visited (a half that moved
18// leaves a stale entry behind; a bucket drops its stale entries whenever it has doubled since it was last cleaned).
19// Portable, standard library only: console_heap_slot_records_test exercises it without a GPU.
20#include <algorithm>
21#include <array>
22#include <bit>
23#include <cstddef>
24#include <cstdint>
25#include <cstdlib>
26#include <memory>
27#include <unordered_map>
28#include <vector>
29
30namespace leonida {
31
32// One change since the last submission, as a range; hi is exclusive and greater than lo.
33struct SlotChange {
34 enum Kind : std::uint8_t {
35 target_gone, // device addresses: a backing released, a copy's block destroyed, an alias range's copy gone
36 source_gone, // V# bases: an alias range removed or replaced, or a copy that answered for it gone
37 target_added, // device addresses: a backing added (a refused alias target may be backed now)
38 source_added, // V# bases: an alias range or title memory added, or a backing added at those arena offsets
39 };
40 Kind kind;
41 std::uint64_t lo, hi;
42};
43
44class ConsoleHeapSlotRecords {
45public:
46 enum State : std::uint8_t { none = 0, resolved = 1, waiting = 2 };
47
48 void reset(std::size_t slots) {
49 slots_ = slots;
50 // calloc: the pages of slots never written are never touched (the retail heap uses a tenth of its slots).
51 halves_.reset(slots ? static_cast<Half*>(std::calloc(slots * 2, sizeof(Half))) : nullptr);
52 if (slots && !halves_) slots_ = 0;
53 for (auto& index : indexes_) index = Index{};
54 recorded_ = waiting_ = 0;
55 looked_at_ = 0;
56 }
57 std::size_t slots() const { return slots_; }
58 std::size_t recorded() const { return recorded_; } // halves in state resolved or waiting
59 std::size_t waiting_count() const { return waiting_; } // halves in state waiting
60 std::uint64_t looked_at() const { return looked_at_; } // index entries visited by touched(), all calls
61
62 // Half `half` (0: the buffer V#, 1: the UAV counter V#) of `slot` now names [base, base + span) and resolved as
63 // `state` says, its copy at `target` (see above). span 0 counts as 1.
64 void set(std::size_t slot, unsigned half, State state, std::uint64_t base, std::uint64_t span,
65 std::uint64_t target) {
66 if (slot >= slots_ || half > 1) return;
67 if (state == none) base = span = target = 0;
68 if (!span) span = 1;
69 if (span > kMaxSpan) span = kMaxSpan;
70 const std::size_t key = slot * 2 + half;
71 Half& h = halves_[key];
72 const Half old = h;
73 count(old.state(), -1);
74 h.base = base;
75 h.target = target;
76 h.span_state = span | (std::uint64_t(state) << 56);
77 count(state, +1);
78 if (state == none) return; // entries left behind are stale now
79 const auto add = [&](int which, std::uint64_t start, std::uint64_t old_start) {
80 const unsigned c = span_class(span);
81 const std::uint64_t granule = start >> granule_shift(c);
82 // Unchanged key: the entry already there stands for it.
83 if (old.state() != none && (which == kSource || old.target) && span_class(old.span()) == c &&
84 (old_start >> granule_shift(c)) == granule)
85 return;
86 push(which, c, granule, std::uint32_t(key));
87 };
88 add(kSource, base, old.base);
89 if (target) add(kTarget, target, old.target);
90 }
91
92 void clear(std::size_t slot) {
93 set(slot, 0, none, 0, 0, 0);
94 set(slot, 1, none, 0, 0, 0);
95 }
96 void clear_range(std::size_t first, std::size_t end) {
97 end = (std::min)(end, slots_);
98 for (std::size_t slot = first; slot < end; ++slot)
99 for (unsigned half = 0; half < 2; ++half)
100 if (halves_[slot * 2 + half].state() != none) set(slot, half, none, 0, 0, 0);
101 }
102
103 State state(std::size_t slot, unsigned half) const {
104 return slot < slots_ && half < 2 ? halves_[slot * 2 + half].state() : none;
105 }
106 std::uint64_t target(std::size_t slot, unsigned half) const {
107 return slot < slots_ && half < 2 ? halves_[slot * 2 + half].target : 0;
108 }
109
110 // The slots `changes` touch, each once, ascending, appended to `out` (cleared first):
111 // target_gone: halves whose [target, target + span) overlaps the range (whatever their state);
112 // source_gone: halves whose [base, base + span) overlaps it;
113 // target_added, source_added: the same, waiting halves only (a resolved one stays valid until something goes).
114 void touched(const SlotChange* changes, std::size_t count, std::vector<std::uint32_t>& out) {
115 out.clear();
116 for (std::size_t i = 0; i < count; ++i) {
117 const SlotChange& change = changes[i];
118 if (change.hi <= change.lo) continue;
119 const bool target = change.kind == SlotChange::target_gone || change.kind == SlotChange::target_added;
120 const bool waiting_only = change.kind == SlotChange::target_added || change.kind == SlotChange::source_added;
121 find(target ? kTarget : kSource, change.lo, change.hi, waiting_only, out);
122 }
123 std::sort(out.begin(), out.end());
124 out.erase(std::unique(out.begin(), out.end()), out.end());
125 }
126
127private:
128 static constexpr int kSource = 0, kTarget = 1;
129 static constexpr std::uint64_t kMaxSpan = (std::uint64_t(1) << 56) - 1;
130 static constexpr unsigned kMinGranule = 16; // 64 KiB
131 static constexpr unsigned kClasses = 57;
132
133 struct Half {
134 std::uint64_t base, target, span_state;
135 std::uint64_t span() const { return span_state & kMaxSpan; }
136 State state() const { return State(span_state >> 56); }
137 };
138 struct Free {
139 void operator()(Half* p) const { std::free(p); }
140 };
141 struct Bucket {
142 std::vector<std::uint32_t> keys;
143 std::size_t clean = 0; // its size when it was last cleaned
144 };
145 struct Index {
146 std::array<std::unordered_map<std::uint64_t, Bucket>, kClasses> classes;
147 std::uint64_t used = 0; // a bit per class that ever held an entry
148 };
149
150 // The smallest c with span <= 2^c.
151 static unsigned span_class(std::uint64_t span) {
152 return span <= 1 ? 0u : unsigned(64 - std::countl_zero(span - 1));
153 }
154 static unsigned granule_shift(unsigned c) { return c < kMinGranule ? kMinGranule : c; }
155
156 void count(State state, int delta) {
157 if (state != none) recorded_ += std::size_t(std::ptrdiff_t(delta));
158 if (state == waiting) waiting_ += std::size_t(std::ptrdiff_t(delta));
159 }
160
161 // Whether index `which` still holds `key` under (c, granule).
162 bool current(int which, std::uint32_t key, unsigned c, std::uint64_t granule) const {
163 const Half& h = halves_[key];
164 if (h.state() == none || span_class(h.span()) != c) return false;
165 if (which == kTarget && !h.target) return false;
166 return ((which == kSource ? h.base : h.target) >> granule_shift(c)) == granule;
167 }
168
169 void push(int which, unsigned c, std::uint64_t granule, std::uint32_t key) {
170 Index& index = indexes_[which];
171 index.used |= std::uint64_t(1) << c;
172 Bucket& bucket = index.classes[c][granule];
173 bucket.keys.push_back(key);
174 if (bucket.keys.size() < 32 || bucket.keys.size() < 2 * bucket.clean) return;
175 auto& keys = bucket.keys;
176 keys.erase(std::remove_if(keys.begin(), keys.end(),
177 [&](std::uint32_t k) { return !current(which, k, c, granule); }),
178 keys.end());
179 std::sort(keys.begin(), keys.end());
180 keys.erase(std::unique(keys.begin(), keys.end()), keys.end());
181 bucket.clean = keys.size();
182 }
183
184 void find(int which, std::uint64_t lo, std::uint64_t hi, bool waiting_only, std::vector<std::uint32_t>& out) {
185 Index& index = indexes_[which];
186 for (std::uint64_t used = index.used; used; used &= used - 1) {
187 const unsigned c = unsigned(std::countr_zero(used));
188 auto& buckets = index.classes[c];
189 if (buckets.empty()) continue;
190 const unsigned shift = granule_shift(c);
191 // A half of this class overlaps [lo, hi) only if it starts in (lo - 2^c, hi).
192 const std::uint64_t reach = std::uint64_t(1) << c;
193 const std::uint64_t first = (lo >= reach ? lo - reach + 1 : 0) >> shift;
194 const std::uint64_t last = (hi - 1) >> shift;
195 const auto visit = [&](std::uint64_t granule, const Bucket& bucket) {
196 for (const std::uint32_t key : bucket.keys) {
197 ++looked_at_;
198 if (!current(which, key, c, granule)) continue;
199 const Half& h = halves_[key];
200 if (waiting_only && h.state() != waiting) continue;
201 const std::uint64_t start = which == kSource ? h.base : h.target;
202 const std::uint64_t span = h.span();
203 const std::uint64_t end = start + span < start ? UINT64_MAX : start + span;
204 if (start < hi && end > lo) out.push_back(key >> 1);
205 }
206 };
207 if (last - first >= buckets.size()) {
208 for (const auto& [granule, bucket] : buckets)
209 if (granule >= first && granule <= last) visit(granule, bucket);
210 } else {
211 for (std::uint64_t granule = first;; ++granule) {
212 const auto it = buckets.find(granule);
213 if (it != buckets.end()) visit(granule, it->second);
214 if (granule == last) break;
215 }
216 }
217 }
218 }
219
220 std::size_t slots_ = 0;
221 std::unique_ptr<Half[], Free> halves_;
222 std::array<Index, 2> indexes_;
223 std::size_t recorded_ = 0, waiting_ = 0;
224 std::uint64_t looked_at_ = 0;
225};
226
227} // namespace leonida
diff --git a/runtime/src/console_heap_vsharp_slots.h b/runtime/src/console_heap_vsharp_slots.h
deleted file mode 100644
index 0b0830053..000000000
--- a/runtime/src/console_heap_vsharp_slots.h
+++ /dev/null
@@ -1,115 +0,0 @@
1#pragma once
2// Host-RAM bitset of console resource-heap slots whose GPU copy (`heap.copy`) currently holds a live buffer V#
3// (`!(w[3] >> 30) && (w[2] || w[6])`).
4//
5// When a buffer backing or title VA alias is released, `refresh_console_heap` must re-run `fix_console_slot` on every
6// slot that might still point at the released allocation. Scanning `heap.copy` linearly reads every 32-byte slot of
7// the heap (4-5.5+ MiB): when `heap.copy` sits in `arena.mapped` (uncached write-combined GPU memory), each release
8// triggers ~180k uncached PCIe reads. Tracking the live V# slots in host RAM keeps invalidation scans strictly in CPU
9// cache (zero reads from `heap.copy`) and skips empty and T# slots 64 at a time.
10
11#include <algorithm>
12#include <bit>
13#include <cstddef>
14#include <cstdint>
15#include <vector>
16
17namespace leonida {
18
19class ConsoleHeapVsharpSlots {
20public:
21 // Matches the descriptor predicate for a non-empty buffer V# (primary or counter half) in a 32-byte slot.
22 static constexpr bool is_live_vsharp(const std::uint32_t* w) noexcept {
23 return !(w[3] >> 30) && (w[2] || w[6]);
24 }
25
26 void reset(std::size_t slot_count) {
27 slot_count_ = slot_count;
28 live_count_ = 0;
29 words_.assign((slot_count + 63) / 64, 0);
30 }
31
32 void set(std::size_t slot, bool live) noexcept {
33 if (slot >= slot_count_) return;
34 std::uint64_t& word = words_[slot >> 6];
35 const std::uint64_t mask = std::uint64_t{1} << (slot & 63);
36 const bool was = (word & mask) != 0;
37 if (live == was) return;
38 if (live) {
39 word |= mask;
40 ++live_count_;
41 } else {
42 word &= ~mask;
43 --live_count_;
44 }
45 }
46
47 void clear(std::size_t slot) noexcept { set(slot, false); }
48
49 // Clears every slot in [first, end), clamping to slot_count().
50 void clear_range(std::size_t first, std::size_t end) noexcept {
51 if (first >= end || first >= slot_count_ || live_count_ == 0) return;
52 end = (std::min)(end, slot_count_);
53 std::size_t w = first >> 6;
54 const std::size_t last_w = (end - 1) >> 6;
55 const unsigned first_bit = static_cast<unsigned>(first & 63);
56 const unsigned end_bit = static_cast<unsigned>(end & 63);
57 const std::uint64_t head_mask = ~std::uint64_t{0} << first_bit;
58 const std::uint64_t tail_mask = end_bit ? ((std::uint64_t{1} << end_bit) - 1) : ~std::uint64_t{0};
59 if (w == last_w) {
60 const std::uint64_t mask = head_mask & tail_mask;
61 const std::uint64_t cleared = words_[w] & mask;
62 if (cleared) {
63 words_[w] &= ~mask;
64 live_count_ -= static_cast<std::size_t>(std::popcount(cleared));
65 }
66 return;
67 }
68 if (const std::uint64_t cleared = words_[w] & head_mask) {
69 words_[w] &= ~head_mask;
70 live_count_ -= static_cast<std::size_t>(std::popcount(cleared));
71 }
72 for (++w; w < last_w; ++w) {
73 if (const std::uint64_t cleared = words_[w]) {
74 words_[w] = 0;
75 live_count_ -= static_cast<std::size_t>(std::popcount(cleared));
76 }
77 }
78 if (const std::uint64_t cleared = words_[last_w] & tail_mask) {
79 words_[last_w] &= ~tail_mask;
80 live_count_ -= static_cast<std::size_t>(std::popcount(cleared));
81 }
82 }
83
84 // Calls fn(slot) in ascending slot order for every set bit present when its 64-slot word is entered.
85 // Safe if fn mutates the bit for `slot` (e.g., fix_console_slot clearing an invalidated V#).
86 template <class F>
87 void for_each(F&& fn) const {
88 if (live_count_ == 0) return;
89 for (std::size_t w = 0; w < words_.size(); ++w) {
90 std::uint64_t bits = words_[w];
91 if (!bits) continue;
92 const std::size_t base = w << 6;
93 while (bits) {
94 const unsigned bit = static_cast<unsigned>(std::countr_zero(bits));
95 bits &= bits - 1;
96 fn(base + bit);
97 }
98 }
99 }
100
101 bool test(std::size_t slot) const noexcept {
102 return slot < slot_count_ && ((words_[slot >> 6] >> (slot & 63)) & 1u) != 0;
103 }
104
105 std::size_t slot_count() const noexcept { return slot_count_; }
106 std::size_t live_count() const noexcept { return live_count_; }
107 bool empty() const noexcept { return live_count_ == 0; }
108
109private:
110 std::size_t slot_count_ = 0;
111 std::size_t live_count_ = 0;
112 std::vector<std::uint64_t> words_;
113};
114
115} // namespace leonida
diff --git a/runtime/src/descriptor_range_changes.h b/runtime/src/descriptor_range_changes.h
deleted file mode 100644
index 5a4d7717f..000000000
--- a/runtime/src/descriptor_range_changes.h
+++ /dev/null
@@ -1,46 +0,0 @@
1#pragma once
2#include <algorithm>
3#include <array>
4#include <cstdint>
5#include <vector>
6
7namespace leonida {
8// A separate cursor per console heap. The owning backing/alias registry locks record() and read().
9struct DescriptorRanges {
10 struct Range { uint64_t first, last; }; // inclusive, including UINT64_MAX
11 std::vector<Range> ranges;
12 void merge() {
13 std::sort(ranges.begin(), ranges.end(), [](auto a, auto b) { return a.first < b.first; });
14 size_t n = 0;
15 for (auto r : ranges) {
16 if (n && r.first <= ranges[n-1].last)
17 ranges[n-1].last = (std::max)(ranges[n-1].last, r.last);
18 else ranges[n++] = r;
19 }
20 ranges.resize(n);
21 }
22 bool overlaps(uint64_t base, uint64_t bytes) const {
23 if (!bytes) return false;
24 auto it = std::lower_bound(ranges.begin(), ranges.end(), base,
25 [](auto r, uint64_t v) { return r.last < v; });
26 return it != ranges.end() && (it->first <= base || it->first - base < bytes);
27 }
28};
29class DescriptorRangeChanges {
30 std::array<DescriptorRanges::Range, 4096> ring_{};
31 uint64_t serial_{};
32public:
33 void record(uint64_t start, uint64_t bytes) {
34 if (bytes) {
35 ring_[serial_++ % ring_.size()] = {start, start + (std::min)(UINT64_MAX-start, bytes-1)};
36 }
37 }
38 bool read(uint64_t& cursor, DescriptorRanges& out) const {
39 const auto previous = cursor;
40 cursor = serial_;
41 if (serial_ - previous > ring_.size()) return false;
42 for (auto i = previous; i != serial_; ++i) out.ranges.push_back(ring_[i % ring_.size()]);
43 return true;
44 }
45};
46}
diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h
index 66a7f5894..c49880d92 100644
--- a/runtime/src/title_va_alias.h
+++ b/runtime/src/title_va_alias.h
@@ -16,7 +16,6 @@
16// that makes a GPU copy for an address in the title's memory that has none yet, and a scanner that rewrites the 16// that makes a GPU copy for an address in the title's memory that has none yet, and a scanner that rewrites the
17// buffer V#s of a bound descriptor table before a submission. Without hooks the table only translates what was 17// buffer V#s of a bound descriptor table before a submission. Without hooks the table only translates what was
18// added to it, so it is tested without a GPU (title_va_alias_test). 18// added to it, so it is tested without a GPU (title_va_alias_test).
19#include "descriptor_range_changes.h"
20#include <algorithm> 19#include <algorithm>
21#include "buffer_va_index.h" 20#include "buffer_va_index.h"
22 21
@@ -55,7 +54,7 @@ public:
55 if (!bytes || title_va > UINT64_MAX - bytes) return false; 54 if (!bytes || title_va > UINT64_MAX - bytes) return false;
56 std::unique_lock lock(mutex_); 55 std::unique_lock lock(mutex_);
57 erase_overlapping(title_va, title_va + bytes); 56 erase_overlapping(title_va, title_va + bytes);
58 changes_.record(title_va, bytes); 57 notify(Change::added, title_va, bytes, shader_va);
59 ranges_[title_va] = {title_va + bytes, shader_va}; 58 ranges_[title_va] = {title_va + bytes, shader_va};
60 by_shader_.insert(shader_va, bytes, title_va); 59 by_shader_.insert(shader_va, bytes, title_va);
61 count_.store(ranges_.size(), std::memory_order_release); 60 count_.store(ranges_.size(), std::memory_order_release);
@@ -77,11 +76,10 @@ public:
77 std::unique_lock lock(mutex_); 76 std::unique_lock lock(mutex_);
78 const auto it = ranges_.find(title_va); 77 const auto it = ranges_.find(title_va);
79 if (it != ranges_.end() && it->second.shader_va == shader_va) { 78 if (it != ranges_.end() && it->second.shader_va == shader_va) {
80 changes_.record(it->first, it->second.end - it->first); 79 notify(Change::removed, it->first, it->second.end - it->first, shader_va);
81 by_shader_.erase(shader_va, title_va); 80 by_shader_.erase(shader_va, title_va);
82 note_removed(it->second.shader_va, it->second.end - it->first); 81 note_removed(it->second.shader_va, it->second.end - it->first);
83 ranges_.erase(it); 82 ranges_.erase(it);
84 invalidations_.fetch_add(1, std::memory_order_release);
85 generation_.fetch_add(1, std::memory_order_release); 83 generation_.fetch_add(1, std::memory_order_release);
86 } 84 }
87 count_.store(ranges_.size(), std::memory_order_release); 85 count_.store(ranges_.size(), std::memory_order_release);
@@ -89,14 +87,13 @@ public:
89 87
90 // A copy that answered for [title_va, title_va + bytes) at shader_va went, whether or not it had a range here (a 88 // A copy that answered for [title_va, title_va + bytes) at shader_va went, whether or not it had a range here (a
91 // geometry copy that vsharp_address or a placed view reached through GeometryViews directly has none): what was 89 // geometry copy that vsharp_address or a placed view reached through GeometryViews directly has none): what was
92 // translated through it is stale. Recorded as a removal would be: the console heaps translate the slots in the 90 // translated through it is stale. Told as a removal is: the console heaps fix the slots that resolved through
93 // range again (invalidations, changed_ranges), and the GPU key table drops answers into shader_va (take_removed). 91 // either side of it again (the listeners), and the GPU key table drops answers into shader_va (take_removed).
94 void forget_copy(std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) { 92 void forget_copy(std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) {
95 if (!bytes) return; 93 if (!bytes) return;
96 std::unique_lock lock(mutex_); 94 std::unique_lock lock(mutex_);
97 changes_.record(title_va, bytes); 95 notify(Change::removed, title_va, bytes, shader_va);
98 note_removed(shader_va, bytes); 96 note_removed(shader_va, bytes);
99 invalidations_.fetch_add(1, std::memory_order_release);
100 generation_.fetch_add(1, std::memory_order_release); 97 generation_.fetch_add(1, std::memory_order_release);
101 } 98 }
102 99
@@ -259,6 +256,7 @@ public:
259 } 256 }
260 memory_[begin] = end; 257 memory_[begin] = end;
261 memory_generation_.fetch_add(1, std::memory_order_release); 258 memory_generation_.fetch_add(1, std::memory_order_release);
259 notify(Change::memory_added, base, bytes, 0);
262 } 260 }
263 void remove_title_memory(std::uint64_t base) { 261 void remove_title_memory(std::uint64_t base) {
264 std::unique_lock lock(memory_mutex_); 262 std::unique_lock lock(memory_mutex_);
@@ -373,10 +371,23 @@ public:
373 } 371 }
374 372
375 std::size_t size() const { return count_.load(std::memory_order_acquire); } 373 std::size_t size() const { return count_.load(std::memory_order_acquire); }
376 std::uint64_t invalidations() const { return invalidations_.load(std::memory_order_acquire); } 374
377 bool changed_ranges(uint64_t& cursor, DescriptorRanges& ranges) const { 375 // What changed, told as it happens to every listener (a device whose console heaps record what each descriptor
378 std::shared_lock lock(mutex_); 376 // resolved to, src/console_heap_slot_records.h): [title_va, title_va + bytes) reached at shader_va was added, or
379 return changes_.read(cursor, ranges); 377 // was removed or replaced (remove, an overlapping add, forget_copy: what resolved through it is stale), or title
378 // memory was added (shader_va 0: a copy may now be made for an address that had none). Called with the table's
379 // lock held, so a listener only records and never calls back into the table. remove_listener returns once no call
380 // to that listener is in progress.
381 enum class Change : unsigned { added, removed, memory_added };
382 using Listener = void (*)(void* context, Change change, std::uint64_t title_va, std::uint64_t bytes,
383 std::uint64_t shader_va);
384 void add_listener(void* context, Listener listener) {
385 std::unique_lock lock(listener_mutex_);
386 listeners_.emplace_back(context, listener);
387 }
388 void remove_listener(void* context) {
389 std::unique_lock lock(listener_mutex_);
390 std::erase_if(listeners_, [context](const auto& l) { return l.first == context; });
380 } 391 }
381 // Bumped by every add and every removal: a copy of mappings() is current while it has not moved. 392 // Bumped by every add and every removal: a copy of mappings() is current while it has not moved.
382 std::uint64_t generation() const { return generation_.load(std::memory_order_acquire); } 393 std::uint64_t generation() const { return generation_.load(std::memory_order_acquire); }
@@ -418,9 +429,8 @@ private:
418 auto previous = std::prev(it); 429 auto previous = std::prev(it);
419 if (previous->second.end > begin) it = previous; 430 if (previous->second.end > begin) it = previous;
420 } 431 }
421 if (it != ranges_.end() && it->first < end) invalidations_.fetch_add(1, std::memory_order_release);
422 while (it != ranges_.end() && it->first < end) { 432 while (it != ranges_.end() && it->first < end) {
423 changes_.record(it->first, it->second.end - it->first); 433 notify(Change::removed, it->first, it->second.end - it->first, it->second.shader_va);
424 by_shader_.erase(it->second.shader_va, it->first); 434 by_shader_.erase(it->second.shader_va, it->first);
425 note_removed(it->second.shader_va, it->second.end - it->first); 435 note_removed(it->second.shader_va, it->second.end - it->first);
426 it = ranges_.erase(it); 436 it = ranges_.erase(it);
@@ -432,12 +442,17 @@ private:
432 if (record_removals_.load(std::memory_order_relaxed)) removed_.push_back({shader_va, bytes}); 442 if (record_removals_.load(std::memory_order_relaxed)) removed_.push_back({shader_va, bytes});
433 } 443 }
434 444
435 DescriptorRangeChanges changes_; 445 void notify(Change change, std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) const {
446 std::shared_lock lock(listener_mutex_);
447 for (const auto& [context, listener] : listeners_) listener(context, change, title_va, bytes, shader_va);
448 }
449
450 mutable std::shared_mutex listener_mutex_; // taken inside mutex_ and memory_mutex_, never the other way
451 std::vector<std::pair<void*, Listener>> listeners_;
436 mutable std::shared_mutex mutex_; 452 mutable std::shared_mutex mutex_;
437 std::map<std::uint64_t, Range> ranges_; // by title VA 453 std::map<std::uint64_t, Range> ranges_; // by title VA
438 BufferVaIndex<std::uint64_t> by_shader_; // the same ranges by shader VA (id: the title VA); copies may overlap 454 BufferVaIndex<std::uint64_t> by_shader_; // the same ranges by shader VA (id: the title VA); copies may overlap
439 std::atomic<std::size_t> count_{0}; 455 std::atomic<std::size_t> count_{0};
440 std::atomic<std::uint64_t> invalidations_{};
441 std::atomic<std::uint64_t> generation_{}; 456 std::atomic<std::uint64_t> generation_{};
442 std::atomic<bool> record_removals_{false}; 457 std::atomic<bool> record_removals_{false};
443 std::vector<std::pair<std::uint64_t, std::uint64_t>> removed_; // (shader VA, bytes), when recorded 458 std::vector<std::pair<std::uint64_t, std::uint64_t>> removed_; // (shader VA, bytes), when recorded